|
1 | 1 | package cm
|
2 | 2 |
|
3 |
| -import "unsafe" |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "encoding/json" |
| 6 | + "unsafe" |
| 7 | +) |
4 | 8 |
|
5 | 9 | // List represents a Component Model list.
|
6 | 10 | // The binary representation of list<T> is similar to a Go slice minus the cap field.
|
@@ -58,3 +62,57 @@ func (l list[T]) Data() *T {
|
58 | 62 | func (l list[T]) Len() uintptr {
|
59 | 63 | return l.len
|
60 | 64 | }
|
| 65 | + |
| 66 | +// MarshalJSON implements json.Marshaler. |
| 67 | +func (l list[T]) MarshalJSON() ([]byte, error) { |
| 68 | + if l.len == 0 { |
| 69 | + return []byte("[]"), nil |
| 70 | + } |
| 71 | + |
| 72 | + s := l.Slice() |
| 73 | + var zero T |
| 74 | + if unsafe.Sizeof(zero) == 1 { |
| 75 | + // The default Go json.Encoder will marshal []byte as base64. |
| 76 | + // We override that behavior so all int types have the same serialization format. |
| 77 | + // []uint8{1,2,3} -> [1,2,3] |
| 78 | + // []uint32{1,2,3} -> [1,2,3] |
| 79 | + return json.Marshal(sliceOf(s)) |
| 80 | + } |
| 81 | + return json.Marshal(s) |
| 82 | +} |
| 83 | + |
| 84 | +type slice[T any] []entry[T] |
| 85 | + |
| 86 | +func sliceOf[S ~[]E, E any](s S) slice[E] { |
| 87 | + return *(*slice[E])(unsafe.Pointer(&s)) |
| 88 | +} |
| 89 | + |
| 90 | +type entry[T any] [1]T |
| 91 | + |
| 92 | +func (v entry[T]) MarshalJSON() ([]byte, error) { |
| 93 | + return json.Marshal(v[0]) |
| 94 | +} |
| 95 | + |
| 96 | +// UnmarshalJSON implements json.Unmarshaler. |
| 97 | +func (l *list[T]) UnmarshalJSON(data []byte) error { |
| 98 | + if bytes.Equal(data, nullLiteral) { |
| 99 | + return nil |
| 100 | + } |
| 101 | + |
| 102 | + var s []T |
| 103 | + err := json.Unmarshal(data, &s) |
| 104 | + if err != nil { |
| 105 | + return err |
| 106 | + } |
| 107 | + |
| 108 | + l.data = unsafe.SliceData([]T(s)) |
| 109 | + l.len = uintptr(len(s)) |
| 110 | + |
| 111 | + return nil |
| 112 | +} |
| 113 | + |
| 114 | +// nullLiteral is the JSON representation of a null literal. |
| 115 | +// By convention, to approximate the behavior of Unmarshal itself, |
| 116 | +// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. |
| 117 | +// See https://pkg.go.dev/encoding/json#Unmarshaler for more information. |
| 118 | +var nullLiteral = []byte("null") |
0 commit comments