|
| 1 | +// Copyright 2025 The Cockroach Authors. |
| 2 | +// |
| 3 | +// Use of this software is governed by the CockroachDB Software License |
| 4 | +// included in the /LICENSE file. |
| 5 | + |
| 6 | +package codec |
| 7 | + |
| 8 | +import ( |
| 9 | + "fmt" |
| 10 | + "path" |
| 11 | + "reflect" |
| 12 | + "strings" |
| 13 | + |
| 14 | + "gopkg.in/yaml.v3" |
| 15 | +) |
| 16 | + |
| 17 | +type ( |
| 18 | + // TypeMap is a map of type names with their corresponding `reflect.Type`. |
| 19 | + // This is used to resolve type names to `reflect.Type` during decoding. |
| 20 | + TypeMap map[TypeName]reflect.Type |
| 21 | + |
| 22 | + // Metadata is an internal type used to encode and decode dynamic types with |
| 23 | + // their type name. |
| 24 | + metadata struct { |
| 25 | + FieldType fieldType `yaml:"type"` |
| 26 | + Val DynamicType `yaml:"val"` |
| 27 | + } |
| 28 | + |
| 29 | + // DynamicType is an interface used to encode and decode dynamic types. |
| 30 | + // This is used to allow for custom types to be encoded and decoded. |
| 31 | + DynamicType interface { |
| 32 | + GetTypeName() TypeName |
| 33 | + } |
| 34 | + |
| 35 | + // Wrapper wraps a dynamic type for encoding and decoding. |
| 36 | + Wrapper[T DynamicType] struct { |
| 37 | + Val T `yaml:",inline"` |
| 38 | + } |
| 39 | + |
| 40 | + // ListWrapper wraps a list of dynamic types for encoding and decoding. |
| 41 | + ListWrapper[T DynamicType] struct { |
| 42 | + Val []T `yaml:",inline"` |
| 43 | + } |
| 44 | + |
| 45 | + // TypeName stores the package and name of a type. |
| 46 | + TypeName struct { |
| 47 | + pkg string |
| 48 | + name string |
| 49 | + } |
| 50 | + |
| 51 | + // fieldType provides the type information during encoding and decoding. It |
| 52 | + // stores a string representation of the TypeName and whether the type should |
| 53 | + // be decoded as a pointer. |
| 54 | + // Ex. `util.Tree` or `util.*Tree` |
| 55 | + fieldType string |
| 56 | +) |
| 57 | + |
| 58 | +var typeRegistry = make(TypeMap) |
| 59 | + |
| 60 | +// Register registers a dynamic type with the codec package. All dynamic types |
| 61 | +// must be registered before they can be encoded and decoded. |
| 62 | +func Register(t DynamicType) { |
| 63 | + typeRegistry[t.GetTypeName()] = ResolveElem(reflect.TypeOf(t)) |
| 64 | +} |
| 65 | + |
| 66 | +// Wrap is a convenience function for wrapping a dynamic type. |
| 67 | +func Wrap[T DynamicType](t T) Wrapper[T] { |
| 68 | + return Wrapper[T]{Val: t} |
| 69 | +} |
| 70 | + |
| 71 | +// WrapList is a convenience function for wrapping a list of dynamic types. |
| 72 | +func WrapList[T DynamicType](t []T) ListWrapper[T] { |
| 73 | + return ListWrapper[T]{Val: t} |
| 74 | +} |
| 75 | + |
| 76 | +func (w *Wrapper[T]) Get() T { |
| 77 | + return w.Val |
| 78 | +} |
| 79 | + |
| 80 | +func (w *ListWrapper[T]) Get() []T { |
| 81 | + return w.Val |
| 82 | +} |
| 83 | + |
| 84 | +// ResolveElem unwraps a pointer type to get the underlying type or returns the |
| 85 | +// type itself if it is not a pointer. |
| 86 | +func ResolveElem(t reflect.Type) reflect.Type { |
| 87 | + if t.Kind() == reflect.Ptr { |
| 88 | + return t.Elem() |
| 89 | + } |
| 90 | + return t |
| 91 | +} |
| 92 | + |
| 93 | +// ResolveTypeName resolves the type name of a dynamic type. |
| 94 | +func ResolveTypeName(t DynamicType) TypeName { |
| 95 | + tType := ResolveElem(reflect.TypeOf(t)) |
| 96 | + return TypeName{ |
| 97 | + pkg: path.Base(tType.PkgPath()), |
| 98 | + name: tType.Name(), |
| 99 | + } |
| 100 | +} |
| 101 | + |
| 102 | +// toFieldType encodes the type name as a fieldType (string), including the |
| 103 | +// package path, and if the type should later on be decoded as a pointer. |
| 104 | +func (t TypeName) toFieldType(pointer bool) fieldType { |
| 105 | + name := t.name |
| 106 | + if pointer { |
| 107 | + name = "*" + name |
| 108 | + } |
| 109 | + return fieldType(t.pkg + "." + name) |
| 110 | +} |
| 111 | + |
| 112 | +// name returns the package and name of the type. |
| 113 | +func (t fieldType) name() (TypeName, error) { |
| 114 | + s := strings.Split(string(t), ".") |
| 115 | + if len(s) != 2 { |
| 116 | + return TypeName{}, fmt.Errorf("invalid type name %q", t) |
| 117 | + } |
| 118 | + // The `typeName` should not include the pointer prefix, as this is only used |
| 119 | + // during decoding to determine if the value should be decoded as a pointer. |
| 120 | + s[1] = strings.TrimPrefix(s[1], "*") |
| 121 | + return TypeName{ |
| 122 | + pkg: s[0], |
| 123 | + name: s[1], |
| 124 | + }, nil |
| 125 | +} |
| 126 | + |
| 127 | +// isPointer returns true if the type is a pointer. |
| 128 | +func (t fieldType) isPointer() bool { |
| 129 | + return strings.Contains(string(t), "*") |
| 130 | +} |
| 131 | + |
| 132 | +// MarshalYAML implements the [yaml.Marshaler] interface. The wrapper is |
| 133 | +// inspected to get its type information, which is then encoded with the |
| 134 | +// metadata type. |
| 135 | +func (w Wrapper[T]) MarshalYAML() (any, error) { |
| 136 | + typeName := w.Get().GetTypeName() |
| 137 | + dynType := reflect.TypeOf(w.Get()) |
| 138 | + pointer := false |
| 139 | + if dynType.Kind() == reflect.Ptr { |
| 140 | + pointer = true |
| 141 | + } |
| 142 | + return metadata{ |
| 143 | + FieldType: typeName.toFieldType(pointer), |
| 144 | + Val: w.Val, |
| 145 | + }, nil |
| 146 | +} |
| 147 | + |
| 148 | +// UnmarshalYAML implements the [yaml.Unmarshaler] interface. Since the wrapper |
| 149 | +// was stored with metadata, we decode the type information and then decode the |
| 150 | +// value using the type information. |
| 151 | +func (w *Wrapper[T]) UnmarshalYAML(value *yaml.Node) error { |
| 152 | + ft := fieldType(value.Content[1].Value) |
| 153 | + typeName, err := ft.name() |
| 154 | + if err != nil { |
| 155 | + return err |
| 156 | + } |
| 157 | + objType, ok := typeRegistry[typeName] |
| 158 | + if !ok { |
| 159 | + return fmt.Errorf("unknown type %s.%s", typeName.pkg, typeName.name) |
| 160 | + } |
| 161 | + objValuePtr := reflect.New(objType).Interface() |
| 162 | + if err := value.Content[3].Decode(objValuePtr); err != nil { |
| 163 | + return err |
| 164 | + } |
| 165 | + objValue := reflect.ValueOf(objValuePtr).Elem().Interface() |
| 166 | + if ft.isPointer() { |
| 167 | + objValue = reflect.ValueOf(objValuePtr).Interface() |
| 168 | + } |
| 169 | + *w = Wrapper[T]{ |
| 170 | + objValue.(T), |
| 171 | + } |
| 172 | + return nil |
| 173 | +} |
| 174 | + |
| 175 | +// MarshalYAML implements the [yaml.Marshaler] interface. This is a convenience |
| 176 | +// function for encoding a list of dynamic types and leverages the Wrapper type |
| 177 | +// to encode each dynamic type. |
| 178 | +func (w ListWrapper[T]) MarshalYAML() (any, error) { |
| 179 | + wrappers := make([]Wrapper[T], len(w.Val)) |
| 180 | + for i, v := range w.Val { |
| 181 | + wrappers[i] = Wrap(v) |
| 182 | + } |
| 183 | + return wrappers, nil |
| 184 | +} |
| 185 | + |
| 186 | +// UnmarshalYAML implements the [yaml.Unmarshaler] interface. This is a |
| 187 | +// convenience function for decoding a list of dynamic types and leverages the |
| 188 | +// Wrapper type to encode each dynamic type. |
| 189 | +func (w *ListWrapper[T]) UnmarshalYAML(value *yaml.Node) error { |
| 190 | + *w = ListWrapper[T]{ |
| 191 | + Val: make([]T, len(value.Content)), |
| 192 | + } |
| 193 | + for i, v := range value.Content { |
| 194 | + var e Wrapper[T] |
| 195 | + if err := v.Decode(&e); err != nil { |
| 196 | + return err |
| 197 | + } |
| 198 | + w.Val[i] = e.Val |
| 199 | + } |
| 200 | + return nil |
| 201 | +} |
0 commit comments