Implement JSON string escape in pure-awk (several orders of magnitude faster)

I've got a very pathological branch of a certain repository where this makes a parallelized (four concurrent invocations) generation change from ~3 _minutes_ down to ~13 _seconds_.
This commit is contained in:
Tianon Gravi 2022-07-13 16:39:56 -07:00
parent 92ab34bccf
commit 9f6a35772a
1 changed files with 7 additions and 12 deletions

View File

@ -3,18 +3,13 @@
# see https://github.com/docker-library/php or https://github.com/docker-library/golang for examples of usage ("apply-templates.sh")
# escape an arbitrary string for passing back to jq as program input
function jq_escape(str, # parameters
prog, e, out) # locals
{
prog = "jq --raw-input --slurp ."
printf "%s", str |& prog
close(prog, "to")
prog |& getline out
e = close(prog)
if (e != 0) {
exit(e)
}
return out
function jq_escape(str) {
gsub(/\\/, "\\\\", str)
gsub(/\n/, "\\n", str)
gsub(/\r/, "\\r", str)
gsub(/\t/, "\\t", str)
gsub(/"/, "\\\"", str)
return "\"" str "\""
}
# return the number of times needle appears in haystack