-
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathtype_fixed.go
81 lines (65 loc) · 1.32 KB
/
type_fixed.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
package parco
import "io"
type (
fixedType[T any] struct {
byteLength int
parser ParserFunc[T]
compiler CompilerFunc[T]
pool Pooler
}
)
func (i fixedType[T]) ByteLength() int {
return i.byteLength
}
func (i fixedType[T]) ParseBytes(data []byte) (res T, err error) {
return i.parser(data)
}
func (i fixedType[T]) Parse(r io.Reader) (res T, err error) {
box := i.pool.Get(i.byteLength)
defer i.pool.Put(box)
data := *box
data = data[:i.byteLength]
read, err := r.Read(data)
if err != nil {
return
}
if read != i.byteLength {
// TODO: wrap
err = ErrCannotRead
return
}
return i.parser(data)
}
func (i fixedType[T]) Compile(item T, w io.Writer) (err error) {
box := i.pool.Get(i.byteLength)
defer i.pool.Put(box)
data := *box
data = data[:i.byteLength]
if err = i.CompileBytes(item, data); err != nil {
return err
}
written, err := w.Write(data)
if err != nil {
return
}
if written != i.byteLength {
err = ErrCannotWrite
return
}
return
}
func (i fixedType[T]) CompileBytes(data T, box []byte) error {
return i.compiler(data, box)
}
func NewFixedType[T any](
byteLength int,
parserFunc ParserFunc[T],
compilerFunc CompilerFunc[T],
) Type[T] {
return fixedType[T]{
byteLength: byteLength,
parser: parserFunc,
compiler: compilerFunc,
pool: SinglePool,
}
}