github.com/Ali-iotechsys/sqlboiler/v4@v4.0.0-20221208124957-6aec9a5f1f71/types/byte.go (about) 1 package types 2 3 import ( 4 "database/sql/driver" 5 "encoding/json" 6 "errors" 7 ) 8 9 // Byte is an alias for byte. 10 // Byte implements Marshal and Unmarshal. 11 type Byte byte 12 13 // String output your byte. 14 func (b Byte) String() string { 15 return string(b) 16 } 17 18 // UnmarshalJSON sets *b to a copy of data. 19 func (b *Byte) UnmarshalJSON(data []byte) error { 20 if b == nil { 21 return errors.New("json: unmarshal json on nil pointer to byte") 22 } 23 24 var x string 25 if err := json.Unmarshal(data, &x); err != nil { 26 return err 27 } 28 29 if len(x) > 1 { 30 return errors.New("json: cannot convert to byte, text len is greater than one") 31 } 32 33 *b = Byte(x[0]) 34 return nil 35 } 36 37 // MarshalJSON returns the JSON encoding of b. 38 func (b Byte) MarshalJSON() ([]byte, error) { 39 return []byte{'"', byte(b), '"'}, nil 40 } 41 42 // Value returns b as a driver.Value. 43 func (b Byte) Value() (driver.Value, error) { 44 return []byte{byte(b)}, nil 45 } 46 47 // Scan stores the src in *b. 48 func (b *Byte) Scan(src interface{}) error { 49 switch src.(type) { 50 case uint8: 51 *b = Byte(src.(uint8)) 52 case string: 53 *b = Byte(src.(string)[0]) 54 case []byte: 55 *b = Byte(src.([]byte)[0]) 56 default: 57 return errors.New("incompatible type for byte") 58 } 59 60 return nil 61 } 62 63 // Randomize for sqlboiler 64 func (b *Byte) Randomize(nextInt func() int64, fieldType string, shouldBeNull bool) { 65 if shouldBeNull { 66 *b = Byte(65) // Can't deal with a true 0-value 67 } 68 69 *b = Byte(nextInt()%60 + 65) // Can't deal with non-ascii characters in some databases 70 }