source: mainline/uspace/lib/posix/string.c@ 087c4c56

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 087c4c56 was 087c4c56, checked in by Petr Koupy <petr.koupy@…>, 14 years ago

Bugfixes in memcmp() and strncmp().

  • Property mode set to 100644
File size: 15.9 KB
Line 
1/*
2 * Copyright (c) 2011 Petr Koupy
3 * Copyright (c) 2011 Jiri Zarevucky
4 * All rights reserved.
5 *
6 * Redistribution and use in source and binary forms, with or without
7 * modification, are permitted provided that the following conditions
8 * are met:
9 *
10 * - Redistributions of source code must retain the above copyright
11 * notice, this list of conditions and the following disclaimer.
12 * - Redistributions in binary form must reproduce the above copyright
13 * notice, this list of conditions and the following disclaimer in the
14 * documentation and/or other materials provided with the distribution.
15 * - The name of the author may not be used to endorse or promote products
16 * derived from this software without specific prior written permission.
17 *
18 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
20 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
21 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
22 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
23 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
24 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
25 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
26 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
27 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
28 */
29
30/** @addtogroup libposix
31 * @{
32 */
33/** @file String manipulation.
34 */
35
36#define LIBPOSIX_INTERNAL
37
38#include "internal/common.h"
39#include "string.h"
40
41#include "assert.h"
42#include "errno.h"
43#include "limits.h"
44#include "stdlib.h"
45#include "signal.h"
46
47#include "libc/str_error.h"
48
49/**
50 * Decides whether s2 is a prefix of s1.
51 *
52 * @param s1 String in which to look for a prefix.
53 * @param s2 Prefix string to look for.
54 * @return True if s2 is a prefix of s1, false otherwise.
55 */
56static bool begins_with(const char *s1, const char *s2)
57{
58 while (*s1 == *s2 && *s2 != '\0') {
59 s1++;
60 s2++;
61 }
62
63 /* true if the end was reached */
64 return *s2 == '\0';
65}
66
67/**
68 * The same as strpbrk, except it returns pointer to the nul terminator
69 * if no occurence is found.
70 *
71 * @param s1 String in which to look for the bytes.
72 * @param s2 String of bytes to look for.
73 * @return Pointer to the found byte on success, pointer to the
74 * string terminator otherwise.
75 */
76static char *strpbrk_null(const char *s1, const char *s2)
77{
78 while (!posix_strchr(s2, *s1)) {
79 ++s1;
80 }
81
82 return (char *) s1;
83}
84
85/**
86 * Copy a string.
87 *
88 * @param dest Destination pre-allocated buffer.
89 * @param src Source string to be copied.
90 * @return Pointer to the destination buffer.
91 */
92char *posix_strcpy(char *restrict dest, const char *restrict src)
93{
94 posix_stpcpy(dest, src);
95 return dest;
96}
97
98/**
99 * Copy fixed length string.
100 *
101 * @param dest Destination pre-allocated buffer.
102 * @param src Source string to be copied.
103 * @param n Number of bytes to be stored into destination buffer.
104 * @return Pointer to the destination buffer.
105 */
106char *posix_strncpy(char *restrict dest, const char *restrict src, size_t n)
107{
108 posix_stpncpy(dest, src, n);
109 return dest;
110}
111
112/**
113 * Copy a string.
114 *
115 * @param dest Destination pre-allocated buffer.
116 * @param src Source string to be copied.
117 * @return Pointer to the nul character in the destination string.
118 */
119char *posix_stpcpy(char *restrict dest, const char *restrict src)
120{
121 assert(dest != NULL);
122 assert(src != NULL);
123
124 for (size_t i = 0; ; ++i) {
125 dest[i] = src[i];
126
127 if (src[i] == '\0') {
128 /* pointer to the terminating nul character */
129 return &dest[i];
130 }
131 }
132
133 /* unreachable */
134 return NULL;
135}
136
137/**
138 * Copy fixed length string.
139 *
140 * @param dest Destination pre-allocated buffer.
141 * @param src Source string to be copied.
142 * @param n Number of bytes to be stored into destination buffer.
143 * @return Pointer to the first written nul character or &dest[n].
144 */
145char *posix_stpncpy(char *restrict dest, const char *restrict src, size_t n)
146{
147 assert(dest != NULL);
148 assert(src != NULL);
149
150 for (size_t i = 0; i < n; ++i) {
151 dest[i] = src[i];
152
153 /* the standard requires that nul characters
154 * are appended to the length of n, in case src is shorter
155 */
156 if (src[i] == '\0') {
157 char *result = &dest[i];
158 for (++i; i < n; ++i) {
159 dest[i] = '\0';
160 }
161 return result;
162 }
163 }
164
165 return &dest[n];
166}
167
168/**
169 * Concatenate two strings.
170 *
171 * @param dest String to which src shall be appended.
172 * @param src String to be appended after dest.
173 * @return Pointer to destination buffer.
174 */
175char *posix_strcat(char *restrict dest, const char *restrict src)
176{
177 assert(dest != NULL);
178 assert(src != NULL);
179
180 posix_strcpy(posix_strchr(dest, '\0'), src);
181 return dest;
182}
183
184/**
185 * Concatenate a string with part of another.
186 *
187 * @param dest String to which part of src shall be appended.
188 * @param src String whose part shall be appended after dest.
189 * @param n Number of bytes to append after dest.
190 * @return Pointer to destination buffer.
191 */
192char *posix_strncat(char *restrict dest, const char *restrict src, size_t n)
193{
194 assert(dest != NULL);
195 assert(src != NULL);
196
197 char *zeroptr = posix_strncpy(posix_strchr(dest, '\0'), src, n);
198 /* strncpy doesn't append the nul terminator, so we do it here */
199 zeroptr[n] = '\0';
200 return dest;
201}
202
203/**
204 * Copy limited number of bytes in memory.
205 *
206 * @param dest Destination buffer.
207 * @param src Source buffer.
208 * @param c Character after which the copying shall stop.
209 * @param n Number of bytes that shall be copied if not stopped earlier by c.
210 * @return Pointer to the first byte after c in dest if found, NULL otherwise.
211 */
212void *posix_memccpy(void *restrict dest, const void *restrict src, int c, size_t n)
213{
214 assert(dest != NULL);
215 assert(src != NULL);
216
217 unsigned char* bdest = dest;
218 const unsigned char* bsrc = src;
219
220 for (size_t i = 0; i < n; ++i) {
221 bdest[i] = bsrc[i];
222
223 if (bsrc[i] == (unsigned char) c) {
224 /* pointer to the next byte */
225 return &bdest[i + 1];
226 }
227 }
228
229 return NULL;
230}
231
232/**
233 * Duplicate a string.
234 *
235 * @param s String to be duplicated.
236 * @return Newly allocated copy of the string.
237 */
238char *posix_strdup(const char *s)
239{
240 return posix_strndup(s, SIZE_MAX);
241}
242
243/**
244 * Duplicate a specific number of bytes from a string.
245 *
246 * @param s String to be duplicated.
247 * @param n Maximum length of the resulting string..
248 * @return Newly allocated string copy of length at most n.
249 */
250char *posix_strndup(const char *s, size_t n)
251{
252 assert(s != NULL);
253
254 size_t len = posix_strnlen(s, n);
255 char *dup = malloc(len + 1);
256 if (dup == NULL) {
257 return NULL;
258 }
259
260 memcpy(dup, s, len);
261 dup[len] = '\0';
262
263 return dup;
264}
265
266/**
267 * Compare bytes in memory.
268 *
269 * @param mem1 First area of memory to be compared.
270 * @param mem2 Second area of memory to be compared.
271 * @param n Maximum number of bytes to be compared.
272 * @return Difference of the first pair of inequal bytes,
273 * or 0 if areas have the same content.
274 */
275int posix_memcmp(const void *mem1, const void *mem2, size_t n)
276{
277 assert(mem1 != NULL);
278 assert(mem2 != NULL);
279
280 const unsigned char *s1 = mem1;
281 const unsigned char *s2 = mem2;
282
283 for (size_t i = 0; i < n; ++i) {
284 if (s1[i] != s2[i]) {
285 return s1[i] - s2[i];
286 }
287 }
288
289 return 0;
290}
291
292/**
293 * Compare two strings.
294 *
295 * @param s1 First string to be compared.
296 * @param s2 Second string to be compared.
297 * @return Difference of the first pair of inequal characters,
298 * or 0 if strings have the same content.
299 */
300int posix_strcmp(const char *s1, const char *s2)
301{
302 assert(s1 != NULL);
303 assert(s2 != NULL);
304
305 return posix_strncmp(s1, s2, STR_NO_LIMIT);
306}
307
308/**
309 * Compare part of two strings.
310 *
311 * @param s1 First string to be compared.
312 * @param s2 Second string to be compared.
313 * @param n Maximum number of characters to be compared.
314 * @return Difference of the first pair of inequal characters,
315 * or 0 if strings have the same content.
316 */
317int posix_strncmp(const char *s1, const char *s2, size_t n)
318{
319 assert(s1 != NULL);
320 assert(s2 != NULL);
321
322 for (size_t i = 0; i < n; ++i) {
323 if (s1[i] != s2[i]) {
324 return s1[i] - s2[i];
325 }
326 if (s1[i] == '\0') {
327 break;
328 }
329 }
330
331 return 0;
332}
333
334/**
335 * Find byte in memory.
336 *
337 * @param mem Memory area in which to look for the byte.
338 * @param c Byte to look for.
339 * @param n Maximum number of bytes to be inspected.
340 * @return Pointer to the specified byte on success,
341 * NULL pointer otherwise.
342 */
343void *posix_memchr(const void *mem, int c, size_t n)
344{
345 assert(mem != NULL);
346
347 const unsigned char *s = mem;
348
349 for (size_t i = 0; i < n; ++i) {
350 if (s[i] == (unsigned char) c) {
351 return (void *) &s[i];
352 }
353 }
354 return NULL;
355}
356
357/**
358 * Scan string for a first occurence of a character.
359 *
360 * @param s String in which to look for the character.
361 * @param c Character to look for.
362 * @return Pointer to the specified character on success,
363 * NULL pointer otherwise.
364 */
365char *posix_strchr(const char *s, int c)
366{
367 assert(s != NULL);
368
369 char *res = gnu_strchrnul(s, c);
370 return (*res == c) ? res : NULL;
371}
372
373/**
374 * Scan string for a last occurence of a character.
375 *
376 * @param s String in which to look for the character.
377 * @param c Character to look for.
378 * @return Pointer to the specified character on success,
379 * NULL pointer otherwise.
380 */
381char *posix_strrchr(const char *s, int c)
382{
383 assert(s != NULL);
384
385 const char *ptr = posix_strchr(s, '\0');
386
387 /* the same as in strchr, except it loops in reverse direction */
388 while (*ptr != (char) c) {
389 if (ptr == s) {
390 return NULL;
391 }
392
393 ptr--;
394 }
395
396 return (char *) ptr;
397}
398
399/**
400 * Scan string for a first occurence of a character.
401 *
402 * @param s String in which to look for the character.
403 * @param c Character to look for.
404 * @return Pointer to the specified character on success, pointer to the
405 * string terminator otherwise.
406 */
407char *gnu_strchrnul(const char *s, int c)
408{
409 assert(s != NULL);
410
411 while (*s != c && *s != '\0') {
412 s++;
413 }
414
415 return (char *) s;
416}
417
418/**
419 * Scan a string for a first occurence of one of provided bytes.
420 *
421 * @param s1 String in which to look for the bytes.
422 * @param s2 String of bytes to look for.
423 * @return Pointer to the found byte on success,
424 * NULL pointer otherwise.
425 */
426char *posix_strpbrk(const char *s1, const char *s2)
427{
428 assert(s1 != NULL);
429 assert(s2 != NULL);
430
431 char *ptr = strpbrk_null(s1, s2);
432 return (*ptr == '\0') ? NULL : ptr;
433}
434
435/**
436 * Get the length of a complementary substring.
437 *
438 * @param s1 String that shall be searched for complementary prefix.
439 * @param s2 String of bytes that shall not occur in the prefix.
440 * @return Length of the prefix.
441 */
442size_t posix_strcspn(const char *s1, const char *s2)
443{
444 assert(s1 != NULL);
445 assert(s2 != NULL);
446
447 char *ptr = strpbrk_null(s1, s2);
448 return (size_t) (ptr - s1);
449}
450
451/**
452 * Get length of a substring.
453 *
454 * @param s1 String that shall be searched for prefix.
455 * @param s2 String of bytes that the prefix must consist of.
456 * @return Length of the prefix.
457 */
458size_t posix_strspn(const char *s1, const char *s2)
459{
460 assert(s1 != NULL);
461 assert(s2 != NULL);
462
463 const char *ptr;
464 for (ptr = s1; *ptr != '\0'; ++ptr) {
465 if (!posix_strchr(s2, *ptr)) {
466 break;
467 }
468 }
469 return ptr - s1;
470}
471
472/**
473 * Find a substring.
474 *
475 * @param s1 String in which to look for a substring.
476 * @param s2 Substring to look for.
477 * @return Pointer to the first character of the substring in s1, or NULL if
478 * not found.
479 */
480char *posix_strstr(const char *s1, const char *s2)
481{
482 assert(s1 != NULL);
483 assert(s2 != NULL);
484
485 /* special case - needle is an empty string */
486 if (*s2 == '\0') {
487 return (char *) s1;
488 }
489
490 // TODO: use faster algorithm
491 /* check for prefix from every position - quadratic complexity */
492 while (*s1 != '\0') {
493 if (begins_with(s1, s2)) {
494 return (char *) s1;
495 }
496
497 s1++;
498 }
499
500 return NULL;
501}
502
503/**
504 * String comparison using collating information.
505 *
506 * Currently ignores locale and just calls strcmp.
507 *
508 * @param s1 First string to be compared.
509 * @param s2 Second string to be compared.
510 * @return Difference of the first pair of inequal characters,
511 * or 0 if strings have the same content.
512 */
513int posix_strcoll(const char *s1, const char *s2)
514{
515 assert(s1 != NULL);
516 assert(s2 != NULL);
517
518 return posix_strcmp(s1, s2);
519}
520
521/**
522 * Transform a string in such a way that the resulting string yields the same
523 * results when passed to the strcmp as if the original string is passed to
524 * the strcoll.
525 *
526 * Since strcoll is equal to strcmp here, this just makes a copy.
527 *
528 * @param s1 Transformed string.
529 * @param s2 Original string.
530 * @param n Maximum length of the transformed string.
531 * @return Length of the transformed string.
532 */
533size_t posix_strxfrm(char *restrict s1, const char *restrict s2, size_t n)
534{
535 assert(s1 != NULL || n == 0);
536 assert(s2 != NULL);
537
538 size_t len = posix_strlen(s2);
539
540 if (n > len) {
541 posix_strcpy(s1, s2);
542 }
543
544 return len;
545}
546
547/**
548 * Get error message string.
549 *
550 * @param errnum Error code for which to obtain human readable string.
551 * @return Error message.
552 */
553char *posix_strerror(int errnum)
554{
555 /* Uses function from libc, we just have to negate errno
556 * (POSIX uses positive errorcodes, HelenOS has negative).
557 */
558 // FIXME: not all POSIX error codes are in libc
559 return (char *) str_error(-posix_abs(errnum));
560}
561
562/**
563 * Get error message string.
564 *
565 * @param errnum Error code for which to obtain human readable string.
566 * @param buf Buffer to store a human readable string to.
567 * @param bufsz Size of buffer pointed to by buf.
568 * @return Zero on success, errno otherwise.
569 */
570int posix_strerror_r(int errnum, char *buf, size_t bufsz)
571{
572 assert(buf != NULL);
573
574 char *errstr = posix_strerror(errnum);
575 /* HelenOS str_error can't fail */
576
577 if (posix_strlen(errstr) + 1 > bufsz) {
578 return -ERANGE;
579 } else {
580 posix_strcpy(buf, errstr);
581 }
582
583 return 0;
584}
585
586/**
587 * Get length of the string.
588 *
589 * @param s String which length shall be determined.
590 * @return Length of the string.
591 */
592size_t posix_strlen(const char *s)
593{
594 assert(s != NULL);
595
596 return (size_t) (posix_strchr(s, '\0') - s);
597}
598
599/**
600 * Get limited length of the string.
601 *
602 * @param s String which length shall be determined.
603 * @param n Maximum number of bytes that can be examined to determine length.
604 * @return The lower of either string length or n limit.
605 */
606size_t posix_strnlen(const char *s, size_t n)
607{
608 assert(s != NULL);
609
610 for (size_t sz = 0; sz < n; ++sz) {
611
612 if (s[sz] == '\0') {
613 return sz;
614 }
615 }
616
617 return n;
618}
619
620/**
621 * Get description of a signal.
622 *
623 * @param signum Signal number.
624 * @return Human readable signal description.
625 */
626char *posix_strsignal(int signum)
627{
628 static const char *const sigstrings[] = {
629 [SIGABRT] = "SIGABRT (Process abort signal)",
630 [SIGALRM] = "SIGALRM (Alarm clock)",
631 [SIGBUS] = "SIGBUS (Access to an undefined portion of a memory object)",
632 [SIGCHLD] = "SIGCHLD (Child process terminated, stopped, or continued)",
633 [SIGCONT] = "SIGCONT (Continue executing, if stopped)",
634 [SIGFPE] = "SIGFPE (Erroneous arithmetic operation)",
635 [SIGHUP] = "SIGHUP (Hangup)",
636 [SIGILL] = "SIGILL (Illegal instruction)",
637 [SIGINT] = "SIGINT (Terminal interrupt signal)",
638 [SIGKILL] = "SIGKILL (Kill process)",
639 [SIGPIPE] = "SIGPIPE (Write on a pipe with no one to read it)",
640 [SIGQUIT] = "SIGQUIT (Terminal quit signal)",
641 [SIGSEGV] = "SIGSEGV (Invalid memory reference)",
642 [SIGSTOP] = "SIGSTOP (Stop executing)",
643 [SIGTERM] = "SIGTERM (Termination signal)",
644 [SIGTSTP] = "SIGTSTP (Terminal stop signal)",
645 [SIGTTIN] = "SIGTTIN (Background process attempting read)",
646 [SIGTTOU] = "SIGTTOU (Background process attempting write)",
647 [SIGUSR1] = "SIGUSR1 (User-defined signal 1)",
648 [SIGUSR2] = "SIGUSR2 (User-defined signal 2)",
649 [SIGPOLL] = "SIGPOLL (Pollable event)",
650 [SIGPROF] = "SIGPROF (Profiling timer expired)",
651 [SIGSYS] = "SIGSYS (Bad system call)",
652 [SIGTRAP] = "SIGTRAP (Trace/breakpoint trap)",
653 [SIGURG] = "SIGURG (High bandwidth data is available at a socket)",
654 [SIGVTALRM] = "SIGVTALRM (Virtual timer expired)",
655 [SIGXCPU] = "SIGXCPU (CPU time limit exceeded)",
656 [SIGXFSZ] = "SIGXFSZ (File size limit exceeded)"
657 };
658
659 if (signum <= _TOP_SIGNAL) {
660 return (char *) sigstrings[signum];
661 }
662
663 return (char *) "ERROR, Invalid signal number";
664}
665
666/** @}
667 */
Note: See TracBrowser for help on using the repository browser.