-
Notifications
You must be signed in to change notification settings - Fork 11
/
compact.go
98 lines (93 loc) · 2.02 KB
/
compact.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
90
91
92
93
94
95
96
97
98
// Copyright 2015 Jean Niklas L'orange. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package edn
import (
"bytes"
"io"
)
func tokNeedsDelim(t tokenType) bool {
switch t {
case tokenString, tokenListStart, tokenListEnd, tokenVectorStart,
tokenVectorEnd, tokenMapEnd, tokenMapStart, tokenSetStart, tokenDiscard, tokenError:
return false
}
return true
}
func delimits(r rune) bool {
switch r {
case '{', '}', '[', ']', '(', ')', '\\', '"':
return true
}
return isWhitespace(r)
}
// Compact appends to dst a compacted form of the EDN-encoded src. It does not
// remove discard values.
func Compact(dst *bytes.Buffer, src []byte) error {
origLen := dst.Len()
var lex lexer
lex.reset()
buf := bytes.NewBuffer(src)
start, pos := 0, 0
needsDelim := false
prevIgnore := '\uFFFD'
r, size, err := buf.ReadRune()
for ; err == nil; r, size, err = buf.ReadRune() {
ls := lex.state(r)
ppos := pos
pos += size
switch ls {
case lexCont:
if ppos == start && needsDelim && !delimits(r) {
dst.WriteRune(prevIgnore)
}
continue
case lexIgnore:
prevIgnore = r
start = pos
case lexError:
dst.Truncate(origLen)
return lex.err
case lexEnd:
// here we might want to discard #_ and the like. Currently we don't.
dst.Write(src[start:pos])
needsDelim = tokNeedsDelim(lex.token)
lex.reset()
start = pos
case lexEndPrev:
dst.Write(src[start:ppos])
lex.reset()
lss := lex.state(r)
needsDelim = tokNeedsDelim(lex.token)
switch lss {
case lexIgnore:
prevIgnore = r
start = pos
case lexCont:
start = ppos
case lexEnd:
dst.WriteRune(r)
lex.reset()
start = pos
case lexEndPrev:
dst.Truncate(origLen)
return errInternal
case lexError:
dst.Truncate(origLen)
return lex.err
}
}
}
if err != io.EOF {
return err
}
ls := lex.eof()
switch ls {
case lexEnd:
dst.Write(src[start:pos])
case lexError:
dst.Truncate(origLen)
return lex.err
}
return nil
}