| 1 |
|
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
|
| 6 |
package canonicaljson |
| 7 |
|
| 8 |
import "bytes" |
| 9 |
|
| 10 |
func newline(dst *bytes.Buffer, prefix, indent string, depth int) { |
| 11 |
dst.WriteByte('\n') |
| 12 |
dst.WriteString(prefix) |
| 13 |
for i := 0; i < depth; i++ { |
| 14 |
dst.WriteString(indent) |
| 15 |
} |
| 16 |
} |
| 17 |
|
| 18 |
|
| 19 |
|
| 20 |
|
| 21 |
|
| 22 |
|
| 23 |
|
| 24 |
|
| 25 |
|
| 26 |
|
| 27 |
|
| 28 |
|
| 29 |
func addIndentation(dst *bytes.Buffer, src []byte, prefix, indent string) error { |
| 30 |
origLen := dst.Len() |
| 31 |
var scan scanner |
| 32 |
scan.reset() |
| 33 |
needIndent := false |
| 34 |
depth := 0 |
| 35 |
for _, c := range src { |
| 36 |
scan.bytes++ |
| 37 |
v := scan.step(&scan, c) |
| 38 |
if v == scanSkipSpace { |
| 39 |
continue |
| 40 |
} |
| 41 |
if v == scanError { |
| 42 |
break |
| 43 |
} |
| 44 |
if needIndent && v != scanEndObject && v != scanEndArray { |
| 45 |
needIndent = false |
| 46 |
depth++ |
| 47 |
newline(dst, prefix, indent, depth) |
| 48 |
} |
| 49 |
|
| 50 |
|
| 51 |
|
| 52 |
if v == scanContinue { |
| 53 |
dst.WriteByte(c) |
| 54 |
continue |
| 55 |
} |
| 56 |
|
| 57 |
|
| 58 |
switch c { |
| 59 |
case '{', '[': |
| 60 |
|
| 61 |
needIndent = true |
| 62 |
dst.WriteByte(c) |
| 63 |
|
| 64 |
case ',': |
| 65 |
dst.WriteByte(c) |
| 66 |
newline(dst, prefix, indent, depth) |
| 67 |
|
| 68 |
case ':': |
| 69 |
dst.WriteByte(c) |
| 70 |
dst.WriteByte(' ') |
| 71 |
|
| 72 |
case '}', ']': |
| 73 |
if needIndent { |
| 74 |
|
| 75 |
needIndent = false |
| 76 |
} else { |
| 77 |
depth-- |
| 78 |
newline(dst, prefix, indent, depth) |
| 79 |
} |
| 80 |
dst.WriteByte(c) |
| 81 |
|
| 82 |
default: |
| 83 |
dst.WriteByte(c) |
| 84 |
} |
| 85 |
} |
| 86 |
if scan.eof() == scanError { |
| 87 |
dst.Truncate(origLen) |
| 88 |
return scan.err |
| 89 |
} |
| 90 |
return nil |
| 91 |
} |