kit

kit
git clone https://git.ryansepassi.com/git/kit.git
Log | Files | Refs | README

mem.c (1557B)


      1 //===-- mem.c - kit freestanding mem* primitives -----------------------===//
      2 //
      3 // SPDX-License-Identifier: 0BSD
      4 //
      5 // Portable C implementations of memcpy, memmove, memset, memcmp.
      6 // All are weak so a user libc (or a tuned arch-specific version) wins.
      7 // Targets without __builtin_trap can replace it; kit always provides it.
      8 //===----------------------------------------------------------------------===//
      9 
     10 #include <stddef.h>
     11 
     12 __attribute__((weak)) void* memcpy(void* restrict dst, const void* restrict src,
     13                                    size_t n) {
     14   unsigned char* d = (unsigned char*)dst;
     15   const unsigned char* s = (const unsigned char*)src;
     16   for (size_t i = 0; i < n; i++) d[i] = s[i];
     17   return dst;
     18 }
     19 
     20 __attribute__((weak)) void* memmove(void* dst, const void* src, size_t n) {
     21   unsigned char* d = (unsigned char*)dst;
     22   const unsigned char* s = (const unsigned char*)src;
     23   if (d == s || n == 0) return dst;
     24   if (d < s) {
     25     for (size_t i = 0; i < n; i++) d[i] = s[i];
     26   } else {
     27     for (size_t i = n; i-- > 0;) d[i] = s[i];
     28   }
     29   return dst;
     30 }
     31 
     32 __attribute__((weak)) void* memset(void* dst, int c, size_t n) {
     33   unsigned char* d = (unsigned char*)dst;
     34   unsigned char v = (unsigned char)c;
     35   for (size_t i = 0; i < n; i++) d[i] = v;
     36   return dst;
     37 }
     38 
     39 __attribute__((weak)) int memcmp(const void* a, const void* b, size_t n) {
     40   const unsigned char* p = (const unsigned char*)a;
     41   const unsigned char* q = (const unsigned char*)b;
     42   for (size_t i = 0; i < n; i++) {
     43     if (p[i] != q[i]) return (int)p[i] - (int)q[i];
     44   }
     45   return 0;
     46 }