/
bytes.go
58 lines (46 loc) · 949 Bytes
/
bytes.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
package db
import (
"database/sql/driver"
"encoding/hex"
"fmt"
"github.com/Cepave/open-falcon-backend/common/types"
)
type Bytes16 types.Bytes16
// Supports hex string or bytes
func (b *Bytes16) Scan(src interface{}) error {
if src == nil {
return nil
}
var srcBytes []byte
switch srcValue := src.(type) {
case []byte:
srcBytes = srcValue
case string:
decodedHex, err := hex.DecodeString(srcValue)
if err != nil {
return err
}
srcBytes = decodedHex
default:
return fmt.Errorf("Needs type of \"[]byte\" or hex string. Got: %T", src)
}
if len(srcBytes) != 16 {
return fmt.Errorf("Needs len of \"[]byte\" to be 16. Got: %d", len(srcBytes))
}
copy(b[:], srcBytes)
return nil
}
func (b Bytes16) Value() (driver.Value, error) {
if b.IsNil() {
return driver.Null{}, nil
}
return b[:], nil
}
func (b Bytes16) IsNil() bool {
for _, v := range b {
if v != byte(0) {
return false
}
}
return true
}