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
)
170 if _
, err
:= fd
.Write(source
); err
!= nil {
175 func printMaps(b
*bytes
.Buffer
, upperClass
string) {
176 fmt
.Fprintf(b
, "var enc%sHelper = map[reflect.Kind]encHelper{\n", upperClass
)
177 for _
, t
:= range types
{
178 fmt
.Fprintf(b
, "reflect.%s: enc%s%s,\n", t
.upper
, t
.upper
, upperClass
)
180 fmt
.Fprintf(b
, "}\n")
184 // Copyright 2014 The Go Authors. All rights reserved.
185 // Use of this source code is governed by a BSD-style
186 // license that can be found in the LICENSE file.
196 const arrayHelper
= `
197 func enc%[2]sArray(state *encoderState, v reflect.Value) bool {
198 // Can only slice if it is addressable.
202 return enc%[2]sSlice(state, v.Slice(0, v.Len()))
206 const sliceHelper
= `
207 func enc%[2]sSlice(state *encoderState, v reflect.Value) bool {
208 slice, ok := v.Interface().([]%[1]s)
210 // It is kind %[1]s but not type %[1]s. TODO: We can handle this unsafely.
213 for _, x := range slice {
214 if x != %[3]s || state.sendZero {