Tests: Add tests for memmove and memcmp + correct our memcmp implementation

This commit is contained in:
apio 2022-10-22 19:04:19 +02:00
parent 8908faf6e2
commit 4725538aa7
3 changed files with 68 additions and 6 deletions

View File

@ -27,13 +27,15 @@ extern "C"
int memcmp(const void* a, const void* b, size_t n)
{
const char* _a = (const char*)a;
const char* _b = (const char*)b;
for (; n && _a == _b; n--, _a++, _b++)
;
if (!n) return 0;
if (*_a > *_b) return 1;
return -1;
const unsigned char* ap = (const unsigned char*)a;
const unsigned char* bp = (const unsigned char*)b;
while (--n && *ap == *bp)
{
ap++;
bp++;
}
return *ap - *bp;
}
void* memmove(void* dest, const void* src, size_t n)

View File

@ -4,6 +4,8 @@
DEFINE_TEST(memset);
DEFINE_TEST(memcpy);
DEFINE_TEST(memchr);
DEFINE_TEST(memcmp);
DEFINE_TEST(memmove);
DEFINE_TEST(strlen);
DEFINE_TEST(strnlen);
DEFINE_TEST(strcspn);
@ -26,6 +28,8 @@ int main()
RUN_TEST(memset);
RUN_TEST(memcpy);
RUN_TEST(memchr);
RUN_TEST(memcmp);
RUN_TEST(memmove);
RUN_TEST(strlen);
RUN_TEST(strnlen);
RUN_TEST(strcspn);

View File

@ -67,6 +67,62 @@ DEFINE_TEST(memchr)
TEST_SUCCESS();
}
DEFINE_TEST(memcmp)
{
START_TEST(memcmp);
char buf[20] = "abcdefghijklmnopqrs";
char buf2[20] = "abcdefghijklmnopqrp";
int val = memcmp(buf, buf, 20);
EXPECT_EQ(val, 0);
val = memcmp(buf, buf2, 20);
EXPECT(val > 0);
val = memcmp(buf2, buf, 20);
EXPECT(val < 0);
TEST_SUCCESS();
}
DEFINE_TEST(memmove)
{
START_TEST(memmove);
char buf[20] = "Nothing is going on";
const char* str = "Something is going!";
char* ptr = memmove(buf, str, 20);
EXPECT_EQ(ptr, buf);
for (int i = 0; i < 20; i++) { EXPECT_EQ(buf[i], str[i]); }
const char* new = "Well...";
ptr = memmove(buf, new, 7);
EXPECT_EQ(ptr, buf);
for (int i = 0; i < 7; i++) { EXPECT_EQ(buf[i], new[i]); }
for (int i = 7; i < 20; i++) { EXPECT_EQ(buf[i], str[i]); }
char newbuf[16] = "part_a is part_b";
char result[16] = "is part_b part_b";
ptr = memmove(newbuf, newbuf + 7, 9);
EXPECT_EQ(ptr, newbuf);
EXPECT(memcmp(newbuf, result, 16) == 0); // we have tested memcmp at this point
TEST_SUCCESS();
}
DEFINE_TEST(strlen)
{
START_TEST(strlen);