diff options
author | Rebecca Turner <rbt@sent.as> | 2024-03-28 16:26:42 -0700 |
---|---|---|
committer | Rebecca Turner <rbt@sent.as> | 2024-03-29 16:26:29 -0700 |
commit | a5a25894c152848d1a57f97b2ef5542ddf6cdb9d (patch) | |
tree | ea623d3e50f133b6f1d651847eef67e9172a3218 /src/libutil/escape-string.cc | |
parent | 5a54b0a20c80356de5098694353f506e73fb883f (diff) |
Move `escapeString` to its own file
Change-Id: Ie5c954ec73c46c9d3c679ef99a83a29cc7a08352
Diffstat (limited to 'src/libutil/escape-string.cc')
-rw-r--r-- | src/libutil/escape-string.cc | 40 |
1 files changed, 40 insertions, 0 deletions
diff --git a/src/libutil/escape-string.cc b/src/libutil/escape-string.cc new file mode 100644 index 000000000..8160403cd --- /dev/null +++ b/src/libutil/escape-string.cc @@ -0,0 +1,40 @@ +#include <iomanip> +#include <ostream> +#include <sstream> + +#include "ansicolor.hh" +#include "escape-char.hh" +#include "english.hh" +#include "escape-string.hh" +#include "print-elided.hh" + +namespace nix { + +std::ostream & +escapeString(std::ostream & str, const std::string_view string, size_t maxLength, bool ansiColors) +{ + size_t charsPrinted = 0; + if (ansiColors) + str << ANSI_MAGENTA; + str << "\""; + for (auto i = string.begin(); i != string.end(); ++i) { + if (charsPrinted >= maxLength) { + str << "\" "; + printElided(str, string.length() - charsPrinted, "byte", "bytes", ansiColors); + return str; + } + if (*i == '\"' || *i == '\\') str << "\\" << *i; + else if (*i == '\n') str << "\\n"; + else if (*i == '\r') str << "\\r"; + else if (*i == '\t') str << "\\t"; + else if (*i == '$' && *(i+1) == '{') str << "\\" << *i; + else str << *i; + charsPrinted++; + } + str << "\""; + if (ansiColors) + str << ANSI_NORMAL; + return str; +} + +}; // namespace nix |