Skip to content

Commit f56a80f

Browse files
committed
Simplify interface checking with type assertions
Replace reflect.Type.Implements() with type assertion using comma-ok idiom and remove redundant pointer interface check. The recursive decode call handles pointer receiver implementations via CanAddr(). Eliminates unmarshalerType variable and reduces code complexity while maintaining identical functionality and performance.
1 parent 4f8b5f8 commit f56a80f

File tree

1 file changed

+3
-19
lines changed

1 file changed

+3
-19
lines changed

internal/decoder/reflection.go

Lines changed: 3 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,6 @@ type Unmarshaler interface {
1717
UnmarshalMaxMindDB(d *Decoder) error
1818
}
1919

20-
// unmarshalerType is cached for efficient interface checking.
21-
var unmarshalerType = reflect.TypeFor[Unmarshaler]()
22-
2320
// ReflectionDecoder is a decoder for the MMDB data section.
2421
type ReflectionDecoder struct {
2522
DataDecoder
@@ -245,30 +242,17 @@ func (d *ReflectionDecoder) decode(offset uint, result reflect.Value, depth int)
245242
}
246243

247244
// First handle pointers by creating the value if needed, similar to indirect()
248-
// but we don't want to fully indirect yet as we need to check for Unmarshaler
249245
if result.Kind() == reflect.Ptr {
250246
if result.IsNil() {
251247
result.Set(reflect.New(result.Type().Elem()))
252248
}
253-
// Now check if the pointed-to type implements Unmarshaler using cached type check
254-
if result.Type().Implements(unmarshalerType) {
255-
unmarshaler := result.Interface().(Unmarshaler) // Safe, we know it implements
256-
decoder := NewDecoder(d.DataDecoder, offset)
257-
if err := unmarshaler.UnmarshalMaxMindDB(decoder); err != nil {
258-
return 0, err
259-
}
260-
return decoder.getNextOffset()
261-
}
262-
// Continue with the pointed-to value
249+
// Continue with the pointed-to value - interface check will happen in recursive call
263250
return d.decode(offset, result.Elem(), depth)
264251
}
265252

266-
// Check if the value implements Unmarshaler interface
267-
// We need to check if result can be addressed and if the pointer type implements Unmarshaler
253+
// Check if the value implements Unmarshaler interface using type assertion
268254
if result.CanAddr() {
269-
ptrType := result.Addr().Type()
270-
if ptrType.Implements(unmarshalerType) {
271-
unmarshaler := result.Addr().Interface().(Unmarshaler) // Safe, we know it implements
255+
if unmarshaler, ok := result.Addr().Interface().(Unmarshaler); ok {
272256
decoder := NewDecoder(d.DataDecoder, offset)
273257
if err := unmarshaler.UnmarshalMaxMindDB(decoder); err != nil {
274258
return 0, err

0 commit comments

Comments
 (0)