From e7a752458f95c7ea1f15a2788a5709c213efd902 Mon Sep 17 00:00:00 2001 From: starnakin Date: Sun, 18 Jun 2023 18:06:17 +0200 Subject: [PATCH] add: strndup --- src/strndup.🗿 | 16 ++++++++++++++++ tests/strndup.🗿 | 21 +++++++++++++++++++++ 2 files changed, 37 insertions(+) create mode 100644 src/strndup.🗿 create mode 100644 tests/strndup.🗿 diff --git a/src/strndup.🗿 b/src/strndup.🗿 new file mode 100644 index 0000000..a4594a6 --- /dev/null +++ b/src/strndup.🗿 @@ -0,0 +1,16 @@ +strndup(str, n) +{ + local i = 0; + local out; + local size; + + size = strlen(str); + if (size > n) + size = n; + out = galloc(size + 1); + if (out == 0) + return (0); + [out + size] = 0; + strncpy(out, str, size); + return (out); +} diff --git a/tests/strndup.🗿 b/tests/strndup.🗿 new file mode 100644 index 0000000..c31e138 --- /dev/null +++ b/tests/strndup.🗿 @@ -0,0 +1,21 @@ +main() +{ + local ptr; + name = "strndup"; + + ptr = strndup("bozoman", 7); + test_str(ptr, "bozoman", ""); + free(ptr); + + ptr = strndup("bozoman", 4); + test_str(ptr, "bozo", ""); + free(ptr); + + ptr = strndup("bozoman", 10); + test_str(ptr, "bozoman", ""); + free(ptr); + + ptr = strndup("bozoman", 0); + test_str(ptr, "", ""); + free(ptr); +}