Commit 6a4d2313 authored by Kirill Smelkov's avatar Kirill Smelkov

X xfmt/py: Speedup

it is annoying to see this function high in fstail profiles taking up to 10%

name       old time/op    new time/op    delta
PyQuote-4    1.33µs ± 1%    0.98µs ± 0%  -26.77%  (p=0.008 n=5+5)

name       old alloc/op   new alloc/op   delta
PyQuote-4     0.00B          0.00B          ~     (all equal)

name       old allocs/op  new allocs/op  delta
PyQuote-4      0.00           0.00          ~     (all equal)
parent 72bc3bf4
......@@ -31,23 +31,20 @@ func AppendQuotePyBytes(buf, b []byte) []byte {
// smartquotes: choose ' or " as quoting character
// https://github.com/python/cpython/blob/v2.7.13-116-g1aa1803b3d/Objects/stringobject.c#L947
quote := byte('\'')
noquote := byte('"')
if bytes.ContainsRune(b, '\'') && !bytes.ContainsRune(b, '"') {
quote, noquote = noquote, quote
quote = '"'
}
buf = append(buf, quote)
for len(b) > 0 {
r, size := utf8.DecodeRune(b)
switch r {
case utf8.RuneError:
buf = append(buf, '\\', 'x', hexdigits[b[0]>>4], hexdigits[b[0]&0xf])
case '\\', rune(quote):
buf = append(buf, '\\', byte(r))
case rune(noquote):
buf = append(buf, noquote)
c := b[0]
switch {
// fast path - ASCII only - trying to avoid UTF-8 decoding
case c < utf8.RuneSelf:
switch c {
case '\\', quote:
buf = append(buf, '\\', c)
// NOTE python converts to \<letter> only \t \n \r (not e.g. \v)
// https://github.com/python/cpython/blob/v2.7.13-116-g1aa1803b3d/Objects/stringobject.c#L963
......@@ -59,15 +56,28 @@ func AppendQuotePyBytes(buf, b []byte) []byte {
buf = append(buf, `\r`...)
default:
switch {
case r < ' ':
if c < ' ' || c == '\x7f' /* the only non-printable ASCII character > space */ {
// we already converted to \<letter> what python represents as such above
buf = append(buf, '\\', 'x', hexdigits[b[0]>>4], hexdigits[b[0]&0xf])
// everything else goes in numeric byte escapes
buf = append(buf, '\\', 'x', hexdigits[c>>4], hexdigits[c&0xf])
} else {
// printable ASCII
buf = append(buf, c)
}
}
case r < utf8.RuneSelf /* RuneSelf itself is not printable */ - 1:
// we already escaped all < RuneSelf runes
buf = append(buf, byte(r))
b = b[1:]
// slow path - full UTF-8 decoding
default:
r, size := utf8.DecodeRune(b)
switch r {
case utf8.RuneError:
buf = append(buf, '\\', 'x', hexdigits[c>>4], hexdigits[c&0xf])
default:
switch {
case strconv.IsPrint(r):
// printable utf-8 characters go as is
buf = append(buf, b[:size]...)
......@@ -82,6 +92,7 @@ func AppendQuotePyBytes(buf, b []byte) []byte {
b = b[size:]
}
}
buf = append(buf, quote)
return buf
......
Markdown is supported
0%
or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment