diff options
author | Paul Eggert <eggert@cs.ucla.edu> | 2021-06-11 17:18:57 -0700 |
---|---|---|
committer | Paul Eggert <eggert@cs.ucla.edu> | 2021-06-11 17:20:11 -0700 |
commit | 40a031df0896ed7bfec35c46d23bd89444ecd5dc (patch) | |
tree | a687bc3a5d0fd705ceafcb260962bb9abfc90fa7 /lib/basename.c | |
parent | 61d866244d7ce4a89a5ed46b768bcace9247d8e8 (diff) | |
download | gnulib-40a031df0896ed7bfec35c46d23bd89444ecd5dc.tar.gz |
dirname: prefer idx_t for some indexes
* lib/basename.c (base_name):
Prefer idx_t to size_t for indexes, and use idx_t-related allocators.
* lib/basename.c: Do not include xstrndup.h.
(basename): Simplify by always using memcpy.
* modules/dirname (Depends-on): Removbe xstrndup.
Diffstat (limited to 'lib/basename.c')
-rw-r--r-- | lib/basename.c | 50 |
1 files changed, 28 insertions, 22 deletions
diff --git a/lib/basename.c b/lib/basename.c index 0ba28780c8..1181134ed1 100644 --- a/lib/basename.c +++ b/lib/basename.c @@ -22,37 +22,43 @@ #include <string.h> #include "xalloc.h" -#include "xstrndup.h" char * base_name (char const *name) { char const *base = last_component (name); - size_t length; - - /* If there is no last component, then name is a file system root or the - empty string. */ - if (! *base) - return xstrndup (name, base_len (name)); - - /* Collapse a sequence of trailing slashes into one. */ - length = base_len (base); - if (ISSLASH (base[length])) - length++; - - /* On systems with drive letters, "a/b:c" must return "./b:c" rather - than "b:c" to avoid confusion with a drive letter. On systems - with pure POSIX semantics, this is not an issue. */ - if (FILE_SYSTEM_PREFIX_LEN (base)) + idx_t length; + int dotslash_len; + if (*base) + { + length = base_len (base); + + /* Collapse a sequence of trailing slashes into one. */ + length += ISSLASH (base[length]); + + /* On systems with drive letters, "a/b:c" must return "./b:c" rather + than "b:c" to avoid confusion with a drive letter. On systems + with pure POSIX semantics, this is not an issue. */ + dotslash_len = FILE_SYSTEM_PREFIX_LEN (base) != 0 ? 2 : 0; + } + else + { + /* There is no last component, so NAME is a file system root or + the empty string. */ + base = name; + length = base_len (base); + dotslash_len = 0; + } + + char *p = ximalloc (dotslash_len + length + 1); + if (dotslash_len) { - char *p = xmalloc (length + 3); p[0] = '.'; p[1] = '/'; - memcpy (p + 2, base, length); - p[length + 2] = '\0'; - return p; } /* Finally, copy the basename. */ - return xstrndup (base, length); + memcpy (p + dotslash_len, base, length); + p[dotslash_len + length] = '\0'; + return p; } |