-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathattribute.go
126 lines (98 loc) · 2.19 KB
/
attribute.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
// Copyright (c) The RPSL Go Authors.
// SPDX-License-Identifier: Apache-2.0
package rpsl
import (
"fmt"
"strings"
)
type Attribute struct {
Name string
Value string
}
func newAttribute(name, value string) Attribute {
key := strings.ToLower(name)
var cleanedLines []string
lines := strings.Split(value, "\n")
for i, line := range lines {
if i > 0 && strings.HasPrefix(line, "+") {
line = line[1:]
}
if strings.Contains(line, "#") {
line = strings.Split(line, "#")[0]
}
line = strings.TrimSpace(line)
if line != "" {
cleanedLines = append(cleanedLines, line)
}
}
value = strings.Join(cleanedLines, " ")
return Attribute{Name: key, Value: value}
}
func parseAttributes(buf string) ([]Attribute, error) {
if buf == "" {
return nil, fmt.Errorf("object cannot be null")
}
var attributes []Attribute
var pos int
for pos < len(buf) {
key, newPos, err := parseKey(buf, pos)
pos = newPos
if err != nil {
return nil, err
}
value, newPos := parseValue(buf, pos)
pos = newPos
attributes = append(attributes, newAttribute(key, value))
}
return attributes, nil
}
func isValidKeyChar(c byte) bool {
return (c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || c == '-'
}
func isLineContinuationChar(c byte) bool {
return c == ' ' || c == '\t' || c == '+'
}
func parseKey(buf string, pos int) (string, int, error) {
start := pos
for pos < len(buf) {
c := buf[pos]
if c == ':' {
if pos == start {
return "", 0, fmt.Errorf("read zero sized key")
}
return buf[start:pos], pos + 1, nil
}
if !isValidKeyChar(c) {
return "", 0, fmt.Errorf("read illegal character in key: '%c'", c)
}
pos++
}
return "", 0, fmt.Errorf("no key found")
}
func parseValue(buf string, pos int) (string, int) {
start := pos
stop := pos
for pos < len(buf) {
c := buf[pos]
pos++
if c == '\r' {
continue
}
if c == '\n' && pos < len(buf) {
next := buf[pos]
if isLineContinuationChar(next) {
continue
}
break
}
stop = pos
}
return buf[start:stop], pos
}
func (a *Attribute) String() string {
var str strings.Builder
str.WriteString(a.Name)
str.WriteString(":")
str.WriteString(a.Value)
return str.String()
}