-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathparsevalue.go
More file actions
76 lines (69 loc) · 1.75 KB
/
parsevalue.go
File metadata and controls
76 lines (69 loc) · 1.75 KB
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
package inifile
import (
"errors"
"strconv"
"strings"
)
// ParseValue parses a value string from an INI-file, unquoting and removing trailing comments if needed.
// Parsed values are always valid UTF-8.
func ParseValue(s string) (value string, err error) {
if value = strings.TrimSpace(s); len(value) > 0 {
switch value[0] {
case '"':
value, err = parseDoubleQuotedValue(value)
case '\'':
value, err = parseSingleQuotedValue(value)
default:
value = parseUnquotedValue(value)
}
value = strings.ToValidUTF8(value, "\uFFFD")
}
return
}
func validateTail(tail string) (err error) {
tail = strings.TrimSpace(tail)
if tail != "" && tail[0] != ';' && tail[0] != '#' {
err = strconv.ErrSyntax
}
return
}
func parseDoubleQuotedValue(value string) (result string, err error) {
var quoted string
if quoted, err = strconv.QuotedPrefix(value); err == nil {
if err = validateTail(value[len(quoted):]); err == nil {
result, err = strconv.Unquote(quoted)
}
}
return
}
func parseSingleQuotedValue(value string) (result string, err error) {
var tail string
if result, tail, err = parseSingleQuoted(value); err == nil {
err = validateTail(tail)
}
return
}
func parseSingleQuoted(value string) (result, tail string, err error) {
var b strings.Builder
b.Grow(len(value))
value = value[1:]
for err == nil && len(value) > 0 {
if value[0] == '\'' {
result = b.String()
tail = value[1:]
return
}
var singlebyte rune
if singlebyte, _, value, err = strconv.UnquoteChar(value, '\''); err == nil {
b.WriteRune(singlebyte)
}
}
err = errors.Join(err, strconv.ErrSyntax)
return
}
func parseUnquotedValue(value string) string {
if idx := strings.IndexAny(value, ";#"); idx >= 0 {
value = strings.TrimSpace(value[:idx])
}
return value
}