Add withBuffer

... to avoid non-standard, unidiomatic alloca.
This commit is contained in:
Robert Hensing 2022-01-06 14:31:23 +01:00
parent d038a67bd3
commit 55c58580be
2 changed files with 21 additions and 18 deletions

View file

@ -272,25 +272,19 @@ Derivation parseDerivation(const Store & store, std::string && s, std::string_vi
static void printString(string & res, std::string_view s) static void printString(string & res, std::string_view s)
{ {
char * buf;
size_t bufSize = s.size() * 2 + 2; size_t bufSize = s.size() * 2 + 2;
std::unique_ptr<char[]> dynBuf; withBuffer<void, char>(bufSize, [&](char buf[]) {
if (bufSize < 0x10000) { char * p = buf;
buf = (char *)alloca(bufSize); *p++ = '"';
} else { for (auto c : s)
dynBuf = decltype(dynBuf)(new char[bufSize]); if (c == '\"' || c == '\\') { *p++ = '\\'; *p++ = c; }
buf = dynBuf.get(); else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; }
} else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; }
char * p = buf; else if (c == '\t') { *p++ = '\\'; *p++ = 't'; }
*p++ = '"'; else *p++ = c;
for (auto c : s) *p++ = '"';
if (c == '\"' || c == '\\') { *p++ = '\\'; *p++ = c; } res.append(buf, p - buf);
else if (c == '\n') { *p++ = '\\'; *p++ = 'n'; } });
else if (c == '\r') { *p++ = '\\'; *p++ = 'r'; }
else if (c == '\t') { *p++ = '\\'; *p++ = 't'; }
else *p++ = c;
*p++ = '"';
res.append(buf, p - buf);
} }

View file

@ -671,5 +671,14 @@ template<class... Ts> overloaded(Ts...) -> overloaded<Ts...>;
std::string showBytes(uint64_t bytes); std::string showBytes(uint64_t bytes);
template<typename R = void, typename T = char> inline R withBuffer(size_t size, std::function<R (T[])> fun) {
if (size < 0x10000) {
T buf[size];
return fun(buf);
} else {
auto buf = std::unique_ptr<T[]>(new T[size]);
return fun(buf.get());
}
}
} }