github.com/anthropics/anthropic-sdk-go@v1.70.1/internal/apijson/registry.go (about)

     1  package apijson
     2  
     3  import (
     4  	"reflect"
     5  
     6  	"github.com/tidwall/gjson"
     7  )
     8  
     9  type UnionVariant struct {
    10  	TypeFilter         gjson.Type
    11  	DiscriminatorValue any
    12  	Type               reflect.Type
    13  }
    14  
    15  var unionRegistry = map[reflect.Type]unionEntry{}
    16  var unionVariants = map[reflect.Type]any{}
    17  var customDecoderRegistry = map[reflect.Type]CustomDecoderFunc{}
    18  
    19  type unionEntry struct {
    20  	discriminatorKey string
    21  	variants         []UnionVariant
    22  }
    23  
    24  func Discriminator[T any](value any) UnionVariant {
    25  	var zero T
    26  	return UnionVariant{
    27  		TypeFilter:         gjson.JSON,
    28  		DiscriminatorValue: value,
    29  		Type:               reflect.TypeOf(zero),
    30  	}
    31  }
    32  
    33  func RegisterUnion[T any](discriminator string, variants ...UnionVariant) {
    34  	typ := reflect.TypeOf((*T)(nil)).Elem()
    35  	unionRegistry[typ] = unionEntry{
    36  		discriminatorKey: discriminator,
    37  		variants:         variants,
    38  	}
    39  	for _, variant := range variants {
    40  		unionVariants[variant.Type] = typ
    41  	}
    42  }
    43  
    44  // Useful to wrap a union type to force it to use [apijson.UnmarshalJSON] since you cannot define an
    45  // UnmarshalJSON function on the interface itself.
    46  type UnionUnmarshaler[T any] struct {
    47  	Value T
    48  }
    49  
    50  func (c *UnionUnmarshaler[T]) UnmarshalJSON(buf []byte) error {
    51  	return UnmarshalRoot(buf, &c.Value)
    52  }
    53  
    54  type CustomDecoderFunc func(node gjson.Result, value reflect.Value, defaultDecoder func(gjson.Result, reflect.Value) error) error
    55  
    56  func RegisterCustomDecoder[T any](decoder CustomDecoderFunc) {
    57  	typ := reflect.TypeOf((*T)(nil)).Elem()
    58  	customDecoderRegistry[typ] = decoder
    59  }