Browse Source

mem: add memeqzero.

Signed-off-by: Rusty Russell <rusty@rustcorp.com.au>
Rusty Russell 10 years ago
parent
commit
299170fa67
3 changed files with 31 additions and 1 deletions
  1. 13 0
      ccan/mem/mem.c
  2. 13 0
      ccan/mem/mem.h
  3. 5 1
      ccan/mem/test/api.c

+ 13 - 0
ccan/mem/mem.c

@@ -88,3 +88,16 @@ void memswap(void *a, void *b, size_t n)
 		n -= m;
 	}
 }
+
+bool memeqzero(const void *data, size_t length)
+{
+	const unsigned char *p = data;
+
+	while (length) {
+		if (*p)
+			return false;
+		p++;
+		length--;
+	}
+	return true;
+}

+ 13 - 0
ccan/mem/mem.h

@@ -144,6 +144,19 @@ static inline bool memstarts(void const *data, size_t data_len,
  *	}
  */
 PURE_FUNCTION
+bool memeqzero(const void *data, size_t length);
+
+/**
+ * memeqzero - Is a byte array all zeroes?
+ * @data: byte array
+ * @length: length of @data in bytes
+ *
+ * Example:
+ *	if (memeqzero(somebytes, bytes_len)) {
+ *		printf("somebytes == 0!\n");
+ *	}
+ */
+PURE_FUNCTION
 static inline bool memeqstr(const void *data, size_t length, const char *string)
 {
 	return memeq(data, length, string, strlen(string));

+ 5 - 1
ccan/mem/test/api.c

@@ -18,7 +18,7 @@ int main(void)
 	char tmp1[SWAPSIZE], tmp2[SWAPSIZE];
 
 	/* This is how many tests you plan to run */
-	plan_tests(62);
+	plan_tests(65);
 
 	ok1(memmem(haystack1, sizeof(haystack1), needle1, 2) == haystack1);
 	ok1(memmem(haystack1, sizeof(haystack1), needle1, 3) == NULL);
@@ -113,6 +113,10 @@ int main(void)
 	ok1(memcmp(tmp1, haystack2, sizeof(haystack2)) == 0);
 	ok1(memcmp(tmp2, haystack1, sizeof(haystack1)) == 0);
 
+	ok1(memeqzero(NULL, 0));
+	ok1(memeqzero(scan2, 3));
+	ok1(!memeqzero(scan2, 4));
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }