source: mainline/uspace/lib/posix/src/string.c@ 7c3fb9b

lfn serial ticket/834-toolchain-update topic/msim-upgrade topic/simplify-dev-export
Last change on this file since 7c3fb9b was 7c3fb9b, checked in by Jiri Svoboda <jiri@…>, 7 years ago

Fix block comment formatting (ccheck).

  • Property mode set to 100644
File size: 16.5 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#include "internal/common.h"
37#include "posix/string.h"
38
39#include <assert.h>
40
41#include <errno.h>
42
43#include "posix/limits.h"
44#include "posix/stdlib.h"
45#include "posix/signal.h"
46
47#include "libc/str.h"
48#include "libc/str_error.h"
49
50/**
51 * The same as strpbrk, except it returns pointer to the nul terminator
52 * if no occurence is found.
53 *
54 * @param s1 String in which to look for the bytes.
55 * @param s2 String of bytes to look for.
56 * @return Pointer to the found byte on success, pointer to the
57 * string terminator otherwise.
58 */
59static char *strpbrk_null(const char *s1, const char *s2)
60{
61 while (!strchr(s2, *s1)) {
62 ++s1;
63 }
64
65 return (char *) s1;
66}
67
68/**
69 * Copy a string.
70 *
71 * @param dest Destination pre-allocated buffer.
72 * @param src Source string to be copied.
73 * @return Pointer to the destination buffer.
74 */
75char *strcpy(char *restrict dest, const char *restrict src)
76{
77 stpcpy(dest, src);
78 return dest;
79}
80
81/**
82 * Copy fixed length string.
83 *
84 * @param dest Destination pre-allocated buffer.
85 * @param src Source string to be copied.
86 * @param n Number of bytes to be stored into destination buffer.
87 * @return Pointer to the destination buffer.
88 */
89char *strncpy(char *restrict dest, const char *restrict src, size_t n)
90{
91 stpncpy(dest, src, n);
92 return dest;
93}
94
95/**
96 * Copy a string.
97 *
98 * @param dest Destination pre-allocated buffer.
99 * @param src Source string to be copied.
100 * @return Pointer to the nul character in the destination string.
101 */
102char *stpcpy(char *restrict dest, const char *restrict src)
103{
104 assert(dest != NULL);
105 assert(src != NULL);
106
107 for (size_t i = 0; ; ++i) {
108 dest[i] = src[i];
109
110 if (src[i] == '\0') {
111 /* pointer to the terminating nul character */
112 return &dest[i];
113 }
114 }
115
116 /* unreachable */
117 return NULL;
118}
119
120/**
121 * Copy fixed length string.
122 *
123 * @param dest Destination pre-allocated buffer.
124 * @param src Source string to be copied.
125 * @param n Number of bytes to be stored into destination buffer.
126 * @return Pointer to the first written nul character or &dest[n].
127 */
128char *stpncpy(char *restrict dest, const char *restrict src, size_t n)
129{
130 assert(dest != NULL);
131 assert(src != NULL);
132
133 for (size_t i = 0; i < n; ++i) {
134 dest[i] = src[i];
135
136 /*
137 * the standard requires that nul characters
138 * are appended to the length of n, in case src is shorter
139 */
140 if (src[i] == '\0') {
141 char *result = &dest[i];
142 for (++i; i < n; ++i) {
143 dest[i] = '\0';
144 }
145 return result;
146 }
147 }
148
149 return &dest[n];
150}
151
152/**
153 * Concatenate two strings.
154 *
155 * @param dest String to which src shall be appended.
156 * @param src String to be appended after dest.
157 * @return Pointer to destination buffer.
158 */
159char *strcat(char *restrict dest, const char *restrict src)
160{
161 assert(dest != NULL);
162 assert(src != NULL);
163
164 strcpy(strchr(dest, '\0'), src);
165 return dest;
166}
167
168/**
169 * Concatenate a string with part of another.
170 *
171 * @param dest String to which part of src shall be appended.
172 * @param src String whose part shall be appended after dest.
173 * @param n Number of bytes to append after dest.
174 * @return Pointer to destination buffer.
175 */
176char *strncat(char *restrict dest, const char *restrict src, size_t n)
177{
178 assert(dest != NULL);
179 assert(src != NULL);
180
181 char *zeroptr = strncpy(strchr(dest, '\0'), src, n);
182 /* strncpy doesn't append the nul terminator, so we do it here */
183 zeroptr[n] = '\0';
184 return dest;
185}
186
187/**
188 * Copy limited number of bytes in memory.
189 *
190 * @param dest Destination buffer.
191 * @param src Source buffer.
192 * @param c Character after which the copying shall stop.
193 * @param n Number of bytes that shall be copied if not stopped earlier by c.
194 * @return Pointer to the first byte after c in dest if found, NULL otherwise.
195 */
196void *memccpy(void *restrict dest, const void *restrict src, int c, size_t n)
197{
198 assert(dest != NULL);
199 assert(src != NULL);
200
201 unsigned char *bdest = dest;
202 const unsigned char *bsrc = src;
203
204 for (size_t i = 0; i < n; ++i) {
205 bdest[i] = bsrc[i];
206
207 if (bsrc[i] == (unsigned char) c) {
208 /* pointer to the next byte */
209 return &bdest[i + 1];
210 }
211 }
212
213 return NULL;
214}
215
216/**
217 * Duplicate a string.
218 *
219 * @param s String to be duplicated.
220 * @return Newly allocated copy of the string.
221 */
222char *strdup(const char *s)
223{
224 return strndup(s, SIZE_MAX);
225}
226
227/**
228 * Duplicate a specific number of bytes from a string.
229 *
230 * @param s String to be duplicated.
231 * @param n Maximum length of the resulting string..
232 * @return Newly allocated string copy of length at most n.
233 */
234char *strndup(const char *s, size_t n)
235{
236 assert(s != NULL);
237
238 size_t len = strnlen(s, n);
239 char *dup = malloc(len + 1);
240 if (dup == NULL) {
241 return NULL;
242 }
243
244 memcpy(dup, s, len);
245 dup[len] = '\0';
246
247 return dup;
248}
249
250/**
251 * Compare two strings.
252 *
253 * @param s1 First string to be compared.
254 * @param s2 Second string to be compared.
255 * @return Difference of the first pair of inequal characters,
256 * or 0 if strings have the same content.
257 */
258int strcmp(const char *s1, const char *s2)
259{
260 assert(s1 != NULL);
261 assert(s2 != NULL);
262
263 return strncmp(s1, s2, STR_NO_LIMIT);
264}
265
266/**
267 * Compare part of two strings.
268 *
269 * @param s1 First string to be compared.
270 * @param s2 Second string to be compared.
271 * @param n Maximum number of characters to be compared.
272 * @return Difference of the first pair of inequal characters,
273 * or 0 if strings have the same content.
274 */
275int strncmp(const char *s1, const char *s2, size_t n)
276{
277 assert(s1 != NULL);
278 assert(s2 != NULL);
279
280 for (size_t i = 0; i < n; ++i) {
281 if (s1[i] != s2[i]) {
282 return s1[i] - s2[i];
283 }
284 if (s1[i] == '\0') {
285 break;
286 }
287 }
288
289 return 0;
290}
291
292/**
293 * Find byte in memory.
294 *
295 * @param mem Memory area in which to look for the byte.
296 * @param c Byte to look for.
297 * @param n Maximum number of bytes to be inspected.
298 * @return Pointer to the specified byte on success,
299 * NULL pointer otherwise.
300 */
301void *memchr(const void *mem, int c, size_t n)
302{
303 assert(mem != NULL);
304
305 const unsigned char *s = mem;
306
307 for (size_t i = 0; i < n; ++i) {
308 if (s[i] == (unsigned char) c) {
309 return (void *) &s[i];
310 }
311 }
312 return NULL;
313}
314
315/**
316 * Scan string for a first occurence of a character.
317 *
318 * @param s String in which to look for the character.
319 * @param c Character to look for.
320 * @return Pointer to the specified character on success,
321 * NULL pointer otherwise.
322 */
323char *strchr(const char *s, int c)
324{
325 assert(s != NULL);
326
327 char *res = gnu_strchrnul(s, c);
328 return (*res == c) ? res : NULL;
329}
330
331/**
332 * Scan string for a last occurence of a character.
333 *
334 * @param s String in which to look for the character.
335 * @param c Character to look for.
336 * @return Pointer to the specified character on success,
337 * NULL pointer otherwise.
338 */
339char *strrchr(const char *s, int c)
340{
341 assert(s != NULL);
342
343 const char *ptr = strchr(s, '\0');
344
345 /* the same as in strchr, except it loops in reverse direction */
346 while (*ptr != (char) c) {
347 if (ptr == s) {
348 return NULL;
349 }
350
351 ptr--;
352 }
353
354 return (char *) ptr;
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, pointer to the
363 * string terminator otherwise.
364 */
365char *gnu_strchrnul(const char *s, int c)
366{
367 assert(s != NULL);
368
369 while (*s != c && *s != '\0') {
370 s++;
371 }
372
373 return (char *) s;
374}
375
376/**
377 * Scan a string for a first occurence of one of provided bytes.
378 *
379 * @param s1 String in which to look for the bytes.
380 * @param s2 String of bytes to look for.
381 * @return Pointer to the found byte on success,
382 * NULL pointer otherwise.
383 */
384char *strpbrk(const char *s1, const char *s2)
385{
386 assert(s1 != NULL);
387 assert(s2 != NULL);
388
389 char *ptr = strpbrk_null(s1, s2);
390 return (*ptr == '\0') ? NULL : ptr;
391}
392
393/**
394 * Get the length of a complementary substring.
395 *
396 * @param s1 String that shall be searched for complementary prefix.
397 * @param s2 String of bytes that shall not occur in the prefix.
398 * @return Length of the prefix.
399 */
400size_t strcspn(const char *s1, const char *s2)
401{
402 assert(s1 != NULL);
403 assert(s2 != NULL);
404
405 char *ptr = strpbrk_null(s1, s2);
406 return (size_t) (ptr - s1);
407}
408
409/**
410 * Get length of a substring.
411 *
412 * @param s1 String that shall be searched for prefix.
413 * @param s2 String of bytes that the prefix must consist of.
414 * @return Length of the prefix.
415 */
416size_t strspn(const char *s1, const char *s2)
417{
418 assert(s1 != NULL);
419 assert(s2 != NULL);
420
421 const char *ptr;
422 for (ptr = s1; *ptr != '\0'; ++ptr) {
423 if (!strchr(s2, *ptr)) {
424 break;
425 }
426 }
427 return ptr - s1;
428}
429
430/**
431 * Find a substring. Uses Knuth-Morris-Pratt algorithm.
432 *
433 * @param s1 String in which to look for a substring.
434 * @param s2 Substring to look for.
435 * @return Pointer to the first character of the substring in s1, or NULL if
436 * not found.
437 */
438char *strstr(const char *haystack, const char *needle)
439{
440 assert(haystack != NULL);
441 assert(needle != NULL);
442
443 /* Special case - needle is an empty string. */
444 if (needle[0] == '\0') {
445 return (char *) haystack;
446 }
447
448 /* Preprocess needle. */
449 size_t nlen = strlen(needle);
450 size_t prefix_table[nlen + 1];
451
452 size_t i = 0;
453 ssize_t j = -1;
454
455 prefix_table[i] = j;
456
457 while (i < nlen) {
458 while (j >= 0 && needle[i] != needle[j]) {
459 j = prefix_table[j];
460 }
461 i++;
462 j++;
463 prefix_table[i] = j;
464 }
465
466 /* Search needle using the precomputed table. */
467 size_t npos = 0;
468
469 for (size_t hpos = 0; haystack[hpos] != '\0'; ++hpos) {
470 while (npos != 0 && haystack[hpos] != needle[npos]) {
471 npos = prefix_table[npos];
472 }
473
474 if (haystack[hpos] == needle[npos]) {
475 npos++;
476
477 if (npos == nlen) {
478 return (char *) (haystack + hpos - nlen + 1);
479 }
480 }
481 }
482
483 return NULL;
484}
485
486/** Split string by delimiters.
487 *
488 * @param s String to be tokenized. May not be NULL.
489 * @param delim String with the delimiters.
490 * @return Pointer to the prefix of @a s before the first
491 * delimiter character. NULL if no such prefix
492 * exists.
493 */
494char *strtok(char *s, const char *delim)
495{
496 static char *next;
497
498 return strtok_r(s, delim, &next);
499}
500
501
502/** Split string by delimiters.
503 *
504 * @param s String to be tokenized. May not be NULL.
505 * @param delim String with the delimiters.
506 * @param next Variable which will receive the pointer to the
507 * continuation of the string following the first
508 * occurrence of any of the delimiter characters.
509 * May be NULL.
510 * @return Pointer to the prefix of @a s before the first
511 * delimiter character. NULL if no such prefix
512 * exists.
513 */
514char *strtok_r(char *s, const char *delim, char **next)
515{
516 char *start, *end;
517
518 if (s == NULL)
519 s = *next;
520
521 /* Skip over leading delimiters. */
522 while (*s && (strchr(delim, *s) != NULL))
523 ++s;
524 start = s;
525
526 /* Skip over token characters. */
527 while (*s && (strchr(delim, *s) == NULL))
528 ++s;
529 end = s;
530 *next = (*s ? s + 1 : s);
531
532 if (start == end) {
533 return NULL; /* No more tokens. */
534 }
535
536 /* Overwrite delimiter with NULL terminator. */
537 *end = '\0';
538 return start;
539}
540
541/**
542 * String comparison using collating information.
543 *
544 * Currently ignores locale and just calls strcmp.
545 *
546 * @param s1 First string to be compared.
547 * @param s2 Second string to be compared.
548 * @return Difference of the first pair of inequal characters,
549 * or 0 if strings have the same content.
550 */
551int strcoll(const char *s1, const char *s2)
552{
553 assert(s1 != NULL);
554 assert(s2 != NULL);
555
556 return strcmp(s1, s2);
557}
558
559/**
560 * Transform a string in such a way that the resulting string yields the same
561 * results when passed to the strcmp as if the original string is passed to
562 * the strcoll.
563 *
564 * Since strcoll is equal to strcmp here, this just makes a copy.
565 *
566 * @param s1 Transformed string.
567 * @param s2 Original string.
568 * @param n Maximum length of the transformed string.
569 * @return Length of the transformed string.
570 */
571size_t strxfrm(char *restrict s1, const char *restrict s2, size_t n)
572{
573 assert(s1 != NULL || n == 0);
574 assert(s2 != NULL);
575
576 size_t len = strlen(s2);
577
578 if (n > len) {
579 strcpy(s1, s2);
580 }
581
582 return len;
583}
584
585/**
586 * Get error message string.
587 *
588 * @param errnum Error code for which to obtain human readable string.
589 * @return Error message.
590 */
591char *strerror(int errnum)
592{
593 // FIXME: move strerror() and strerror_r() to libc.
594 return (char *) str_error(errnum);
595}
596
597/**
598 * Get error message string.
599 *
600 * @param errnum Error code for which to obtain human readable string.
601 * @param buf Buffer to store a human readable string to.
602 * @param bufsz Size of buffer pointed to by buf.
603 * @return Zero on success, errno otherwise.
604 */
605int strerror_r(int errnum, char *buf, size_t bufsz)
606{
607 assert(buf != NULL);
608
609 char *errstr = strerror(errnum);
610
611 if (strlen(errstr) + 1 > bufsz) {
612 return ERANGE;
613 } else {
614 strcpy(buf, errstr);
615 }
616
617 return EOK;
618}
619
620/**
621 * Get length of the string.
622 *
623 * @param s String which length shall be determined.
624 * @return Length of the string.
625 */
626size_t strlen(const char *s)
627{
628 assert(s != NULL);
629
630 return (size_t) (strchr(s, '\0') - s);
631}
632
633/**
634 * Get limited length of the string.
635 *
636 * @param s String which length shall be determined.
637 * @param n Maximum number of bytes that can be examined to determine length.
638 * @return The lower of either string length or n limit.
639 */
640size_t strnlen(const char *s, size_t n)
641{
642 assert(s != NULL);
643
644 for (size_t sz = 0; sz < n; ++sz) {
645
646 if (s[sz] == '\0') {
647 return sz;
648 }
649 }
650
651 return n;
652}
653
654/**
655 * Get description of a signal.
656 *
657 * @param signum Signal number.
658 * @return Human readable signal description.
659 */
660char *strsignal(int signum)
661{
662 static const char *const sigstrings[] = {
663 [SIGABRT] = "SIGABRT (Process abort signal)",
664 [SIGALRM] = "SIGALRM (Alarm clock)",
665 [SIGBUS] = "SIGBUS (Access to an undefined portion of a memory object)",
666 [SIGCHLD] = "SIGCHLD (Child process terminated, stopped, or continued)",
667 [SIGCONT] = "SIGCONT (Continue executing, if stopped)",
668 [SIGFPE] = "SIGFPE (Erroneous arithmetic operation)",
669 [SIGHUP] = "SIGHUP (Hangup)",
670 [SIGILL] = "SIGILL (Illegal instruction)",
671 [SIGINT] = "SIGINT (Terminal interrupt signal)",
672 [SIGKILL] = "SIGKILL (Kill process)",
673 [SIGPIPE] = "SIGPIPE (Write on a pipe with no one to read it)",
674 [SIGQUIT] = "SIGQUIT (Terminal quit signal)",
675 [SIGSEGV] = "SIGSEGV (Invalid memory reference)",
676 [SIGSTOP] = "SIGSTOP (Stop executing)",
677 [SIGTERM] = "SIGTERM (Termination signal)",
678 [SIGTSTP] = "SIGTSTP (Terminal stop signal)",
679 [SIGTTIN] = "SIGTTIN (Background process attempting read)",
680 [SIGTTOU] = "SIGTTOU (Background process attempting write)",
681 [SIGUSR1] = "SIGUSR1 (User-defined signal 1)",
682 [SIGUSR2] = "SIGUSR2 (User-defined signal 2)",
683 [SIGPOLL] = "SIGPOLL (Pollable event)",
684 [SIGPROF] = "SIGPROF (Profiling timer expired)",
685 [SIGSYS] = "SIGSYS (Bad system call)",
686 [SIGTRAP] = "SIGTRAP (Trace/breakpoint trap)",
687 [SIGURG] = "SIGURG (High bandwidth data is available at a socket)",
688 [SIGVTALRM] = "SIGVTALRM (Virtual timer expired)",
689 [SIGXCPU] = "SIGXCPU (CPU time limit exceeded)",
690 [SIGXFSZ] = "SIGXFSZ (File size limit exceeded)"
691 };
692
693 if (signum <= _TOP_SIGNAL) {
694 return (char *) sigstrings[signum];
695 }
696
697 return (char *) "ERROR, Invalid signal number";
698}
699
700/** @}
701 */
Note: See TracBrowser for help on using the repository browser.