github.skymusic.top/99designs/gqlgen@v0.7.2/graphql/jsonw.go (about)

     1  package graphql
     2  
     3  import (
     4  	"io"
     5  	"strconv"
     6  )
     7  
     8  var nullLit = []byte(`null`)
     9  var trueLit = []byte(`true`)
    10  var falseLit = []byte(`false`)
    11  var openBrace = []byte(`{`)
    12  var closeBrace = []byte(`}`)
    13  var openBracket = []byte(`[`)
    14  var closeBracket = []byte(`]`)
    15  var colon = []byte(`:`)
    16  var comma = []byte(`,`)
    17  
    18  var Null = &lit{nullLit}
    19  var True = &lit{trueLit}
    20  var False = &lit{falseLit}
    21  
    22  type Marshaler interface {
    23  	MarshalGQL(w io.Writer)
    24  }
    25  
    26  type Unmarshaler interface {
    27  	UnmarshalGQL(v interface{}) error
    28  }
    29  
    30  type OrderedMap struct {
    31  	Keys   []string
    32  	Values []Marshaler
    33  }
    34  
    35  type WriterFunc func(writer io.Writer)
    36  
    37  func (f WriterFunc) MarshalGQL(w io.Writer) {
    38  	f(w)
    39  }
    40  
    41  func NewOrderedMap(len int) *OrderedMap {
    42  	return &OrderedMap{
    43  		Keys:   make([]string, len),
    44  		Values: make([]Marshaler, len),
    45  	}
    46  }
    47  
    48  func (m *OrderedMap) Add(key string, value Marshaler) {
    49  	m.Keys = append(m.Keys, key)
    50  	m.Values = append(m.Values, value)
    51  }
    52  
    53  func (m *OrderedMap) MarshalGQL(writer io.Writer) {
    54  	writer.Write(openBrace)
    55  	for i, key := range m.Keys {
    56  		if i != 0 {
    57  			writer.Write(comma)
    58  		}
    59  		io.WriteString(writer, strconv.Quote(key))
    60  		writer.Write(colon)
    61  		m.Values[i].MarshalGQL(writer)
    62  	}
    63  	writer.Write(closeBrace)
    64  }
    65  
    66  type Array []Marshaler
    67  
    68  func (a Array) MarshalGQL(writer io.Writer) {
    69  	writer.Write(openBracket)
    70  	for i, val := range a {
    71  		if i != 0 {
    72  			writer.Write(comma)
    73  		}
    74  		val.MarshalGQL(writer)
    75  	}
    76  	writer.Write(closeBracket)
    77  }
    78  
    79  type lit struct{ b []byte }
    80  
    81  func (l lit) MarshalGQL(w io.Writer) {
    82  	w.Write(l.b)
    83  }