|
| 1 | +package codec |
| 2 | + |
| 3 | +import "fmt" |
| 4 | + |
| 5 | +// NameableKeyCodec is a KeyCodec that can be named. |
| 6 | +type NameableKeyCodec[T any] interface { |
| 7 | + KeyCodec[T] |
| 8 | + |
| 9 | + // WithName returns the KeyCodec with the provided name. |
| 10 | + WithName(name string) KeyCodec[T] |
| 11 | +} |
| 12 | + |
| 13 | +// NameableValueCodec is a ValueCodec that can be named. |
| 14 | +type NameableValueCodec[T any] interface { |
| 15 | + ValueCodec[T] |
| 16 | + |
| 17 | + // WithName returns the ValueCodec with the provided name. |
| 18 | + WithName(name string) ValueCodec[T] |
| 19 | +} |
| 20 | + |
| 21 | +// NamedKeyCodec wraps a KeyCodec with a name. |
| 22 | +// The underlying key codec MUST have exactly one field in its schema. |
| 23 | +type NamedKeyCodec[T any] struct { |
| 24 | + KeyCodec[T] |
| 25 | + |
| 26 | + // Name is the name of the KeyCodec in the schema. |
| 27 | + Name string |
| 28 | +} |
| 29 | + |
| 30 | +// SchemaCodec returns the schema codec for the named key codec. |
| 31 | +func (n NamedKeyCodec[T]) SchemaCodec() (SchemaCodec[T], error) { |
| 32 | + cdc, err := KeySchemaCodec[T](n.KeyCodec) |
| 33 | + if err != nil { |
| 34 | + return SchemaCodec[T]{}, err |
| 35 | + } |
| 36 | + return withName(cdc, n.Name) |
| 37 | +} |
| 38 | + |
| 39 | +// NamedValueCodec wraps a ValueCodec with a name. |
| 40 | +// The underlying value codec MUST have exactly one field in its schema. |
| 41 | +type NamedValueCodec[T any] struct { |
| 42 | + ValueCodec[T] |
| 43 | + |
| 44 | + // Name is the name of the ValueCodec in the schema. |
| 45 | + Name string |
| 46 | +} |
| 47 | + |
| 48 | +// SchemaCodec returns the schema codec for the named value codec. |
| 49 | +func (n NamedValueCodec[T]) SchemaCodec() (SchemaCodec[T], error) { |
| 50 | + cdc, err := ValueSchemaCodec[T](n.ValueCodec) |
| 51 | + if err != nil { |
| 52 | + return SchemaCodec[T]{}, err |
| 53 | + } |
| 54 | + return withName(cdc, n.Name) |
| 55 | +} |
| 56 | + |
| 57 | +func withName[T any](cdc SchemaCodec[T], name string) (SchemaCodec[T], error) { |
| 58 | + if len(cdc.Fields) != 1 { |
| 59 | + return SchemaCodec[T]{}, fmt.Errorf("expected exactly one field to be named, got %d", len(cdc.Fields)) |
| 60 | + } |
| 61 | + cdc.Fields[0].Name = name |
| 62 | + return cdc, nil |
| 63 | +} |
0 commit comments