-
Notifications
You must be signed in to change notification settings - Fork 0
/
char.go
61 lines (51 loc) · 1.25 KB
/
char.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
//
// @project GeniusRabbit
// @author Dmitry Ponomarev <[email protected]> 2016, 2020
//
package gosql
import "database/sql/driver"
// Char type of field
type Char rune
// Value implements the driver.Valuer interface, char field
func (f Char) Value() (driver.Value, error) {
if f == 0 {
return " ", nil
}
return string(f), nil
}
// Scan implements the sql.Scanner interface, char field
func (f *Char) Scan(value any) (err error) {
*f, err = decodeChar(value)
return err
}
// MarshalJSON implements the json.Marshaler
func (f Char) MarshalJSON() ([]byte, error) {
if f == 0 {
return []byte("\" \""), nil
}
return []byte{'"', byte(f), '"'}, nil
}
// UnmarshalJSON implements the json.Unmarshaller
func (f *Char) UnmarshalJSON(b []byte) (err error) {
*f, err = decodeChar(b)
return err
}
///////////////////////////////////////////////////////////////////////////////
/// Helpers
///////////////////////////////////////////////////////////////////////////////
func decodeChar(value any) (Char, error) {
if value == nil {
return Char(0), ErrNullValueNotAllowed
}
switch v := value.(type) {
case []byte:
if len(v) > 0 {
return Char(v[0]), nil
}
case string:
if len(v) > 0 {
return Char(v[0]), nil
}
}
return Char(0), ErrInvalidScan
}