use _GL_ATTRIBUTE_CONST and _GL_ATTRIBUTE_PURE
[gnulib.git] / lib / basename-lgpl.c
1 /* basename.c -- return the last element in a file name
2
3    Copyright (C) 1990, 1998-2001, 2003-2006, 2009-2011 Free Software
4    Foundation, Inc.
5
6    This program is free software: you can redistribute it and/or modify
7    it under the terms of the GNU General Public License as published by
8    the Free Software Foundation; either version 3 of the License, or
9    (at your option) any later version.
10
11    This program is distributed in the hope that it will be useful,
12    but WITHOUT ANY WARRANTY; without even the implied warranty of
13    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14    GNU General Public License for more details.
15
16    You should have received a copy of the GNU General Public License
17    along with this program.  If not, see <http://www.gnu.org/licenses/>.  */
18
19 #include <config.h>
20
21 #include "dirname.h"
22
23 #include <string.h>
24
25 /* The attribute __pure__ was added in gcc 2.96.  */
26 #undef _GL_ATTRIBUTE_PURE
27 #if __GNUC__ > 2 || (__GNUC__ == 2 && __GNUC_MINOR__ >= 96)
28 # define _GL_ATTRIBUTE_PURE __attribute__ ((__pure__))
29 #else
30 # define _GL_ATTRIBUTE_PURE /* empty */
31 #endif
32
33 /* Return the address of the last file name component of NAME.  If
34    NAME has no relative file name components because it is a file
35    system root, return the empty string.  */
36
37 char * _GL_ATTRIBUTE_PURE
38 last_component (char const *name)
39 {
40   char const *base = name + FILE_SYSTEM_PREFIX_LEN (name);
41   char const *p;
42   bool saw_slash = false;
43
44   while (ISSLASH (*base))
45     base++;
46
47   for (p = base; *p; p++)
48     {
49       if (ISSLASH (*p))
50         saw_slash = true;
51       else if (saw_slash)
52         {
53           base = p;
54           saw_slash = false;
55         }
56     }
57
58   return (char *) base;
59 }
60
61 /* Return the length of the basename NAME.  Typically NAME is the
62    value returned by base_name or last_component.  Act like strlen
63    (NAME), except omit all trailing slashes.  */
64
65 size_t
66 base_len (char const *name)
67 {
68   size_t len;
69   size_t prefix_len = FILE_SYSTEM_PREFIX_LEN (name);
70
71   for (len = strlen (name);  1 < len && ISSLASH (name[len - 1]);  len--)
72     continue;
73
74   if (DOUBLE_SLASH_IS_DISTINCT_ROOT && len == 1
75       && ISSLASH (name[0]) && ISSLASH (name[1]) && ! name[2])
76     return 2;
77
78   if (FILE_SYSTEM_DRIVE_PREFIX_CAN_BE_RELATIVE && prefix_len
79       && len == prefix_len && ISSLASH (name[prefix_len]))
80     return prefix_len + 1;
81
82   return len;
83 }