#include <k5-platform.h>
#ifdef _WIN32
#define WINDOWS_PATHS
#endif
#ifdef WINDOWS_PATHS
#define SEP '\\'
#define IS_SEPARATOR(c) ((c) == '\\' || (c) == '/')
#else
#define SEP '/'
#define IS_SEPARATOR(c) ((c) == '/')
#endif
static inline const char *
find_sep(const char *path)
{
#ifdef WINDOWS_PATHS
const char *slash, *backslash;
slash = strrchr(path, '/');
backslash = strrchr(path, '\\');
if (slash != NULL && backslash != NULL)
return (slash > backslash) ? slash : backslash;
else
return (slash != NULL) ? slash : backslash;
#else
return strrchr(path, '/');
#endif
}
long
k5_path_split(const char *path, char **parent_out, char **basename_out)
{
const char *pathstart, *sep, *pend, *bstart;
char *parent = NULL, *basename = NULL;
if (parent_out != NULL)
*parent_out = NULL;
if (basename_out != NULL)
*basename_out = NULL;
pathstart = path;
#ifdef WINDOWS_PATHS
if (*path != '\0' && path[1] == ':')
pathstart = path + 2;
#endif
sep = find_sep(pathstart);
if (sep != NULL) {
bstart = sep + 1;
pend = sep;
while (pend > pathstart && IS_SEPARATOR(pend[-1]))
pend--;
if (pend == pathstart)
pend = sep + 1;
} else {
bstart = pathstart;
pend = pathstart;
}
if (parent_out) {
parent = malloc(pend - path + 1);
if (parent == NULL)
return ENOMEM;
memcpy(parent, path, pend - path);
parent[pend - path] = '\0';
}
if (basename_out) {
basename = strdup(bstart);
if (basename == NULL) {
free(parent);
return ENOMEM;
}
}
if (parent_out)
*parent_out = parent;
if (basename_out)
*basename_out = basename;
return 0;
}
long
k5_path_join(const char *path1, const char *path2, char **path_out)
{
char *path, c;
int ret;
*path_out = NULL;
if (k5_path_isabs(path2) || *path1 == '\0') {
path = strdup(path2);
if (path == NULL)
return ENOMEM;
} else {
c = path1[strlen(path1) - 1];
if (IS_SEPARATOR(c) || IS_SEPARATOR(*path2))
ret = asprintf(&path, "%s%s", path1, path2);
else
ret = asprintf(&path, "%s%c%s", path1, SEP, path2);
if (ret < 0)
return ENOMEM;
}
*path_out = path;
return 0;
}
int
k5_path_isabs(const char *path)
{
#ifdef WINDOWS_PATHS
if (*path != '\0' && path[1] == ':')
path += 2;
return (*path == '/' || *path == '\\');
#else
return (*path == '/');
#endif
}