-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathutils.c
122 lines (109 loc) · 2.14 KB
/
utils.c
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
112
113
114
115
116
117
118
119
120
121
122
//
// utils.c
//
// Copyright 2021 The Hook Programming Language Authors.
//
// This file is part of the Hook project.
// For detailed license information, please refer to the LICENSE file
// located in the root directory of this project.
//
#include "hook/utils.h"
#include <errno.h>
#include <stdlib.h>
#include <string.h>
#include "hook/memory.h"
#ifdef _WIN32
#include <windows.h>
#include <direct.h>
#else
#include <sys/stat.h>
#include <limits.h>
#endif
#ifdef __linux__
#include <linux/limits.h>
#endif
#ifdef __APPLE__
#include <sys/syslimits.h>
#endif
#ifdef _WIN32
#define PATH_MAX MAX_PATH
#endif
static void make_directory(char *path);
static void make_directory(char *path)
{
char *sep = strrchr(path, '/');
if (sep)
{
*sep = '\0';
make_directory(path);
*sep = '/';
}
#ifdef _WIN32
_mkdir(path);
#else
mkdir(path, 0777);
#endif
}
int hk_power_of_two_ceil(int n)
{
--n;
n |= n >> 1;
n |= n >> 2;
n |= n >> 4;
n |= n >> 8;
n |= n >> 16;
++n;
return n;
}
void hk_ensure_path(const char *filename)
{
char *sep = strrchr(filename, '/');
if (sep)
{
char path[PATH_MAX + 1];
hk_copy_cstring(path, filename, PATH_MAX);
path[sep - filename] = '\0';
make_directory(path);
}
}
bool hk_long_from_chars(long *result, const char *chars)
{
errno = 0;
char *end = (char *) chars;
long _result = strtol(chars, &end, 10);
if (errno == ERANGE)
return false;
if (*end)
return false;
*result = _result;
return true;
}
bool hk_double_from_chars(double *result, const char *chars, bool strict)
{
errno = 0;
char *end;
double _result = strtod(chars, &end);
if (errno == ERANGE)
return false;
if (strict && *end)
return false;
*result = _result;
return true;
}
void hk_copy_cstring(char *dest, const char *src, int max_len)
{
#ifdef _WIN32
strncpy_s(dest, max_len + 1, src, _TRUNCATE);
#else
strncpy(dest, src, max_len);
dest[max_len] = '\0';
#endif
}
char *hk_duplicate_cstring(const char *str)
{
int length = (int) strnlen(str, INT_MAX);
char *_str = (char *) hk_allocate(length + 1);
memcpy(_str, str, length);
_str[length] = '\0';
return _str;
}