forked from volatiletech/sqlboiler
-
Notifications
You must be signed in to change notification settings - Fork 0
/
byte.go
72 lines (58 loc) · 1.49 KB
/
byte.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
package types
import (
"database/sql/driver"
"encoding/json"
"errors"
"github.com/volatiletech/sqlboiler/randomize"
)
// Byte is an alias for byte.
// Byte implements Marshal and Unmarshal.
type Byte byte
// String output your byte.
func (b Byte) String() string {
return string(b)
}
// UnmarshalJSON sets *b to a copy of data.
func (b *Byte) UnmarshalJSON(data []byte) error {
if b == nil {
return errors.New("json: unmarshal json on nil pointer to byte")
}
var x string
if err := json.Unmarshal(data, &x); err != nil {
return err
}
if len(x) > 1 {
return errors.New("json: cannot convert to byte, text len is greater than one")
}
*b = Byte(x[0])
return nil
}
// MarshalJSON returns the JSON encoding of b.
func (b Byte) MarshalJSON() ([]byte, error) {
return []byte{'"', byte(b), '"'}, nil
}
// Value returns b as a driver.Value.
func (b Byte) Value() (driver.Value, error) {
return []byte{byte(b)}, nil
}
// Scan stores the src in *b.
func (b *Byte) Scan(src interface{}) error {
switch src.(type) {
case uint8:
*b = Byte(src.(uint8))
case string:
*b = Byte(src.(string)[0])
case []byte:
*b = Byte(src.([]byte)[0])
default:
return errors.New("incompatible type for byte")
}
return nil
}
// Randomize for sqlboiler
func (b *Byte) Randomize(seed *randomize.Seed, fieldType string, shouldBeNull bool) {
if shouldBeNull {
*b = Byte(65) // Can't deal with a true 0-value
}
*b = Byte(seed.NextInt()%60 + 65) // Can't deal with non-ascii characters in some databases
}