Closes #21: File-unique auxiliary function names.

This commit is contained in:
Victor Starodub
2016-04-25 02:11:43 +03:00
parent f71fb54472
commit 7b35f91cec
4 changed files with 19 additions and 8 deletions
+1 -1
View File
@@ -95,7 +95,7 @@ func (g *Generator) writeMain() (path string, err error) {
fmt.Fprintln(f, ")")
fmt.Fprintln(f)
fmt.Fprintln(f, "func main() {")
fmt.Fprintln(f, " g := gen.NewGenerator()")
fmt.Fprintf(f, " g := gen.NewGenerator(%q)\n", filepath.Base(g.OutName))
fmt.Fprintf(f, " g.SetPkg(%q, %q)\n", g.PkgName, g.PkgPath)
if g.BuildTags != "" {
fmt.Fprintf(f, " g.SetBuildTags(%q)\n", g.BuildTags)
+1 -1
View File
@@ -14,7 +14,7 @@ import (
const minSliceBytes = 64
func (g *Generator) getStructDecoderName(t reflect.Type) string {
return g.functionName("easyjson_decode_", t)
return g.functionName("decode_", t)
}
var primitiveDecoders = map[reflect.Kind]string{
+1 -1
View File
@@ -11,7 +11,7 @@ import (
)
func (g *Generator) getStructEncoderName(t reflect.Type) string {
return g.functionName("easyjson_encode_", t)
return g.functionName("encode_", t)
}
var primitiveEncoders = map[reflect.Kind]string{
+16 -5
View File
@@ -3,6 +3,7 @@ package gen
import (
"bytes"
"fmt"
"hash/fnv"
"io"
"path"
"reflect"
@@ -23,9 +24,10 @@ type FieldNamer interface {
type Generator struct {
out *bytes.Buffer
pkgName string
pkgPath string
buildTags string
pkgName string
pkgPath string
buildTags string
funcPrefix string
varCounter int
@@ -51,8 +53,8 @@ type Generator struct {
}
// NewGenerator initializes and returns a Generator.
func NewGenerator() *Generator {
return &Generator{
func NewGenerator(filename string) *Generator {
ret := &Generator{
imports: map[string]string{
pkgWriter: "jwriter",
pkgLexer: "jlexer",
@@ -63,6 +65,14 @@ func NewGenerator() *Generator {
typesSeen: make(map[reflect.Type]bool),
functionNames: make(map[string]reflect.Type),
}
// Use a file-unique prefix on all auxiliary functions to avoid
// name clashes.
hash := fnv.New32()
hash.Write([]byte(filename))
ret.funcPrefix = fmt.Sprintf("easyjson_%x_", hash.Sum32())
return ret
}
// SetPkg sets the name and path of output package.
@@ -257,6 +267,7 @@ func safeName(t reflect.Type) string {
//
// Method is used to track encoder/decoder names for the type.
func (g *Generator) functionName(prefix string, t reflect.Type) string {
prefix = g.funcPrefix + prefix
name := prefix + safeName(t)
// Most of the names will be unique, try a shortcut first.