From 13e1e4515746fe65b6c50cfbc42f00e29fd56599 Mon Sep 17 00:00:00 2001 From: Aqua-sama Date: Sat, 6 Feb 2021 17:32:40 +0200 Subject: libk: add some tests - merge types.h and type_traits.h --- libk/string/integerview.cc | 40 ++++++++++++++++++++++++++++++++++++++++ libk/string/string.cc | 26 ++++++++++++++++++++++++++ libk/string/test.cc | 14 ++++++++++++++ 3 files changed, 80 insertions(+) create mode 100644 libk/string/integerview.cc create mode 100644 libk/string/string.cc create mode 100644 libk/string/test.cc (limited to 'libk/string') diff --git a/libk/string/integerview.cc b/libk/string/integerview.cc new file mode 100644 index 0000000..beeb561 --- /dev/null +++ b/libk/string/integerview.cc @@ -0,0 +1,40 @@ +#include + +/* itoa: convert n to characters in s */ +template +constexpr size_t itoa(T n, char s[]) { + const bool is_negative = (n < 0); + if constexpr (!is_unsigned()) { + if (n < 0) + n = -n; + } + + int i = 0; + do { /* generate digits in reverse order */ + s[i++] = "0123456789abcdef"[n % base]; /* get next digit */ + } while ((n /= base) > 0); /* delete it */ + + if (is_negative) + s[i++] = '-'; + + s[i] = '\0'; + + // reverse(s, i); + return i; +} + +IntegerView::IntegerView(int32_t n) { + length = itoa(n, buffer); +} + +IntegerView::IntegerView(HexFormat_int32 f) { + length = itoa(f.n, buffer); + buffer[length++] = 'x'; + buffer[length++] = '0'; +} + +IntegerView::IntegerView(HexFormat_uint32 f) { + length = itoa(f.n, buffer); + buffer[length++] = 'x'; + buffer[length++] = '0'; +} diff --git a/libk/string/string.cc b/libk/string/string.cc new file mode 100644 index 0000000..c75feb1 --- /dev/null +++ b/libk/string/string.cc @@ -0,0 +1,26 @@ +#include "string.h" + +// TODO + +// int strcpy(char *dst, const char *stc); +// void strcat(void *dst, const void *src); +// char* strncpy(char *dest, const char *src, int length); +// int strncmp(const char *s1, const char *s2, int c); + +/* strcmp - compare two C-strings */ +constexpr int strcmp(const char* s1, const char* s2) { + const auto s1_len = strlen(s1); + for (size_t i = 0; i < s1_len; ++i) { + if (s1[i] == s2[i]) + continue; + if (s1[i] > s2[i]) + return 1; + if (s1[i] < s2[i]) + return -1; + } + return 0; +} + +static_assert(strcmp("one", "one") == 0); +static_assert(strcmp("one", "two") < 0); +static_assert(strcmp("foo", "bar") > 0); diff --git a/libk/string/test.cc b/libk/string/test.cc new file mode 100644 index 0000000..4d7d340 --- /dev/null +++ b/libk/string/test.cc @@ -0,0 +1,14 @@ +#include + +// strlen +static_assert(strlen("") == 0); +static_assert(strlen("0") == 1); +static_assert(strlen("hello") == 5); +static_assert(strlen("world") == 5); + +// reverse +static_assert([]() { + char s[] = "xyz"; + reverse(s, strlen(s)); + return s[0] == 'z' && s[1] == 'y' && s[2] == 'x' && s[3] == '\0'; +}()); -- cgit v1.2.1