-
Notifications
You must be signed in to change notification settings - Fork 0
/
cast_byte.go
50 lines (41 loc) · 1 KB
/
cast_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
package pick
import (
"encoding/json"
)
func (c DefaultCaster) AsByte(input any) (byte, error) {
switch origin := input.(type) {
case byte:
return origin, nil
case int, int8, int16, int32, int64, uint, uint16, uint32, uint64, float32, float64, bool:
return c.uint8Caster.cast(input)
case string:
return byte(0), newCastError(ErrCastInvalidType, input)
case json.Number:
n, err := origin.Float64()
if err != nil {
return 0, newCastError(err, input)
}
return c.AsByte(n)
case []byte:
return c.AsByte(string(origin))
case nil:
return 0, nil
default:
// try to cast to basic (in case input is ~basic)
if basic, err := tryCastToBasicType(input); err == nil {
return c.AsByte(basic)
}
return tryReflectConvert[byte](input)
}
}
func (c DefaultCaster) AsByteSlice(input any) ([]byte, error) {
switch cc := input.(type) {
case []byte:
return cc, nil
case string:
return []byte(cc), nil
case json.RawMessage:
return []byte(cc), nil
}
return mapTo(input, mapOpFn(c.AsByte))
}