Changeset ea4910b in mainline for uspace/lib/posix/src/string.c


Ignore:
Timestamp:
2018-11-30T10:04:57Z (5 years ago)
Author:
Jiri Svoboda <jiri@…>
Branches:
lfn, master, serial, ticket/834-toolchain-update, topic/msim-upgrade, topic/simplify-dev-export
Children:
26f5bdf, 4aba581
Parents:
c483fca
git-author:
Jiri Svoboda <jiri@…> (2018-11-29 18:02:24)
git-committer:
Jiri Svoboda <jiri@…> (2018-11-30 10:04:57)
Message:

strdup(), strndup(), strnlen() are commonly used extensions so move them to libc (native ports can use these).

File:
1 edited

Legend:

Unmodified
Added
Removed
  • uspace/lib/posix/src/string.c

    rc483fca rea4910b  
    135135
    136136/**
    137  * Duplicate a string.
    138  *
    139  * @param s String to be duplicated.
    140  * @return Newly allocated copy of the string.
    141  */
    142 char *strdup(const char *s)
    143 {
    144         return strndup(s, SIZE_MAX);
    145 }
    146 
    147 /**
    148  * Duplicate a specific number of bytes from a string.
    149  *
    150  * @param s String to be duplicated.
    151  * @param n Maximum length of the resulting string..
    152  * @return Newly allocated string copy of length at most n.
    153  */
    154 char *strndup(const char *s, size_t n)
    155 {
    156         assert(s != NULL);
    157 
    158         size_t len = strnlen(s, n);
    159         char *dup = malloc(len + 1);
    160         if (dup == NULL) {
    161                 return NULL;
    162         }
    163 
    164         memcpy(dup, s, len);
    165         dup[len] = '\0';
    166 
    167         return dup;
    168 }
    169 
    170 /**
    171137 * Scan string for a first occurence of a character.
    172138 *
     
    225191
    226192        return EOK;
    227 }
    228 
    229 /**
    230  * Get limited length of the string.
    231  *
    232  * @param s String which length shall be determined.
    233  * @param n Maximum number of bytes that can be examined to determine length.
    234  * @return The lower of either string length or n limit.
    235  */
    236 size_t strnlen(const char *s, size_t n)
    237 {
    238         assert(s != NULL);
    239 
    240         for (size_t sz = 0; sz < n; ++sz) {
    241 
    242                 if (s[sz] == '\0') {
    243                         return sz;
    244                 }
    245         }
    246 
    247         return n;
    248193}
    249194
Note: See TracChangeset for help on using the changeset viewer.