Debian Codegraph @

indent.go

raw symbols SCIP
1 // Copyright 2016 Richard Gibson. All rights reserved.
2 // Copyright 2010 The Go Authors. All rights reserved.
3 // Use of this source code is governed by a BSD-style
4 // license that can be found in the LICENSE file.
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 // addIndentation appends to dst an indented form of the JSON-encoded src.
19 // Each element in a JSON object or array begins on a new,
20 // indented line beginning with prefix followed by one or more
21 // copies of indent according to the indentation nesting.
22 // The data appended to dst does not begin with the prefix nor
23 // any indentation, to make it easier to embed inside other formatted JSON data.
24 // Although leading space characters (space, tab, carriage return, newline)
25 // at the beginning of src are dropped, trailing space characters
26 // at the end of src are preserved and copied to dst.
27 // For example, if src has no trailing spaces, neither will dst;
28 // if src ends in a trailing newline, so will dst.
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 // Emit semantically uninteresting bytes
51 // (in particular, punctuation in strings) unmodified.
52 if v == scanContinue {
53 dst.WriteByte(c)
54 continue
55 }
56
57 // Add spacing around real punctuation.
58 switch c {
59 case '{', '[':
60 // delay indent so that empty object and array are formatted as {} and [].
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 // suppress indent in empty object/array
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 }