blob: 44ba3e60d4fb148de04e4fbd016af62a0e711fef [file] [log] [blame]
Lev Walkin79f54952004-08-13 16:58:19 +00001#include <asn1c_compat.h>
2
3#include <string.h>
4#include <errno.h>
5
6#ifdef HAVE_SYS_PARAM_H
7#include <sys/param.h> /* For MAXPATHLEN */
8#endif
9
10#ifndef MAXPATHLEN
11#define MAXPATHLEN 1024
12#endif
13
14char *
15a1c_basename(const char *path) {
16 static char strbuf[MAXPATHLEN];
17 const char *pend;
18 const char *name;
19
20 pend = path + strlen(path);
21 if(pend == path) {
22 strcpy(strbuf, ".");
23 return strbuf;
24 }
25
26 /* Skip tailing slashes */
27 for(pend--; pend > path && *pend == '/'; pend--);
28
29 if(pend == path && *path == '/') {
30 strcpy(strbuf, "/");
31 return strbuf;
32 }
33
34 for(name = pend; name > path && name[-1] != '/'; name--);
35
36 if((pend - name) >= sizeof(strbuf) - 1) {
37 errno = ENAMETOOLONG;
38 return 0;
39 }
40
41 memcpy(strbuf, name, pend - name + 1);
42 strbuf[pend - name + 1] = '\0';
43
44 return strbuf;
45}
46
47
48char *
49a1c_dirname(const char *path) {
50 static char strbuf[MAXPATHLEN];
51 const char *pend;
52 const char *last = 0;
53 int in_slash = 0;
54
55 /* One-pass determination of the last char of the pathname */
56 for(pend = path; ; pend++) {
Lev Walkin79f54952004-08-13 16:58:19 +000057 switch(*pend) {
58 case '\0': break;
59 case '/':
60 if(!in_slash) {
61 last = pend;
62 in_slash = 1;
63 }
64 continue;
65 default:
66 if(in_slash) in_slash = 0;
67 continue;
68 }
69 break;
70 }
Lev Walkin79f54952004-08-13 16:58:19 +000071
72 if(last <= path) {
73 strcpy(strbuf, *path == '/' ? "/" : ".");
74 return strbuf;
75 }
76
77 if(!last) {
78 strcpy(strbuf, "/");
79 return strbuf;
80 }
81
82 if((last - path) >= sizeof(strbuf)) {
83 errno = ENAMETOOLONG;
84 return 0;
85 }
86
87 memcpy(strbuf, path, last - path);
88 strbuf[last - path] = '\0';
89
90 return strbuf;
91}
92