summaryrefslogtreecommitdiff
path: root/legacy/evil/src/lib/evil_libgen.c
blob: 3913050237f1ab83ca4cf4ff91adb4a007ee327e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
#ifdef HAVE_CONFIG_H
# include "config.h"
#endif /* HAVE_CONFIG_H */

#include <string.h>

#include "Evil.h"

char _evil_basename_buf[PATH_MAX];
char _evil_dirname_buf[PATH_MAX];

char *
evil_basename(char *path)
{
   char *p1;
   char *p2;
   size_t length;

   /* path must begin by "?:\" or "?:/" */
   if ((!path) ||
       (strlen(path) <= 3) ||
       ((path[0] < 'a' || path[0] > 'z') && (path[0] < 'A' || path[0] > 'Z')) ||
       (path[1] != ':') ||
       ((path[2] != '/') && (path[2] != '\\')))
     {
        memcpy(_evil_basename_buf, "C:\\", 4);
        return _evil_basename_buf;
     }

   /* '/' --> '\\' */
   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_evil_basename_buf, "C:\\", 4);
        return _evil_basename_buf;
     }
   p2 = p1;
   while (*p2)
     {
        if (*p2 == '/') *p2 = '\\';
        p2++;
     }

   /* remove trailing backslashes */
   p2 = p1 + (length - 1);
   if (*p2 == '\\')
     {
       while (*p2 == '\\')
         p2--;
     }
   *(p2 + 1) = '\0';

   p2 = strrchr(p1, '\\');
   memcpy(_evil_basename_buf, p2 + 1, (p1 + length + 1) - p2);

   free(p1);

   return _evil_basename_buf;
}

char *
evil_dirname(char *path)
{
   char *p1;
   char *p2;
   size_t length;

   /* path must begin by "?:\" or "?:/" */
   if ((!path) ||
       (strlen(path) <= 3) ||
       ((path[0] < 'a' || path[0] > 'z') && (path[0] < 'A' || path[0] > 'Z')) ||
       (path[1] != ':') ||
       ((path[2] != '/') && (path[2] != '\\')))
     {
        memcpy(_evil_dirname_buf, "C:\\", 4);
        return _evil_dirname_buf;
     }

   /* '/' --> '\\' */
   length = strlen(path);
   p1 = strdup(path);
   if (!p1)
     {
        memcpy(_evil_dirname_buf, "C:\\", 4);
        return _evil_dirname_buf;
     }
   p2 = p1;
   while (*p2)
     {
        if (*p2 == '/') *p2 = '\\';
        p2++;
     }

   /* remove trailing backslashes */
   p2 = p1 + (length - 1);
   if (*p2 == '\\')
     {
       while (*p2 == '\\')
         p2--;
     }
   *(p2 + 1) = '\0';

   p2 = strrchr(p1, '\\');
   *p2 = '\0';
   memcpy(_evil_dirname_buf, p1, strlen(p1) + 1);

   free(p1);

   return _evil_dirname_buf;
}