|
| 1 | +//go:build !module.std |
| 2 | + |
| 3 | +package cm |
| 4 | + |
| 5 | +// This file contains JSON-related functionality for Component Model list types. |
| 6 | +// To avoid a cyclical dependency on package encoding/json when using this package |
| 7 | +// in a Go or TinyGo standard library, do not include files named *_json.go. |
| 8 | + |
| 9 | +import ( |
| 10 | + "bytes" |
| 11 | + "encoding/json" |
| 12 | + "unsafe" |
| 13 | +) |
| 14 | + |
| 15 | +// MarshalJSON implements json.Marshaler. |
| 16 | +func (l list[T]) MarshalJSON() ([]byte, error) { |
| 17 | + if l.len == 0 { |
| 18 | + return []byte("[]"), nil |
| 19 | + } |
| 20 | + |
| 21 | + s := l.Slice() |
| 22 | + var zero T |
| 23 | + if unsafe.Sizeof(zero) == 1 { |
| 24 | + // The default Go json.Encoder will marshal []byte as base64. |
| 25 | + // We override that behavior so all int types have the same serialization format. |
| 26 | + // []uint8{1,2,3} -> [1,2,3] |
| 27 | + // []uint32{1,2,3} -> [1,2,3] |
| 28 | + return json.Marshal(sliceOf(s)) |
| 29 | + } |
| 30 | + return json.Marshal(s) |
| 31 | +} |
| 32 | + |
| 33 | +type slice[T any] []entry[T] |
| 34 | + |
| 35 | +func sliceOf[S ~[]E, E any](s S) slice[E] { |
| 36 | + return *(*slice[E])(unsafe.Pointer(&s)) |
| 37 | +} |
| 38 | + |
| 39 | +type entry[T any] [1]T |
| 40 | + |
| 41 | +func (v entry[T]) MarshalJSON() ([]byte, error) { |
| 42 | + return json.Marshal(v[0]) |
| 43 | +} |
| 44 | + |
| 45 | +// UnmarshalJSON implements json.Unmarshaler. |
| 46 | +func (l *list[T]) UnmarshalJSON(data []byte) error { |
| 47 | + if bytes.Equal(data, nullLiteral) { |
| 48 | + return nil |
| 49 | + } |
| 50 | + |
| 51 | + var s []T |
| 52 | + err := json.Unmarshal(data, &s) |
| 53 | + if err != nil { |
| 54 | + return err |
| 55 | + } |
| 56 | + |
| 57 | + l.data = unsafe.SliceData([]T(s)) |
| 58 | + l.len = uintptr(len(s)) |
| 59 | + |
| 60 | + return nil |
| 61 | +} |
| 62 | + |
| 63 | +// nullLiteral is the JSON representation of a null literal. |
| 64 | +// By convention, to approximate the behavior of Unmarshal itself, |
| 65 | +// Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op. |
| 66 | +// See https://pkg.go.dev/encoding/json#Unmarshaler for more information. |
| 67 | +var nullLiteral = []byte("null") |
0 commit comments