1package graphql
2
3import (
4 "fmt"
5 "io"
6 "strconv"
7)
8
9const encodeHex = "0123456789ABCDEF"
10
11func MarshalString(s string) Marshaler {
12 return WriterFunc(func(w io.Writer) {
13 start := 0
14 io.WriteString(w, `"`)
15
16 for i, c := range s {
17 if c < 0x20 || c == '\\' || c == '"' {
18 io.WriteString(w, s[start:i])
19
20 switch c {
21 case '\t':
22 io.WriteString(w, `\t`)
23 case '\r':
24 io.WriteString(w, `\r`)
25 case '\n':
26 io.WriteString(w, `\n`)
27 case '\\':
28 io.WriteString(w, `\\`)
29 case '"':
30 io.WriteString(w, `\"`)
31 default:
32 io.WriteString(w, `\u00`)
33 w.Write([]byte{encodeHex[c>>4], encodeHex[c&0xf]})
34 }
35
36 start = i + 1
37 }
38 }
39
40 io.WriteString(w, s[start:])
41 io.WriteString(w, `"`)
42 })
43}
44func UnmarshalString(v interface{}) (string, error) {
45 switch v := v.(type) {
46 case string:
47 return v, nil
48 case int:
49 return strconv.Itoa(v), nil
50 case float64:
51 return fmt.Sprintf("%f", v), nil
52 case bool:
53 if v {
54 return "true", nil
55 } else {
56 return "false", nil
57 }
58 case nil:
59 return "null", nil
60 default:
61 return "", fmt.Errorf("%T is not a string", v)
62 }
63}