| 1 |
package decoder |
| 2 |
|
| 3 |
import ( |
| 4 |
"reflect" |
| 5 |
"testing" |
| 6 |
|
| 7 |
"github.com/goccy/go-json/internal/runtime" |
| 8 |
) |
| 9 |
|
| 10 |
// The recent decoders of a context return the decoder of the type asked, whatever types share its set |
| 11 |
// and in whatever order they are asked: more types than the table holds are asked for by turns. |
| 12 |
func TestRecentDecodersEvict(t *testing.T) { |
| 13 |
types := []reflect.Type{ |
| 14 |
reflect.TypeOf((*int)(nil)), reflect.TypeOf((*string)(nil)), reflect.TypeOf((*bool)(nil)), |
| 15 |
reflect.TypeOf((*float64)(nil)), reflect.TypeOf((*[]int)(nil)), reflect.TypeOf((*[]string)(nil)), |
| 16 |
reflect.TypeOf((*map[string]int)(nil)), reflect.TypeOf((*map[string]string)(nil)), reflect.TypeOf((*any)(nil)), |
| 17 |
reflect.TypeOf((*struct{ A int })(nil)), reflect.TypeOf((*struct{ B string })(nil)), reflect.TypeOf((*[2]int)(nil)), |
| 18 |
reflect.TypeOf((*int8)(nil)), reflect.TypeOf((*int16)(nil)), reflect.TypeOf((*int32)(nil)), |
| 19 |
reflect.TypeOf((*uint)(nil)), reflect.TypeOf((*uint8)(nil)), reflect.TypeOf((*uint16)(nil)), |
| 20 |
reflect.TypeOf((*uint32)(nil)), reflect.TypeOf((*uint64)(nil)), reflect.TypeOf((*float32)(nil)), |
| 21 |
reflect.TypeOf((*[]bool)(nil)), reflect.TypeOf((*[]float64)(nil)), reflect.TypeOf((*map[string]bool)(nil)), |
| 22 |
reflect.TypeOf((*[]any)(nil)), reflect.TypeOf((*map[string]any)(nil)), reflect.TypeOf((*struct{ C []int })(nil)), |
| 23 |
reflect.TypeOf((*struct{ D map[string]int })(nil)), reflect.TypeOf((**int)(nil)), reflect.TypeOf((**string)(nil)), |
| 24 |
reflect.TypeOf((*[3]string)(nil)), reflect.TypeOf((*[]*int)(nil)), reflect.TypeOf((*struct{ E *int })(nil)), |
| 25 |
reflect.TypeOf((*int64)(nil)), |
| 26 |
} |
| 27 |
ctx := TakeRuntimeContext() |
| 28 |
defer ReleaseRuntimeContext(ctx) |
| 29 |
for round := 0; round < 4; round++ { |
| 30 |
for i := range types { |
| 31 |
// by turns, forward and backward, so that every pair of a set evicts each other |
| 32 |
typ := types[i] |
| 33 |
if round%2 == 1 { |
| 34 |
typ = types[len(types)-1-i] |
| 35 |
} |
| 36 |
got, err := ctx.DecoderOf(runtime.TypePtr(typ)) |
| 37 |
if err != nil { |
| 38 |
t.Fatal(err) |
| 39 |
} |
| 40 |
want, err := CompileToGetDecoder(runtime.TypePtr(typ)) |
| 41 |
if err != nil { |
| 42 |
t.Fatal(err) |
| 43 |
} |
| 44 |
if got != want { |
| 45 |
t.Fatalf("round %d: the decoder of %v is %T, want %T", round, typ, got, want) |
| 46 |
} |
| 47 |
} |
| 48 |
} |
| 49 |
// A type which is not a pointer is an error, and is not remembered. |
| 50 |
if _, err := ctx.DecoderOf(runtime.TypePtr(reflect.TypeOf(0))); err == nil { |
| 51 |
t.Fatal("expected an error for a type which is not a pointer") |
| 52 |
} |
| 53 |
} |