1 package graphql
2
3 import (
4 "encoding/json"
5 "errors"
6 "fmt"
7 "io"
8 "strconv"
9 )
10
11 func MarshalUint(i uint) Marshaler {
12 return WriterFunc(func(w io.Writer) {
13 _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10))
14 })
15 }
16
17 func UnmarshalUint(v interface{}) (uint, error) {
18 switch v := v.(type) {
19 case string:
20 u64, err := strconv.ParseUint(v, 10, 64)
21 return uint(u64), err
22 case int:
23 if v < 0 {
24 return 0, errors.New("cannot convert negative numbers to uint")
25 }
26
27 return uint(v), nil
28 case int64:
29 if v < 0 {
30 return 0, errors.New("cannot convert negative numbers to uint")
31 }
32
33 return uint(v), nil
34 case json.Number:
35 u64, err := strconv.ParseUint(string(v), 10, 64)
36 return uint(u64), err
37 default:
38 return 0, fmt.Errorf("%T is not an uint", v)
39 }
40 }
41
42 func MarshalUint64(i uint64) Marshaler {
43 return WriterFunc(func(w io.Writer) {
44 _, _ = io.WriteString(w, strconv.FormatUint(i, 10))
45 })
46 }
47
48 func UnmarshalUint64(v interface{}) (uint64, error) {
49 switch v := v.(type) {
50 case string:
51 return strconv.ParseUint(v, 10, 64)
52 case int:
53 if v < 0 {
54 return 0, errors.New("cannot convert negative numbers to uint64")
55 }
56
57 return uint64(v), nil
58 case int64:
59 if v < 0 {
60 return 0, errors.New("cannot convert negative numbers to uint64")
61 }
62
63 return uint64(v), nil
64 case json.Number:
65 return strconv.ParseUint(string(v), 10, 64)
66 default:
67 return 0, fmt.Errorf("%T is not an uint", v)
68 }
69 }
70
71 func MarshalUint32(i uint32) Marshaler {
72 return WriterFunc(func(w io.Writer) {
73 _, _ = io.WriteString(w, strconv.FormatUint(uint64(i), 10))
74 })
75 }
76
77 func UnmarshalUint32(v interface{}) (uint32, error) {
78 switch v := v.(type) {
79 case string:
80 iv, err := strconv.ParseUint(v, 10, 32)
81 if err != nil {
82 return 0, err
83 }
84 return uint32(iv), nil
85 case int:
86 if v < 0 {
87 return 0, errors.New("cannot convert negative numbers to uint32")
88 }
89
90 return uint32(v), nil
91 case int64:
92 if v < 0 {
93 return 0, errors.New("cannot convert negative numbers to uint32")
94 }
95
96 return uint32(v), nil
97 case json.Number:
98 iv, err := strconv.ParseUint(string(v), 10, 32)
99 if err != nil {
100 return 0, err
101 }
102 return uint32(iv), nil
103 default:
104 return 0, fmt.Errorf("%T is not an uint", v)
105 }
106 }
107
View as plain text