2020-08-14 10:01:03 +03:00
|
|
|
package json
|
|
|
|
|
|
|
|
import (
|
|
|
|
"bytes"
|
|
|
|
)
|
|
|
|
|
2020-08-18 07:36:36 +03:00
|
|
|
func compact(dst *bytes.Buffer, src []byte, escape bool) error {
|
2021-03-11 07:09:49 +03:00
|
|
|
if len(src) == 0 {
|
|
|
|
return errUnexpectedEndOfJSON("", 0)
|
|
|
|
}
|
2020-08-14 10:01:03 +03:00
|
|
|
length := len(src)
|
|
|
|
for cursor := 0; cursor < length; cursor++ {
|
|
|
|
c := src[cursor]
|
|
|
|
switch c {
|
|
|
|
case ' ', '\t', '\n', '\r':
|
|
|
|
continue
|
|
|
|
case '"':
|
|
|
|
if err := dst.WriteByte(c); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
for {
|
|
|
|
cursor++
|
2020-08-18 07:36:36 +03:00
|
|
|
c := src[cursor]
|
|
|
|
if escape && (c == '<' || c == '>' || c == '&') {
|
|
|
|
if _, err := dst.WriteString(`\u00`); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
if _, err := dst.Write([]byte{hex[c>>4], hex[c&0xF]}); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
} else if err := dst.WriteByte(c); err != nil {
|
2020-08-14 10:01:03 +03:00
|
|
|
return err
|
|
|
|
}
|
2020-08-18 07:36:36 +03:00
|
|
|
switch c {
|
2020-08-14 10:01:03 +03:00
|
|
|
case '\\':
|
|
|
|
cursor++
|
|
|
|
if err := dst.WriteByte(src[cursor]); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
case '"':
|
|
|
|
goto LOOP_END
|
|
|
|
case nul:
|
|
|
|
return errUnexpectedEndOfJSON("string", int64(length))
|
|
|
|
}
|
|
|
|
}
|
|
|
|
default:
|
|
|
|
if err := dst.WriteByte(c); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
}
|
|
|
|
LOOP_END:
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
}
|