Files
promptkit/internal/jsonvalue/trusted.go

78 lines
2.1 KiB
Go

package jsonvalue
import "reflect"
type cloneReference struct {
typeOf reflect.Type
pointer uintptr
length int
}
// CloneTrusted detaches a previously accepted value without revalidating it.
// Cyclic values can also occur in inactive, uninterpreted request fields.
func CloneTrusted(value any) any {
if value == nil {
return nil
}
return cloneTrustedReflect(reflect.ValueOf(value), make(map[cloneReference]reflect.Value)).Interface()
}
func cloneTrustedReflect(value reflect.Value, active map[cloneReference]reflect.Value) reflect.Value {
if !value.IsValid() {
return value
}
switch value.Kind() {
case reflect.Interface:
if value.IsNil() {
return reflect.Zero(value.Type())
}
out := reflect.New(value.Type()).Elem()
out.Set(cloneTrustedReflect(value.Elem(), active))
return out
case reflect.Pointer, reflect.Map, reflect.Slice:
if value.IsNil() {
return reflect.Zero(value.Type())
}
key := cloneReference{typeOf: value.Type(), pointer: uintptr(value.UnsafePointer())}
if value.Kind() == reflect.Slice {
key.length = value.Len()
}
if existing, found := active[key]; found {
return existing
}
var out reflect.Value
switch value.Kind() {
case reflect.Pointer:
out = reflect.New(value.Type().Elem())
case reflect.Map:
out = reflect.MakeMapWithSize(value.Type(), value.Len())
case reflect.Slice:
out = reflect.MakeSlice(value.Type(), value.Len(), value.Cap())
}
active[key] = out
defer delete(active, key)
switch value.Kind() {
case reflect.Pointer:
out.Elem().Set(cloneTrustedReflect(value.Elem(), active))
case reflect.Map:
iter := value.MapRange()
for iter.Next() {
out.SetMapIndex(cloneTrustedReflect(iter.Key(), active), cloneTrustedReflect(iter.Value(), active))
}
case reflect.Slice:
for i := 0; i < value.Len(); i++ {
out.Index(i).Set(cloneTrustedReflect(value.Index(i), active))
}
}
return out
case reflect.Array:
out := reflect.New(value.Type()).Elem()
for i := 0; i < value.Len(); i++ {
out.Index(i).Set(cloneTrustedReflect(value.Index(i), active))
}
return out
default:
return value
}
}