1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // encgen writes the helper functions for encoding. Intended to be
8 // used with go generate; see the invocation in encode.go.
10 // TODO: We could do more by being unsafe. Add a -unsafe flag?
23 var output
= flag
.String("output", "enc_helpers.go", "file name to write")
47 `rpart := floatBits(float64(real(x)))
48 ipart := floatBits(float64(imag(x)))
49 state.encodeUint(rpart)
50 state.encodeUint(ipart)`,
56 `rpart := floatBits(real(x))
57 ipart := floatBits(imag(x))
58 state.encodeUint(rpart)
59 state.encodeUint(ipart)`,
65 `bits := floatBits(float64(x))
66 state.encodeUint(bits)`,
73 state.encodeUint(bits)`,
79 `state.encodeInt(int64(x))`,
85 `state.encodeInt(int64(x))`,
91 `state.encodeInt(int64(x))`,
103 `state.encodeInt(int64(x))`,
109 `state.encodeUint(uint64(len(x)))
110 state.b.WriteString(x)`,
116 `state.encodeUint(uint64(x))`,
122 `state.encodeUint(uint64(x))`,
128 `state.encodeUint(uint64(x))`,
134 `state.encodeUint(x)`,
140 `state.encodeUint(uint64(x))`,
142 // uint8 Handled separately.
147 log
.SetPrefix("encgen: ")
149 if flag
.NArg() != 0 {
150 log
.Fatal("usage: encgen [--output filename]")
153 fmt
.Fprintf(&b
, "// Code generated by go run encgen.go -output %s; DO NOT EDIT.\n", *output
)
154 fmt
.Fprint(&b
, header
)
155 printMaps(&b
, "Array")
157 printMaps(&b
, "Slice")
158 for _
, t
:= range types
{
159 fmt
.Fprintf(&b
, arrayHelper
, t
.lower
, t
.upper
)
160 fmt
.Fprintf(&b
, sliceHelper
, t
.lower
, t
.upper
, t
.zero
, t
.encoder
)
162 source
, err
:= format
.Source(b
.Bytes())
164 log
.Fatal("source format error:", err
)
166 fd
, err
:= os
.Create(*output
)
167 _
, err
= fd
.Write(source
)
173 func printMaps(b
*bytes
.Buffer
, upperClass
string) {
174 fmt
.Fprintf(b
, "var enc%sHelper = map[reflect.Kind]encHelper{\n", upperClass
)
175 for _
, t
:= range types
{
176 fmt
.Fprintf(b
, "reflect.%s: enc%s%s,\n", t
.upper
, t
.upper
, upperClass
)
178 fmt
.Fprintf(b
, "}\n")
182 // Copyright 2014 The Go Authors. All rights reserved.
183 // Use of this source code is governed by a BSD-style
184 // license that can be found in the LICENSE file.
194 const arrayHelper
= `
195 func enc%[2]sArray(state *encoderState, v reflect.Value) bool {
196 // Can only slice if it is addressable.
200 return enc%[2]sSlice(state, v.Slice(0, v.Len()))
204 const sliceHelper
= `
205 func enc%[2]sSlice(state *encoderState, v reflect.Value) bool {
206 slice, ok := v.Interface().([]%[1]s)
208 // It is kind %[1]s but not type %[1]s. TODO: We can handle this unsafely.
211 for _, x := range slice {
212 if x != %[3]s || state.sendZero {