-
Notifications
You must be signed in to change notification settings - Fork 0
/
bool.go
99 lines (79 loc) · 1.54 KB
/
bool.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
package scale_codec
import (
"errors"
"fmt"
"io"
)
var ErrExpectedOneByteRead = errors.New("expected one byte read")
func BoolFromRawBytes(reader io.Reader) (*Bool, error) {
scaleBool := new(Bool)
if err := scaleBool.UnmarshalSCALE(reader); err != nil {
return nil, err
}
return scaleBool, nil
}
type Bool struct {
Value bool
}
func (Bool) New() Encodable {
return &Bool{}
}
func (b Bool) MarshalSCALE() ([]byte, error) {
var value byte = 0x00
if b.Value {
value = 0x01
}
return []byte{value}, nil
}
func (b *Bool) UnmarshalSCALE(byteReader io.Reader) error {
bValue := make([]byte, 1)
n, err := byteReader.Read(bValue)
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("%w: %v", ErrExpectedOneByteRead, n)
}
switch bValue[0] {
case 0x01:
b.Value = true
case 0x00:
b.Value = false
default:
return fmt.Errorf("unknown byte to decode bool: %v", bValue)
}
return nil
}
type OptionBool struct {
*Bool
}
func (o OptionBool) MarshalSCALE() ([]byte, error) {
if o.Bool == nil {
return []byte{0x00}, nil
}
if o.Bool.Value {
return []byte{0x01}, nil
}
return []byte{0x02}, nil
}
func (o *OptionBool) UnmarshalSCALE(r io.Reader) error {
bValue := make([]byte, 1)
n, err := r.Read(bValue)
if err != nil {
return err
}
if n != 1 {
return fmt.Errorf("%w: %v", ErrExpectedOneByteRead, n)
}
switch bValue[0] {
case 0x00:
o.Bool = nil
case 0x01:
o.Bool = &Bool{true}
case 0x02:
o.Bool = &Bool{false}
default:
return fmt.Errorf("unknown byte to decode bool: %v", bValue)
}
return nil
}