feat: add ParseAs and NewSchema generics
Test / test (push) Successful in 1m38s

Assisted-by: GLM 5.3 Flash
This commit is contained in:
2026-09-22 00:36:10 +02:00
parent b02471c09a
commit 71bd82a7a5
4 changed files with 73 additions and 0 deletions
+30
View File
@@ -270,6 +270,36 @@ func Unmarshal(data []byte, v any) error {
return UnmarshalContext(context.Background(), data, v)
}
// ParseAs decodes a TOML document into T in one call, the generic shorthand
// for Unmarshal with a destination variable:
//
// cfg, err := interpres.ParseAs[Config](data)
//
// The zero T comes back with the error.
func ParseAs[T any](data []byte) (T, error) {
var v T
err := Unmarshal(data, &v)
return v, err
}
// NewSchema precompiles the codec for T: the struct schema both directions
// walk and the interface flags the decoder and the encoder resolve through
// are built once and cached, so the first document pays the cost instead of
// the hot path. A T that is not a struct warms nothing; there is nothing to
// precompute for a map or a slice.
func NewSchema[T any]() {
t := reflect.TypeFor[T]()
if t.Kind() != reflect.Struct {
return
}
cachedStructSchema(t)
_ = typeFlags(t)
_ = encTypeFlags(t)
pt := reflect.PointerTo(t)
_ = typeFlags(pt)
_ = encTypeFlags(pt)
}
// UnmarshalContext is the cancellable variant of Unmarshal.
func UnmarshalContext(ctx context.Context, data []byte, v any) error {
// Only a destination that can reach an OrderedMap needs the node tree the