Browse Source

mem: Add function to check whether memory ranges overlap

The test is simple, but every time I do it by hand, I always spend ages
convincing myself it's actually correct.

Signed-off-by: David Gibson <david@gibson.dropbear.id.au>
David Gibson 10 years ago
parent
commit
8f6126000b
2 changed files with 39 additions and 1 deletions
  1. 17 0
      ccan/mem/mem.h
  2. 22 1
      ccan/mem/test/api.c

+ 17 - 0
ccan/mem/mem.h

@@ -200,4 +200,21 @@ static inline bool memends_str(const void *a, size_t al, const char *s)
 	return memends(a, al, s, strlen(s));
 }
 
+/**
+ * memoverlaps - Do two memory ranges overlap?
+ * @a: pointer to first memory range
+ * @al: length of first memory range
+ * @b: pointer to second memory range
+ * @al: length of second memory range
+ */
+CONST_FUNCTION
+static inline bool memoverlaps(const void *a_, size_t al,
+			       const void *b_, size_t bl)
+{
+	const char *a = a_;
+	const char *b = b_;
+
+	return (a < (b + bl)) && (b < (a + al));
+}
+
 #endif /* CCAN_MEM_H */

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

@@ -11,7 +11,7 @@ int main(void)
 	char scan2[] = "\0\0\0b";
 
 	/* This is how many tests you plan to run */
-	plan_tests(46);
+	plan_tests(60);
 
 	ok1(memmem(haystack1, sizeof(haystack1), needle1, 2) == haystack1);
 	ok1(memmem(haystack1, sizeof(haystack1), needle1, 3) == NULL);
@@ -75,6 +75,27 @@ int main(void)
 	ok1(!memends_str(S("a\0bcdef"), "a"));
 	ok1(memends_str(S("a\0bcdef"), "ef"));
 
+	ok1(!memoverlaps(haystack1, sizeof(haystack1),
+			 haystack2, sizeof(haystack2)));
+	ok1(!memoverlaps(haystack2, sizeof(haystack2),
+			 haystack1, sizeof(haystack1)));
+	ok1(memoverlaps(haystack1, sizeof(haystack1), haystack1, 1));
+	ok1(memoverlaps(haystack1, 1, haystack1, sizeof(haystack1)));
+	ok1(memoverlaps(haystack1, sizeof(haystack1),
+			haystack1 + sizeof(haystack1) - 1, 1));
+	ok1(memoverlaps(haystack1 + sizeof(haystack1) - 1, 1,
+			haystack1, sizeof(haystack1)));
+	ok1(!memoverlaps(haystack1, sizeof(haystack1),
+			 haystack1 + sizeof(haystack1), 1));
+	ok1(!memoverlaps(haystack1 + sizeof(haystack1), 1,
+			 haystack1, sizeof(haystack1)));
+	ok1(!memoverlaps(haystack1, sizeof(haystack1), haystack1 - 1, 1));
+	ok1(!memoverlaps(haystack1 - 1, 1, haystack1, sizeof(haystack1)));
+	ok1(memoverlaps(haystack1, 5, haystack1 + 4, 7));
+	ok1(!memoverlaps(haystack1, 5, haystack1 + 5, 6));
+	ok1(memoverlaps(haystack1 + 4, 7, haystack1, 5));
+	ok1(!memoverlaps(haystack1 + 5, 6, haystack1, 5));
+
 	/* This exits depending on whether all tests passed */
 	return exit_status();
 }