-
Notifications
You must be signed in to change notification settings - Fork 0
/
cpp-utils.cpp
411 lines (356 loc) · 10.7 KB
/
cpp-utils.cpp
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
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
#ifdef _WIN32
#define _CRT_SECURE_NO_WARNINGS 1
#endif
#include <stdio.h>
#include <stdlib.h>
#include <assert.h>
#include <stdexcept>
#include <vector>
#include <sys/stat.h>
#ifdef _WIN32
#include <process.h>
#include <Windows.h>
#include <Userenv.h>
#pragma comment(lib, "userenv.lib")
#pragma comment(lib, "Advapi32.lib")
#else
#include <strings.h>
#include <sys/utsname.h>
#include <sys/time.h>
#include <sys/resource.h>
#endif
#include "cpp-utils.h"
// From Randy Sargent's public domain library, 2001-2012
#ifdef _WIN32
// Windows
#define ALLOWABLE_DIRECTORY_DELIMITERS "/\\"
#define DIRECTORY_DELIMITER '\\'
#define DIRECTORY_DELIMITER_STRING "\\"
#else
// UNIX
#define ALLOWABLE_DIRECTORY_DELIMITERS "/"
#define DIRECTORY_DELIMITER '/'
#define DIRECTORY_DELIMITER_STRING "/"
#endif
std::string filename_sans_directory(const std::string &filename)
{
size_t lastDirDelim = filename.find_last_of(ALLOWABLE_DIRECTORY_DELIMITERS);
// No directory delimiter, so return filename
if (lastDirDelim == std::string::npos) return filename;
// Return everything after the delimiter
return filename.substr(lastDirDelim+1);
}
std::string filename_directory(const std::string &filename)
{
size_t lastDirDelim = filename.find_last_of(ALLOWABLE_DIRECTORY_DELIMITERS);
// No directory delimiter, so return nothing
if (lastDirDelim == std::string::npos) return "";
// Return everything up to just before the last delimiter
return filename.substr(0, lastDirDelim);
}
std::string filename_sans_suffix(const std::string &filename)
{
// Find the last '.'
size_t lastDot = filename.find_last_of(".");
if (lastDot == std::string::npos) return filename;
// Find the last directory delimiter
size_t lastDirDelim = filename.find_last_of(ALLOWABLE_DIRECTORY_DELIMITERS);
if (lastDirDelim != std::string::npos &&
lastDot < lastDirDelim) {
// The last dot was inside the directory name, so return as is
return filename;
}
// Return everything up to the last dot
return filename.substr(0, lastDot);
}
std::string filename_suffix(const std::string &filename)
{
// Find the last '.'
size_t lastDot = filename.find_last_of(".");
if (lastDot == std::string::npos) return "";
// Find the last directory delimiter
size_t lastDirDelim = filename.find_last_of(ALLOWABLE_DIRECTORY_DELIMITERS);
if (lastDirDelim != std::string::npos &&
lastDot < lastDirDelim) {
// The last dot was inside the directory name, so no suffix
return "";
}
// Return everything after the last dot
return filename.substr(lastDot+1);
}
std::string filename_suffix_with_dot(const std::string &filename)
{
// Find the last '.'
size_t lastDot = filename.find_last_of(".");
if (lastDot == std::string::npos) return "";
// Find the last directory delimiter
size_t lastDirDelim = filename.find_last_of(ALLOWABLE_DIRECTORY_DELIMITERS);
if (lastDirDelim != std::string::npos &&
lastDot < lastDirDelim) {
// The last dot was inside the directory name, so no suffix
return "";
}
// Return everything starting with last dot
return filename.substr(lastDot);
}
std::string string_vprintf(const char *fmt, va_list args) {
size_t size = 500;
char *buf = (char *)malloc(size);
// grow the buffer size until the output is no longer truncated
while (1) {
va_list args_copy;
#if defined(_WIN32)
args_copy = args;
size_t nwritten = _vsnprintf(buf, size-1, fmt, args_copy);
#else
va_copy(args_copy, args);
size_t nwritten = vsnprintf(buf, size-1, fmt, args_copy);
#endif
// Some c libraries return -1 for overflow, some return a number larger than size-1
if (nwritten < size-2) {
buf[nwritten+1] = 0;
std::string ret(buf);
free(buf);
return ret;
}
size *= 2;
buf = (char *)realloc(buf, size);
}
}
std::string string_printf(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
std::string ret = string_vprintf(fmt, args);
va_end(args);
return ret;
}
void make_directory(const std::string &dirname) {
#ifdef _WIN32
_wmkdir(Unicode(dirname).path());
#else
mkdir(Unicode(dirname).path(), 0777);
#endif
}
void make_directory_and_parents(const std::string &dirname) {
if (dirname == "") return;
make_directory_and_parents(filename_directory(dirname));
make_directory(dirname);
}
bool filename_exists(const std::string &filename) {
#ifdef _WIN32
struct _stat64i32 s;
return (0 == _wstat(Unicode(filename).path(), &s));
#else
struct stat s;
return (0 == stat(Unicode(filename).path(), &s));
#endif
}
void rename_file(const std::string &src, const std::string &dest) {
#ifdef _WIN32
if (!MoveFileExW(Unicode(src).path(), Unicode(dest).path(), MOVEFILE_REPLACE_EXISTING)) {
throw_error("Can't rename %s to %s", src.c_str(), dest.c_str());
}
#else
if (rename(src.c_str(), dest.c_str())) {
throw_error("Can't rename %s to %s", src.c_str(), dest.c_str());
}
#endif
}
FILE *fopen_utf8(const std::string &filename, const char *mode) {
#ifdef _WIN32
return _wfopen(Unicode(filename).path(), Unicode(mode).path());
#else
return fopen(filename.c_str(), mode);
#endif
}
bool iequals(const std::string &a, const std::string &b)
{
#ifdef _WIN32
return !_stricmp(a.c_str(), b.c_str());
#else
return !strcasecmp(a.c_str(), b.c_str());
#endif
}
std::string temporary_path(const std::string &path)
{
// TODO(RS): make this thread-safe if we someday use threads
static unsigned int counter = 0;
static std::string cached_hostname;
if (!counter) cached_hostname = hostname();
#ifdef _WIN32
int pid = _getpid();
#else
int pid = getpid();
#endif
return string_printf("%s_%s_%d_%d_%d%s",
filename_sans_suffix(path).c_str(),
cached_hostname.c_str(),
(int) time(0),
pid,
counter++,
filename_suffix_with_dot(path).c_str());
}
#ifdef _WIN32
std::string hostname()
{
char buf[1000];
DWORD bufsize = sizeof(buf);
GetComputerNameExA(ComputerNameDnsHostname, buf, &bufsize);
return std::string(buf, bufsize);
}
#else
std::string hostname()
{
struct utsname u;
if (uname(&u)) {
perror("uname");
exit(1);
}
return u.nodename;
}
#endif
void throw_error(const char *fmt, ...) {
va_list args;
va_start(args, fmt);
std::string msg = string_vprintf(fmt, args);
va_end(args);
throw std::runtime_error(msg);
}
std::string executable_suffix() {
#ifdef _WIN32
return ".exe";
#else
return "";
#endif
}
///// executable_path
// From http://stackoverflow.com/questions/1023306/finding-current-executables-path-without-proc-self-exe
// Mac OS X: _NSGetExecutablePath() (man 3 dyld)
// Linux: readlink /proc/self/exe
// Solaris: getexecname()
// FreeBSD: sysctl CTL_KERN KERN_PROC KERN_PROC_PATHNAME -1
// BSD with procfs: readlink /proc/curproc/file
// Windows: GetModuleFileName() with hModule = NULL
#if defined(_WIN32)
std::string executable_path() {
wchar_t buf[10000];
DWORD bufsize = sizeof(buf);
GetModuleFileNameW(NULL, buf, bufsize);
return Unicode(buf).utf8();
}
#elif defined(__APPLE__)
#include <mach-o/dyld.h>
std::string executable_path() {
uint32_t len = 0;
int ret = _NSGetExecutablePath(NULL, &len);
assert(ret == -1);
std::vector<char> buf(len);
ret = _NSGetExecutablePath(&buf[0], &len);
return std::string(&buf[0]);
}
#else
// Linux
std::string executable_path() {
std::vector<char> buf(1000);
while (1) {
int ret = readlink("/proc/self/exe", &buf[0], buf.size());
assert(ret > 0);
if (ret < (int)buf.size()) return std::string(&buf[0], ret);
buf.resize(buf.size()*2);
}
}
#endif
///// home_directory
#ifdef _WIN32
std::string home_directory() {
TCHAR buf[10000]={0};
DWORD bufsize = sizeof(buf);
HANDLE token = 0;
OpenProcessToken(GetCurrentProcess(), TOKEN_QUERY, &token);
GetUserProfileDirectory(token, buf, &bufsize);
CloseHandle(token);
return Unicode(buf).utf8();
}
#else
// Linux or OS X
#include <unistd.h>
#include <sys/types.h>
#include <pwd.h>
std::string home_directory() {
struct passwd pwd, *pwdptr;
char buf[10000];
int ret = getpwuid_r(getuid(), &pwd, buf, sizeof(buf), &pwdptr);
assert(ret == 0 && pwdptr);
return pwdptr->pw_dir;
}
#endif
///// application_user_state_directory
#if defined(_WIN32)
std::string application_user_state_directory(const std::string &application_name) {
return home_directory() + "/Application Data/" + application_name;
}
#elif defined(__APPLE__)
std::string application_user_state_directory(const std::string &application_name) {
return home_directory() + "/Library/Application Support/" + application_name;
}
#endif
///// Unicode paths
Unicode::Unicode(const std::string &utf8) : m_utf8(utf8) {
init_from_utf8();
}
Unicode::Unicode(const char *utf8) : m_utf8(utf8) {
init_from_utf8();
}
const char *Unicode::utf8() { return m_utf8.c_str(); }
#ifdef _WIN32
Unicode::Unicode(const wchar_t *utf16) : m_utf16(utf16, utf16+wcslen(utf16)+1) {
std::vector<char> tmp(m_utf16.size() * 4);
// TODO(PD) or TODO(RS): patch from Paul Heckbert's code
wcstombs(&tmp[0], utf16, tmp.size());
m_utf8 = std::string(&tmp[0]);
}
const wchar_t *Unicode::utf16() { return &m_utf16[0]; }
void Unicode::init_from_utf8() {
// calculate size of output buffer (this includes terminating NULL)
int nchars = MultiByteToWideChar(CP_UTF8, 0, m_utf8.c_str(), -1, NULL, 0);
assert(nchars>0);
m_utf16.resize(nchars);
// see http://msdn.microsoft.com/en-us/library/windows/desktop/dd319072%28v=vs.85%29.aspx
// this time, do the conversion and write to m_utf16
int nchars_written = MultiByteToWideChar(CP_UTF8, 0, m_utf8.c_str(), -1, &m_utf16[0], nchars);
assert(nchars_written == nchars);
}
const wchar_t *Unicode::path() { return utf16(); }
#else
void Unicode::init_from_utf8() {}
const char *Unicode::path() { return utf8(); }
#endif
#if defined(__APPLE__)
std::string os() { return "osx"; }
#elif defined(_WIN32)
std::string os() { return "windows"; }
#else
std::string os() { return "linux"; }
#endif
#if defined(_WIN32)
double filetime_to_double(struct _FILETIME &ft) {
unsigned long long t = ft.dwLowDateTime + ((unsigned long long)ft.dwHighDateTime << 32);
return t / 1e7;
}
void get_cpu_usage(double &user, double &system) {
struct _FILETIME creation_time, exit_time, kernel_time, user_time;
GetProcessTimes(GetCurrentProcess(), &creation_time, &exit_time, &kernel_time, &user_time);
user = filetime_to_double(user_time);
system = filetime_to_double(kernel_time);
}
#else
double tv_to_double(struct timeval &tv) {
return tv.tv_sec + tv.tv_usec / 1e6;
}
void get_cpu_usage(double &user, double &system) {
struct rusage usage;
getrusage(RUSAGE_SELF, &usage);
user = tv_to_double(usage.ru_utime);
system = tv_to_double(usage.ru_stime);
}
#endif