-
Notifications
You must be signed in to change notification settings - Fork 123
/
plain.go
110 lines (83 loc) · 2.1 KB
/
plain.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
package parse
import (
"bytes"
"errors"
"fmt"
"io"
"math"
"strconv"
"unsafe"
"github.com/go-graphite/go-carbon/points"
)
// https://github.com/golang/go/issues/2632#issuecomment-66061057
func unsafeString(b []byte) string {
return *(*string)(unsafe.Pointer(&b))
}
func PlainLine(p []byte) ([]byte, float64, int64, error) {
p = bytes.Trim(p, " \n\r")
i1 := bytes.IndexByte(p, ' ')
if i1 < 1 {
return nil, 0, 0, fmt.Errorf("bad message: %#v", string(p))
}
i2 := bytes.IndexByte(p[i1+1:], ' ')
if i2 < 1 {
return nil, 0, 0, fmt.Errorf("bad message: %#v", string(p))
}
i2 += i1 + 1
i3 := len(p)
value, err := strconv.ParseFloat(unsafeString(p[i1+1:i2]), 64)
if err != nil || math.IsNaN(value) {
return nil, 0, 0, fmt.Errorf("bad message: %#v", string(p))
}
tsf, err := strconv.ParseFloat(unsafeString(p[i2+1:i3]), 64)
if err != nil || math.IsNaN(tsf) {
return nil, 0, 0, fmt.Errorf("bad message: %#v", string(p))
}
return p[:i1], value, int64(tsf), nil
}
func Plain(body []byte) ([]*points.Points, error) {
size := len(body)
offset := 0
result := make([]*points.Points, 0, 4)
MainLoop:
for offset < size {
lineEnd := bytes.IndexByte(body[offset:size], '\n')
if lineEnd < 0 {
return result, errors.New("unfinished line")
} else if lineEnd == 0 {
// skip empty line
offset++
continue MainLoop
}
name, value, timestamp, err := PlainLine(body[offset : offset+lineEnd+1])
offset += lineEnd + 1
if err != nil {
return result, err
}
result = append(result, points.OnePoint(string(name), value, timestamp))
}
return result, nil
}
// old version. for benchmarks only
func oldPlain(body []byte) ([]*points.Points, error) {
result := make([]*points.Points, 4)
reader := bytes.NewBuffer(body)
for {
line, err := reader.ReadBytes('\n')
if err != nil && err != io.EOF {
return result, err
}
if len(line) == 0 {
break
}
if line[len(line)-1] != '\n' {
return result, errors.New("unfinished line in file")
}
p, err := points.ParseText(string(line))
if err != nil {
return result, err
}
result = append(result, p)
}
return result, nil
}