root/kernel/string.c

/* [<][>][^][v][top][bottom][index][help] */

DEFINITIONS

This source file includes following definitions.
  1. memset
  2. memcmp
  3. memmove
  4. memcpy
  5. strncmp
  6. strncpy
  7. safestrcpy
  8. strlen

   1 #include "types.h"
   2 
   3 void*
   4 memset(void *dst, int c, uint n)
   5 {
   6   char *cdst = (char *) dst;
   7   int i;
   8   for(i = 0; i < n; i++){
   9     cdst[i] = c;
  10   }
  11   return dst;
  12 }
  13 
  14 int
  15 memcmp(const void *v1, const void *v2, uint n)
  16 {
  17   const uchar *s1, *s2;
  18 
  19   s1 = v1;
  20   s2 = v2;
  21   while(n-- > 0){
  22     if(*s1 != *s2)
  23       return *s1 - *s2;
  24     s1++, s2++;
  25   }
  26 
  27   return 0;
  28 }
  29 
  30 void*
  31 memmove(void *dst, const void *src, uint n)
  32 {
  33   const char *s;
  34   char *d;
  35 
  36   if(n == 0)
  37     return dst;
  38   
  39   s = src;
  40   d = dst;
  41   if(s < d && s + n > d){
  42     s += n;
  43     d += n;
  44     while(n-- > 0)
  45       *--d = *--s;
  46   } else
  47     while(n-- > 0)
  48       *d++ = *s++;
  49 
  50   return dst;
  51 }
  52 
  53 // memcpy exists to placate GCC.  Use memmove.
  54 void*
  55 memcpy(void *dst, const void *src, uint n)
  56 {
  57   return memmove(dst, src, n);
  58 }
  59 
  60 int
  61 strncmp(const char *p, const char *q, uint n)
  62 {
  63   while(n > 0 && *p && *p == *q)
  64     n--, p++, q++;
  65   if(n == 0)
  66     return 0;
  67   return (uchar)*p - (uchar)*q;
  68 }
  69 
  70 char*
  71 strncpy(char *s, const char *t, int n)
  72 {
  73   char *os;
  74 
  75   os = s;
  76   while(n-- > 0 && (*s++ = *t++) != 0)
  77     ;
  78   while(n-- > 0)
  79     *s++ = 0;
  80   return os;
  81 }
  82 
  83 // Like strncpy but guaranteed to NUL-terminate.
  84 char*
  85 safestrcpy(char *s, const char *t, int n)
  86 {
  87   char *os;
  88 
  89   os = s;
  90   if(n <= 0)
  91     return os;
  92   while(--n > 0 && (*s++ = *t++) != 0)
  93     ;
  94   *s = 0;
  95   return os;
  96 }
  97 
  98 int
  99 strlen(const char *s)
 100 {
 101   int n;
 102 
 103   for(n = 0; s[n]; n++)
 104     ;
 105   return n;
 106 }
 107 

/* [<][>][^][v][top][bottom][index][help] */