github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/encoding/json/indent.go (about)

     1  // Copyright 2010 The Go Authors.  All rights reserved.
     2  // Use of this source code is governed by a BSD-style
     3  // license that can be found in the LICENSE file.
     4  
     5  package json
     6  
     7  import "bytes"
     8  
     9  // Compact appends to dst the JSON-encoded src with
    10  // insignificant space characters elided.
    11  func Compact(dst *bytes.Buffer, src []byte) error {
    12  	return compact(dst, src, false)
    13  }
    14  
    15  func compact(dst *bytes.Buffer, src []byte, escape bool) error {
    16  	origLen := dst.Len()
    17  	var scan scanner
    18  	scan.reset()
    19  	start := 0
    20  	for i, c := range src {
    21  		if escape && (c == '<' || c == '>' || c == '&') {
    22  			if start < i {
    23  				dst.Write(src[start:i])
    24  			}
    25  			dst.WriteString(`\u00`)
    26  			dst.WriteByte(hex[c>>4])
    27  			dst.WriteByte(hex[c&0xF])
    28  			start = i + 1
    29  		}
    30  		// Convert U+2028 and U+2029 (E2 80 A8 and E2 80 A9).
    31  		if c == 0xE2 && i+2 < len(src) && src[i+1] == 0x80 && src[i+2]&^1 == 0xA8 {
    32  			if start < i {
    33  				dst.Write(src[start:i])
    34  			}
    35  			dst.WriteString(`\u202`)
    36  			dst.WriteByte(hex[src[i+2]&0xF])
    37  			start = i + 3
    38  		}
    39  		v := scan.step(&scan, int(c))
    40  		if v >= scanSkipSpace {
    41  			if v == scanError {
    42  				break
    43  			}
    44  			if start < i {
    45  				dst.Write(src[start:i])
    46  			}
    47  			start = i + 1
    48  		}
    49  	}
    50  	if scan.eof() == scanError {
    51  		dst.Truncate(origLen)
    52  		return scan.err
    53  	}
    54  	if start < len(src) {
    55  		dst.Write(src[start:])
    56  	}
    57  	return nil
    58  }
    59  
    60  func newline(dst *bytes.Buffer, prefix, indent string, depth int) {
    61  	dst.WriteByte('\n')
    62  	dst.WriteString(prefix)
    63  	for i := 0; i < depth; i++ {
    64  		dst.WriteString(indent)
    65  	}
    66  }
    67  
    68  // Indent appends to dst an indented form of the JSON-encoded src.
    69  // Each element in a JSON object or array begins on a new,
    70  // indented line beginning with prefix followed by one or more
    71  // copies of indent according to the indentation nesting.
    72  // The data appended to dst does not begin with the prefix nor
    73  // any indentation, and has no trailing newline, to make it
    74  // easier to embed inside other formatted JSON data.
    75  func Indent(dst *bytes.Buffer, src []byte, prefix, indent string) error {
    76  	origLen := dst.Len()
    77  	var scan scanner
    78  	scan.reset()
    79  	needIndent := false
    80  	depth := 0
    81  	for _, c := range src {
    82  		scan.bytes++
    83  		v := scan.step(&scan, int(c))
    84  		if v == scanSkipSpace {
    85  			continue
    86  		}
    87  		if v == scanError {
    88  			break
    89  		}
    90  		if needIndent && v != scanEndObject && v != scanEndArray {
    91  			needIndent = false
    92  			depth++
    93  			newline(dst, prefix, indent, depth)
    94  		}
    95  
    96  		// Emit semantically uninteresting bytes
    97  		// (in particular, punctuation in strings) unmodified.
    98  		if v == scanContinue {
    99  			dst.WriteByte(c)
   100  			continue
   101  		}
   102  
   103  		// Add spacing around real punctuation.
   104  		switch c {
   105  		case '{', '[':
   106  			// delay indent so that empty object and array are formatted as {} and [].
   107  			needIndent = true
   108  			dst.WriteByte(c)
   109  
   110  		case ',':
   111  			dst.WriteByte(c)
   112  			newline(dst, prefix, indent, depth)
   113  
   114  		case ':':
   115  			dst.WriteByte(c)
   116  			dst.WriteByte(' ')
   117  
   118  		case '}', ']':
   119  			if needIndent {
   120  				// suppress indent in empty object/array
   121  				needIndent = false
   122  			} else {
   123  				depth--
   124  				newline(dst, prefix, indent, depth)
   125  			}
   126  			dst.WriteByte(c)
   127  
   128  		default:
   129  			dst.WriteByte(c)
   130  		}
   131  	}
   132  	if scan.eof() == scanError {
   133  		dst.Truncate(origLen)
   134  		return scan.err
   135  	}
   136  	return nil
   137  }