From 55c58580be89e0f7ec6519bd7a7f2cded4fab382 Mon Sep 17 00:00:00 2001 From: Robert Hensing Date: Thu, 6 Jan 2022 14:31:23 +0100 Subject: Add withBuffer ... to avoid non-standard, unidiomatic alloca. --- src/libstore/derivations.cc | 30 ++++++++++++------------------ src/libutil/util.hh | 9 +++++++++ 2 files changed, 21 insertions(+), 18 deletions(-) (limited to 'src') diff --git a/src/libstore/derivations.cc b/src/libstore/derivations.cc index 616e78076..21ea84dbf 100644 --- a/src/libstore/derivations.cc +++ b/src/libstore/derivations.cc @@ -272,25 +272,19 @@ Derivation parseDerivation(const Store & store, std::string && s, std::string_vi static void printString(string & res, std::string_view s) { - char * buf; size_t bufSize = s.size() * 2 + 2; - std::unique_ptr dynBuf; - if (bufSize < 0x10000) { - buf = (char *)alloca(bufSize); - } else { - dynBuf = decltype(dynBuf)(new char[bufSize]); - buf = dynBuf.get(); - } - char * p = buf; - *p++ = '"'; - for (auto c : s) - if (c == '\"' || c == '\\') { *p++ = '\\'; *p++ = c; } - 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); + withBuffer(bufSize, [&](char buf[]) { + char * p = buf; + *p++ = '"'; + for (auto c : s) + if (c == '\"' || c == '\\') { *p++ = '\\'; *p++ = c; } + 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); + }); } diff --git a/src/libutil/util.hh b/src/libutil/util.hh index 369c44f78..840acd67b 100644 --- a/src/libutil/util.hh +++ b/src/libutil/util.hh @@ -671,5 +671,14 @@ template overloaded(Ts...) -> overloaded; std::string showBytes(uint64_t bytes); +template inline R withBuffer(size_t size, std::function fun) { + if (size < 0x10000) { + T buf[size]; + return fun(buf); + } else { + auto buf = std::unique_ptr(new T[size]); + return fun(buf.get()); + } +} } -- cgit v1.2.3