From 5fdb7d729e4678d532744a1361dc812faec7c163 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C3=89milie=20Feral?= Date: Fri, 23 Sep 2016 17:37:28 +0200 Subject: [PATCH] [liba] implement strlcpy Change-Id: I083129b31cbb070e8c1d87d7e3db91f8134e3540 --- liba/Makefile | 4 ++-- liba/include/string.h | 1 + liba/src/strlcpy.c | 14 ++++++++++++++ liba/test/strlcpy.c | 12 ++++++++++++ 4 files changed, 29 insertions(+), 2 deletions(-) create mode 100644 liba/src/strlcpy.c create mode 100644 liba/test/strlcpy.c diff --git a/liba/Makefile b/liba/Makefile index 92111d16f..4c903efa3 100644 --- a/liba/Makefile +++ b/liba/Makefile @@ -2,8 +2,8 @@ SFLAGS += -Iliba/include liba/src/external/sqlite/mem5.o: CFLAGS += -w -objs += $(addprefix liba/src/, assert.o errno.o malloc.o memcpy.o memset.o powf.o strcmp.o strlen.o external/sqlite/mem5.o) -tests += $(addprefix liba/test/, stdint.c) +objs += $(addprefix liba/src/, assert.o errno.o malloc.o memcpy.o memset.o powf.o strcmp.o strlcpy.o strlen.o external/sqlite/mem5.o) +tests += $(addprefix liba/test/, stdint.c strlcpy.c) # The use of aeabi-rt could be made conditional to an AEABI target. # In practice we're always using liba on such a target. diff --git a/liba/include/string.h b/liba/include/string.h index a12b90e5a..6c00070c0 100644 --- a/liba/include/string.h +++ b/liba/include/string.h @@ -10,6 +10,7 @@ void * memcpy(void * dst, const void * src, size_t n); void * memset(void * b, int c, size_t len); size_t strlen(const char * s); int strcmp(const char *s1, const char *s2); +size_t strlcpy(char * dst, const char * src, size_t len); LIBA_END_DECLS diff --git a/liba/src/strlcpy.c b/liba/src/strlcpy.c new file mode 100644 index 000000000..b3ab406b6 --- /dev/null +++ b/liba/src/strlcpy.c @@ -0,0 +1,14 @@ +#include + +size_t strlcpy(char * dst, const char * src, size_t len) { + if (len == 0) { + return 0; + } + const char * cur = src; + const char * end = src+len-1; + while (*cur != 0 && cur < end) { + *dst++ = *cur++; + } + *dst = 0; + return cur-src; +} diff --git a/liba/test/strlcpy.c b/liba/test/strlcpy.c new file mode 100644 index 000000000..aed30128c --- /dev/null +++ b/liba/test/strlcpy.c @@ -0,0 +1,12 @@ +#include +#include +#include + +QUIZ_CASE(liba_strlcpy) { + char * t = "Hello"; + char buffer[16]; + size_t result = strlcpy(buffer, t, 2); + assert(result == 1); + assert(buffer[0] == 'H'); + assert(buffer[1] == NULL); +}