Skip to content

Commit 801e568

Browse files
committed
feat: allow json.Marshaler+json.Unmarshaler in om.HashRepository
1 parent 0255319 commit 801e568

File tree

1 file changed

+10
-9
lines changed

1 file changed

+10
-9
lines changed

om/conv.go

+10-9
Original file line numberDiff line numberDiff line change
@@ -24,13 +24,6 @@ func newHashConvFactory(t reflect.Type, schema schema) *hashConvFactory {
2424
k := f.typ.Kind()
2525
panic(fmt.Sprintf("schema %q should not contain unsupported field type %s.", t, k))
2626
}
27-
if conv.ValueToString == nil && conv.StringToValue == nil {
28-
ptr := reflect.PointerTo(f.typ)
29-
if !ptr.Implements(reflect.TypeOf((*json.Marshaler)(nil)).Elem()) || !ptr.Implements(reflect.TypeOf((*json.Unmarshaler)(nil)).Elem()) {
30-
k := f.typ.Kind()
31-
panic(fmt.Sprintf("schema %q should not contain unsupported field type %s.", t, k))
32-
}
33-
}
3427
factory.fields[name] = fieldConv{conv: conv, idx: f.idx}
3528
}
3629
return factory
@@ -59,7 +52,7 @@ func (r hashConv) ToHash() (fields map[string]string) {
5952
for k, f := range r.factory.fields {
6053
ref := r.entity.Field(f.idx)
6154
if f.conv.ValueToString == nil {
62-
if bs, err := ref.Interface().(json.Marshaler).MarshalJSON(); err == nil {
55+
if bs, err := json.Marshal(ref.Interface()); err == nil {
6356
fields[k] = rueidis.BinaryString(bs)
6457
}
6558
} else if v, ok := f.conv.ValueToString(ref); ok {
@@ -76,7 +69,7 @@ func (r hashConv) FromHash(fields map[string]string) error {
7669
continue
7770
}
7871
if f.conv.StringToValue == nil {
79-
if err := r.entity.Field(f.idx).Addr().Interface().(json.Unmarshaler).UnmarshalJSON([]byte(v)); err != nil {
72+
if err := json.Unmarshal(unsafe.Slice(unsafe.StringData(v), len(v)), r.entity.Field(f.idx).Addr().Interface()); err != nil {
8073
return err
8174
}
8275
} else {
@@ -142,6 +135,10 @@ var converters = struct {
142135
return reflect.ValueOf(&b), nil
143136
},
144137
},
138+
reflect.Struct: {
139+
ValueToString: nil,
140+
StringToValue: nil,
141+
},
145142
},
146143
val: map[reflect.Kind]converter{
147144
reflect.Int64: {
@@ -209,5 +206,9 @@ var converters = struct {
209206
return reflect.ValueOf(rueidis.ToVector64(value)), nil
210207
},
211208
},
209+
reflect.Struct: {
210+
ValueToString: nil,
211+
StringToValue: nil,
212+
},
212213
},
213214
}

0 commit comments

Comments
 (0)