3 * Copyright (c) 2001,2004 David H. Hovemeyer <daveho@cs.umd.edu>
6 * This is free software. You are permitted to use,
7 * redistribute, and modify it as specified in the file "COPYING".
12 * These are slow and simple implementations of a subset of
13 * the standard C library string functions.
14 * We also have an implementation of snprintf().
20 extern void *Malloc(size_t size);
22 void* memset(void* s, int c, size_t n)
24 unsigned char* p = (unsigned char*) s;
27 *p++ = (unsigned char) c;
34 void* memcpy(void *dst, const void* src, size_t n)
36 unsigned char* d = (unsigned char*) dst;
37 const unsigned char* s = (const unsigned char*) src;
47 int memcmp(const void *s1_, const void *s2_, size_t n)
49 const signed char *s1 = s1_, *s2 = s2_;
62 size_t strlen(const char* s)
71 * This it a GNU extension.
72 * It is like strlen(), but it will check at most maxlen
73 * characters for the terminating nul character,
74 * returning maxlen if it doesn't find a nul.
75 * This is very useful for checking the length of untrusted
76 * strings (e.g., from user space).
78 size_t strnlen(const char *s, size_t maxlen)
81 while (len < maxlen && *s++ != '\0')
86 int strcmp(const char* s1, const char* s2)
90 if (cmp != 0 || *s1 == '\0' || *s2 == '\0')
97 int strncmp(const char* s1, const char* s2, size_t limit)
102 if (cmp != 0 || *s1 == '\0' || *s2 == '\0')
109 /* limit reached and equal */
113 char *strcat(char *s1, const char *s2)
119 while(*s2) *s1++ = *s2++;
125 char *strcpy(char *dest, const char *src)
137 char *strncpy(char *dest, const char *src, size_t limit)
141 while (*src != '\0' && limit > 0) {
151 char *strdup(const char *s1)
155 ret = Malloc(strlen(s1) + 1);
161 int atoi(const char *buf)
165 while (*buf >= '0' && *buf <= '9') {
174 char *strchr(const char *s, int c)
184 char *strrchr(const char *s, int c)
186 size_t len = strlen(s);
187 const char *p = s + len;
197 char *strpbrk(const char *s, const char *accept)
199 size_t setLen = strlen(accept);
203 for (i = 0; i < setLen; ++i) {
213 struct String_Output_Sink {
214 struct Output_Sink o;
219 static void String_Emit(struct Output_Sink *o_, int ch)
221 struct String_Output_Sink *o = (struct String_Output_Sink*) o_;
228 static void String_Finish(struct Output_Sink *o_)
230 struct String_Output_Sink *o = (struct String_Output_Sink*) o_;
236 * Output was truncated; write terminator at end of buffer
237 * (we will have advanced one character too far)
242 int snprintf(char *s, size_t size, const char *fmt, ...)
244 struct String_Output_Sink sink;
248 /* Prepare string output sink */
249 sink.o.Emit = &String_Emit;
250 sink.o.Finish = &String_Finish;
255 /* Format the string */
257 rc = Format_Output(&sink.o, fmt, args);