Skip to content

Commit 2158f48

Browse files
theob-prokartben
authored andcommitted
include: util: Add util_eq and util_memeq
`util_eq` compare two memory areas and their length. It returns true if they are equal, else false. `util_memeq` the first n bytes of two memory areas. It returns true if they are equal, else false. Signed-off-by: Théo Battrel <[email protected]>
1 parent 8d6ab28 commit 2158f48

File tree

1 file changed

+35
-0
lines changed

1 file changed

+35
-0
lines changed

include/zephyr/sys/util.h

Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -28,6 +28,7 @@
2828
#include <zephyr/types.h>
2929
#include <stddef.h>
3030
#include <stdint.h>
31+
#include <string.h>
3132

3233
/** @brief Number of bits that make up a type */
3334
#define NUM_BITS(t) (sizeof(t) * BITS_PER_BYTE)
@@ -783,6 +784,40 @@ static inline void mem_xor_128(uint8_t dst[16], const uint8_t src1[16], const ui
783784
mem_xor_n(dst, src1, src2, 16);
784785
}
785786

787+
/**
788+
* @brief Compare memory areas. The same way as `memcmp` it assume areas to be
789+
* the same length
790+
*
791+
* @param m1 First memory area to compare, cannot be NULL even if length is 0
792+
* @param m2 Second memory area to compare, cannot be NULL even if length is 0
793+
* @param n First n bytes of @p m1 and @p m2 to compares
794+
*
795+
* @returns true if the @p n first bytes of @p m1 and @p m2 are the same, else
796+
* false
797+
*/
798+
static inline bool util_memeq(const void *m1, const void *m2, size_t n)
799+
{
800+
return memcmp(m1, m2, n) == 0;
801+
}
802+
803+
/**
804+
* @brief Compare memory areas and their length
805+
*
806+
* If the length are 0, return true.
807+
*
808+
* @param m1 First memory area to compare, cannot be NULL even if length is 0
809+
* @param len1 Length of the first memory area to compare
810+
* @param m2 Second memory area to compare, cannot be NULL even if length is 0
811+
* @param len2 Length of the second memory area to compare
812+
*
813+
* @returns true if both the length of the memory areas and their content are
814+
* equal else false
815+
*/
816+
static inline bool util_eq(const void *m1, size_t len1, const void *m2, size_t len2)
817+
{
818+
return len1 == len2 && (m1 == m2 || util_memeq(m1, m2, len1));
819+
}
820+
786821
#ifdef __cplusplus
787822
}
788823
#endif

0 commit comments

Comments
 (0)