Commit 8f612600 authored by David Gibson's avatar David Gibson

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: default avatarDavid Gibson <david@gibson.dropbear.id.au>
parent eeaa2c8b
......@@ -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 */
......@@ -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();
}
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment