root/user/ulib.c

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

DEFINITIONS

This source file includes following definitions.
  1. start
  2. strcpy
  3. strcmp
  4. strlen
  5. memset
  6. strchr
  7. gets
  8. stat
  9. atoi
  10. memmove
  11. memcmp
  12. memcpy

   1 #include "kernel/types.h"
   2 #include "kernel/stat.h"
   3 #include "kernel/fcntl.h"
   4 #include "user/user.h"
   5 
   6 //
   7 // wrapper so that it's OK if main() does not call exit().
   8 //
   9 void
  10 start()
  11 {
  12   extern int main();
  13   main();
  14   exit(0);
  15 }
  16 
  17 char*
  18 strcpy(char *s, const char *t)
  19 {
  20   char *os;
  21 
  22   os = s;
  23   while((*s++ = *t++) != 0)
  24     ;
  25   return os;
  26 }
  27 
  28 int
  29 strcmp(const char *p, const char *q)
  30 {
  31   while(*p && *p == *q)
  32     p++, q++;
  33   return (uchar)*p - (uchar)*q;
  34 }
  35 
  36 uint
  37 strlen(const char *s)
  38 {
  39   int n;
  40 
  41   for(n = 0; s[n]; n++)
  42     ;
  43   return n;
  44 }
  45 
  46 void*
  47 memset(void *dst, int c, uint n)
  48 {
  49   char *cdst = (char *) dst;
  50   int i;
  51   for(i = 0; i < n; i++){
  52     cdst[i] = c;
  53   }
  54   return dst;
  55 }
  56 
  57 char*
  58 strchr(const char *s, char c)
  59 {
  60   for(; *s; s++)
  61     if(*s == c)
  62       return (char*)s;
  63   return 0;
  64 }
  65 
  66 char*
  67 gets(char *buf, int max)
  68 {
  69   int i, cc;
  70   char c;
  71 
  72   for(i=0; i+1 < max; ){
  73     cc = read(0, &c, 1);
  74     if(cc < 1)
  75       break;
  76     buf[i++] = c;
  77     if(c == '\n' || c == '\r')
  78       break;
  79   }
  80   buf[i] = '\0';
  81   return buf;
  82 }
  83 
  84 int
  85 stat(const char *n, struct stat *st)
  86 {
  87   int fd;
  88   int r;
  89 
  90   fd = open(n, O_RDONLY);
  91   if(fd < 0)
  92     return -1;
  93   r = fstat(fd, st);
  94   close(fd);
  95   return r;
  96 }
  97 
  98 int
  99 atoi(const char *s)
 100 {
 101   int n;
 102 
 103   n = 0;
 104   while('0' <= *s && *s <= '9')
 105     n = n*10 + *s++ - '0';
 106   return n;
 107 }
 108 
 109 void*
 110 memmove(void *vdst, const void *vsrc, int n)
 111 {
 112   char *dst;
 113   const char *src;
 114 
 115   dst = vdst;
 116   src = vsrc;
 117   if (src > dst) {
 118     while(n-- > 0)
 119       *dst++ = *src++;
 120   } else {
 121     dst += n;
 122     src += n;
 123     while(n-- > 0)
 124       *--dst = *--src;
 125   }
 126   return vdst;
 127 }
 128 
 129 int
 130 memcmp(const void *s1, const void *s2, uint n)
 131 {
 132   const char *p1 = s1, *p2 = s2;
 133   while (n-- > 0) {
 134     if (*p1 != *p2) {
 135       return *p1 - *p2;
 136     }
 137     p1++;
 138     p2++;
 139   }
 140   return 0;
 141 }
 142 
 143 void *
 144 memcpy(void *dst, const void *src, uint n)
 145 {
 146   return memmove(dst, src, n);
 147 }

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