Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow non-string-keyed maps by converting the keys #331

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 26 additions & 1 deletion gen/elem.go
Original file line number Diff line number Diff line change
Expand Up @@ -264,6 +264,7 @@ type Map struct {
Validx string // value variable name
Value Elem // value element
isAllowNil bool
KeyType string // key type
}

func (m *Map) SetVarname(s string) {
Expand All @@ -284,7 +285,7 @@ func (m *Map) TypeName() string {
if m.common.alias != "" {
return m.common.alias
}
m.common.Alias("map[string]" + m.Value.TypeName())
m.common.Alias(fmt.Sprintf("map[%s]%s", m.KeyType, m.Value.TypeName()))
return m.common.alias
}

Expand All @@ -308,6 +309,30 @@ func (m *Map) AllowNil() bool { return true }
// SetIsAllowNil sets whether the map is allowed to be nil.
func (m *Map) SetIsAllowNil(b bool) { m.isAllowNil = b }

func (m *Map) KeyStringExpr() string {
if m.KeyType == "string" {
return m.Keyidx
} else {
return fmt.Sprintf("%s.MsgpStrMapKey()", m.Keyidx)
}
}

func (m *Map) KeyOrigTypeExpr() string {
if m.KeyType == "string" {
return m.Keyidx
} else {
return fmt.Sprintf("*(new(%s).MsgpFromStrMapKey(%s)).(*%s)", m.KeyType, m.Keyidx, m.KeyType)
}
}

func (m *Map) KeySizeExpr() string {
if m.KeyType == "string" {
return fmt.Sprintf("len(%s)", m.Keyidx)
} else {
return fmt.Sprintf("%s.MsgpStrMapKeySize()", m.Keyidx)
}
}

type Slice struct {
common
Index string
Expand Down
2 changes: 1 addition & 1 deletion gen/encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ func (e *encodeGen) gMap(m *Map) {
e.writeAndCheck(mapHeader, lenAsUint32, vname)

e.p.printf("\nfor %s, %s := range %s {", m.Keyidx, m.Validx, vname)
e.writeAndCheck(stringTyp, literalFmt, m.Keyidx)
e.writeAndCheck(stringTyp, literalFmt, m.KeyStringExpr())
e.ctx.PushVar(m.Keyidx)
next(e, m.Value)
e.ctx.Pop()
Expand Down
2 changes: 1 addition & 1 deletion gen/marshal.go
Original file line number Diff line number Diff line change
Expand Up @@ -233,7 +233,7 @@ func (m *marshalGen) gMap(s *Map) {
vname := s.Varname()
m.rawAppend(mapHeader, lenAsUint32, vname)
m.p.printf("\nfor %s, %s := range %s {", s.Keyidx, s.Validx, vname)
m.rawAppend(stringTyp, literalFmt, s.Keyidx)
m.rawAppend(stringTyp, literalFmt, s.KeyStringExpr())
m.ctx.PushVar(s.Keyidx)
next(m, s.Value)
m.ctx.Pop()
Expand Down
2 changes: 1 addition & 1 deletion gen/size.go
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,7 @@ func (s *sizeGen) gMap(m *Map) {
s.p.printf("\nif %s != nil {", vn)
s.p.printf("\nfor %s, %s := range %s {", m.Keyidx, m.Validx, vn)
s.p.printf("\n_ = %s", m.Validx) // we may not use the value
s.p.printf("\ns += msgp.StringPrefixSize + len(%s)", m.Keyidx)
s.p.printf("\ns += msgp.StringPrefixSize + %s", m.KeySizeExpr())
s.state = expr
s.ctx.PushVar(m.Keyidx)
next(s, m.Value)
Expand Down
2 changes: 1 addition & 1 deletion gen/spec.go
Original file line number Diff line number Diff line change
Expand Up @@ -341,7 +341,7 @@ func (p *printer) mapAssign(m *Map) {
if !p.ok() {
return
}
p.printf("\n%s[%s] = %s", m.Varname(), m.Keyidx, m.Validx)
p.printf("\n%s[%s] = %s", m.Varname(), m.KeyOrigTypeExpr(), m.Validx)
}

// clear map keys
Expand Down
10 changes: 10 additions & 0 deletions msgp/non_str_map_key.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package msgp

// NonStrMapKey must be implemented to allow non-string Go types to be used as MessagePack map keys.
// Msgp maps must have string keys for JSON interop.
// NonStrMapKey enables conversion from type to string and vice versa.
type NonStrMapKey interface {
MsgpStrMapKey() string
MsgpFromStrMapKey(s string) NonStrMapKey
MsgpStrMapKeySize() int
}
9 changes: 7 additions & 2 deletions parse/getast.go
Original file line number Diff line number Diff line change
Expand Up @@ -479,9 +479,14 @@ func (fs *FileSet) parseExpr(e ast.Expr) gen.Elem {
switch e := e.(type) {

case *ast.MapType:
if k, ok := e.Key.(*ast.Ident); ok && k.Name == "string" {
switch k := e.Key.(type) {
case *ast.Ident:
if in := fs.parseExpr(e.Value); in != nil {
return &gen.Map{Value: in}
return &gen.Map{Value: in, KeyType: k.Name}
}
case *ast.SelectorExpr:
if in := fs.parseExpr(e.Value); in != nil {
return &gen.Map{Value: in, KeyType: stringify(k)}
}
}
return nil
Expand Down
29 changes: 29 additions & 0 deletions printer/print.go
Original file line number Diff line number Diff line change
Expand Up @@ -94,6 +94,9 @@ func generate(f *parse.FileSet, mode gen.Method) (*bytes.Buffer, *bytes.Buffer,
dedup := dedupImports(myImports)
writeImportHeader(outbuf, dedup...)

nonStrMapKeyImpls := nonStrMapKeyImpls(f)
writeInterfaceTypeConstraints(outbuf, "msgp.NonStrMapKey", nonStrMapKeyImpls)

var testbuf *bytes.Buffer
var testwr io.Writer
if mode&gen.Test == gen.Test {
Expand Down Expand Up @@ -131,3 +134,29 @@ func writeImportHeader(b *bytes.Buffer, imports ...string) {
}
b.WriteString(")\n\n")
}

func nonStrMapKeyImpls(f *parse.FileSet) []string {
m := map[string]struct{}{}
for _, identity := range f.Identities {
if _struct, ok := identity.(*gen.Struct); ok {
for _, field := range _struct.Fields {
if _map, ok := field.FieldElem.(*gen.Map); ok {
if _map.KeyType != "string" {
m[_map.KeyType] = struct{}{}
}
}
}
}
}
r := []string{}
for k := range m {
r = append(r, k)
}
return r
}

func writeInterfaceTypeConstraints(b *bytes.Buffer, _interface string, impls []string) {
for _, impl := range impls {
fmt.Fprintf(b, "var _ %s = new(%s)\n", _interface, impl)
}
}
Loading