-
Notifications
You must be signed in to change notification settings - Fork 22
/
standard.go
89 lines (84 loc) · 2.3 KB
/
standard.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// Copyright (c) 2021 Tailscale Inc & AUTHORS All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package hujson
// IsStandard reports whether this is standard JSON
// by checking that there are no comments and no trailing commas.
func (v Value) IsStandard() bool {
return v.isStandard()
}
func (v *Value) isStandard() bool {
if !v.BeforeExtra.IsStandard() {
return false
}
if comp, ok := v.Value.(composite); ok {
for v2 := range comp.allValues() {
if !v2.isStandard() {
return false
}
}
if hasTrailingComma(comp) || !comp.afterExtra().IsStandard() {
return false
}
}
if !v.AfterExtra.IsStandard() {
return false
}
return true
}
// IsStandard reports whether this is standard JSON whitespace.
func (b Extra) IsStandard() bool {
return !b.hasComment()
}
func (b Extra) hasComment() bool {
return consumeWhitespace(b) < len(b)
}
// Minimize removes all whitespace, comments, and trailing commas from v,
// making it compliant with standard JSON per RFC 8259.
func (v *Value) Minimize() {
v.minimize()
v.UpdateOffsets()
}
func (v *Value) minimize() {
v.BeforeExtra = nil
if v2, ok := v.Value.(composite); ok {
for v3 := range v2.allValues() {
v3.minimize()
}
setTrailingComma(v2, false)
*v2.afterExtra() = nil
}
v.AfterExtra = nil
}
// Standardize strips any features specific to HuJSON from v,
// making it compliant with standard JSON per RFC 8259.
// All comments and trailing commas are replaced with a space character
// in order to preserve the original line numbers and byte offsets.
func (v *Value) Standardize() {
v.standardize()
v.UpdateOffsets() // should be noop if offsets are already correct
}
func (v *Value) standardize() {
v.BeforeExtra.standardize()
if comp, ok := v.Value.(composite); ok {
for v2 := range comp.allValues() {
v2.standardize()
}
if last := comp.lastValue(); last != nil && last.AfterExtra != nil {
*comp.afterExtra() = append(append(last.AfterExtra, ' '), *comp.afterExtra()...)
last.AfterExtra = nil
}
comp.afterExtra().standardize()
}
v.AfterExtra.standardize()
}
func (b *Extra) standardize() {
for i, c := range *b {
switch c {
case ' ', '\t', '\r', '\n':
// NOTE: Avoid changing '\n' to keep line numbers the same.
default:
(*b)[i] = ' '
}
}
}