forked from kanaka/mal
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathString.cpp
88 lines (80 loc) · 2.05 KB
/
String.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
#include "Debug.h"
#include "String.h"
#include <stdarg.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// Adapted from: http://stackoverflow.com/questions/2342162
String stringPrintf(const char* fmt, ...) {
int size = strlen(fmt); // make a guess
String str;
va_list ap;
while (1) {
str.resize(size);
va_start(ap, fmt);
int n = vsnprintf((char *)str.data(), size, fmt, ap);
va_end(ap);
if (n > -1 && n < size) { // Everything worked
str.resize(n);
return str;
}
if (n > -1) // Needed size returned
size = n + 1; // For null char
else
size *= 2; // Guess at a larger size (OS specific)
}
return str;
}
String copyAndFree(char* mallocedString)
{
String ret(mallocedString);
free(mallocedString);
return ret;
}
String escape(const String& in)
{
String out;
out.reserve(in.size() * 2 + 2); // each char may get escaped + two "'s
out += '"';
for (auto it = in.begin(), end = in.end(); it != end; ++it) {
char c = *it;
switch (c) {
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '"': out += "\\\""; break;
default: out += c; break;
};
}
out += '"';
out.shrink_to_fit();
return out;
}
static char unescape(char c)
{
switch (c) {
case '\\': return '\\';
case 'n': return '\n';
case '"': return '"';
default: return c;
}
}
String unescape(const String& in)
{
String out;
out.reserve(in.size()); // unescaped string will always be shorter
// in will have double-quotes at either end, so move the iterators in
for (auto it = in.begin()+1, end = in.end()-1; it != end; ++it) {
char c = *it;
if (c == '\\') {
++it;
if (it != end) {
out += unescape(*it);
}
}
else {
out += c;
}
}
out.shrink_to_fit();
return out;
}