Skip to content

Commit

Permalink
Add specializations (#15)
Browse files Browse the repository at this point in the history
  • Loading branch information
cristaloleg authored Oct 27, 2023
1 parent 8e80b6d commit 7ed3654
Showing 1 changed file with 37 additions and 16 deletions.
53 changes: 37 additions & 16 deletions encode.go
Original file line number Diff line number Diff line change
Expand Up @@ -81,16 +81,26 @@ func (enc *Encoder) writeMap(v reflect.Value) (int, error) {
count := 4 + 1 // sizeof(int) + sizeof(\0)

doc := make(docRefl, v.Len())

keys := v.MapKeys()
for i := range keys {
key := keys[i]
doc[i] = pairRefl{
Key: key.String(),
Val: v.MapIndex(key),
// TODO(cristaloleg): bson.D and bson.M are not supported.
if m, ok := v.Interface().(map[string]any); ok {
i := 0
for k, v := range m {
doc[i] = pairRefl{
Key: k,
Val: reflect.ValueOf(v),
}
i++
}
} else {
keys := v.MapKeys()
for i := range keys {
key := keys[i]
doc[i] = pairRefl{
Key: key.String(),
Val: v.MapIndex(key),
}
}
}

sortPairRefl(doc)

for i := 0; i < len(doc); i++ {
Expand Down Expand Up @@ -139,15 +149,26 @@ func (enc *Encoder) writeSlice(v reflect.Value) (int, error) {
enc.buf = append(enc.buf, 0, 0, 0, 0)
count := 4 + 1 // sizeof(int) + sizeof(\0)

n := v.Len()
for i := 0; i < n; i++ {
val := v.Index(i)

n, err := enc.writeValue(strconv.Itoa(i), val)
if err != nil {
return 0, err
// TODO(cristaloleg): bson.A is not supported.
if a, ok := v.Interface().([]any); ok {
for i := range a {
n, err := enc.writeValue(strconv.Itoa(i), reflect.ValueOf(a[i]))
if err != nil {
return 0, err
}
count += n
}
} else {
n := v.Len()
for i := 0; i < n; i++ {
val := v.Index(i)

n, err := enc.writeValue(strconv.Itoa(i), val)
if err != nil {
return 0, err
}
count += n
}
count += n
}

enc.buf = append(enc.buf, 0)
Expand Down

0 comments on commit 7ed3654

Please sign in to comment.