diff options
Diffstat (limited to 'src/string.c')
| -rw-r--r-- | src/string.c | 59 |
1 files changed, 59 insertions, 0 deletions
diff --git a/src/string.c b/src/string.c new file mode 100644 index 0000000..4801154 --- /dev/null +++ b/src/string.c | |||
| @@ -0,0 +1,59 @@ | |||
| 1 | #include <string.h> | ||
| 2 | |||
| 3 | #include <stdint.h> | ||
| 4 | |||
| 5 | void* memcpy(void* dst, const void* src, size_t count) { | ||
| 6 | // TODO: Can probably use better implementations based on hw instruction set. | ||
| 7 | uint32_t* dst32 = (uint32_t*)dst; | ||
| 8 | const uint32_t* src32 = (uint32_t*)src; | ||
| 9 | for(; count >= 4; count -= 4) { | ||
| 10 | *dst32++ = *src32++; | ||
| 11 | } | ||
| 12 | uint8_t* dst8 = (uint8_t*)dst32; | ||
| 13 | const uint8_t* src8 = (uint8_t*)src32; | ||
| 14 | for(; count != 0; count--) { | ||
| 15 | *dst8++ = *src8++; | ||
| 16 | } | ||
| 17 | return dst8; | ||
| 18 | } | ||
| 19 | |||
| 20 | static int count_digits_u(unsigned int x) { | ||
| 21 | int count = 0; | ||
| 22 | for(; x != 0; x /= 10, count++); | ||
| 23 | return count; | ||
| 24 | } | ||
| 25 | |||
| 26 | char* utoa(unsigned int x, char* buffer, size_t size) { | ||
| 27 | if (size > 0) { | ||
| 28 | const int num_digits = count_digits_u(x); | ||
| 29 | size_t i = 0; | ||
| 30 | while ((x != 0) && ((i+1) < size)) { | ||
| 31 | const unsigned int digit = x % 10; | ||
| 32 | x /= 10; | ||
| 33 | buffer[num_digits-1 - i++] = '0' + digit; | ||
| 34 | } | ||
| 35 | buffer[i] = 0; | ||
| 36 | } | ||
| 37 | return buffer; | ||
| 38 | } | ||
| 39 | |||
| 40 | char* ptoa(const void* ptr, char* buffer, size_t size) { | ||
| 41 | if (size > 2) { | ||
| 42 | size_t i = 0; | ||
| 43 | buffer[i++] = '0'; | ||
| 44 | buffer[i++] = 'x'; | ||
| 45 | uintptr_t x = (uintptr_t)ptr; | ||
| 46 | const int num_digits = count_digits_u(x); | ||
| 47 | while ((x != 0) && (i < size)) { | ||
| 48 | const unsigned int digit = x % 16; | ||
| 49 | x /= 16; | ||
| 50 | const char hex = (digit < 10) ? ('0' + digit) : ('a' + (digit-10)); | ||
| 51 | buffer[num_digits-1+2 - i++] = hex; | ||
| 52 | } | ||
| 53 | buffer[i] = 0; | ||
| 54 | } else if (size > 0) { | ||
| 55 | buffer[0] = 0; | ||
| 56 | } | ||
| 57 | return buffer; | ||
| 58 | } | ||
| 59 | |||
