marshal.odin 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618
  1. package encoding_cbor
  2. import "base:intrinsics"
  3. import "base:runtime"
  4. import "core:bytes"
  5. import "core:io"
  6. import "core:mem"
  7. import "core:reflect"
  8. import "core:slice"
  9. import "core:strconv"
  10. import "core:strings"
  11. import "core:unicode/utf8"
  12. /*
  13. Marshal a value into binary CBOR.
  14. Flags can be used to control the output (mainly determinism, which coincidently affects size).
  15. The default flags `ENCODE_SMALL` (`.Deterministic_Int_Size`, `.Deterministic_Float_Size`) will try
  16. to put ints and floats into their smallest possible byte size without losing equality.
  17. Adding the `.Self_Described_CBOR` flag will wrap the value in a tag that lets generic decoders know
  18. the contents are CBOR from just reading the first byte.
  19. Adding the `.Deterministic_Map_Sorting` flag will sort the encoded maps by the byte content of the
  20. encoded key. This flag has a cost on performance and memory efficiency because all keys in a map
  21. have to be precomputed, sorted and only then written to the output.
  22. Empty flags will do nothing extra to the value.
  23. The allocations for the `.Deterministic_Map_Sorting` flag are done using the given `temp_allocator`.
  24. but are followed by the necessary `delete` and `free` calls if the allocator supports them.
  25. This is helpful when the CBOR size is so big that you don't want to collect all the temporary
  26. allocations until the end.
  27. */
  28. marshal_into :: proc {
  29. marshal_into_bytes,
  30. marshal_into_builder,
  31. marshal_into_writer,
  32. marshal_into_encoder,
  33. }
  34. marshal :: marshal_into
  35. // Marshals the given value into a CBOR byte stream (allocated using the given allocator).
  36. // See docs on the `marshal_into` proc group for more info.
  37. marshal_into_bytes :: proc(v: any, flags := ENCODE_SMALL, allocator := context.allocator, temp_allocator := context.temp_allocator, loc := #caller_location) -> (bytes: []byte, err: Marshal_Error) {
  38. b, alloc_err := strings.builder_make(allocator, loc=loc)
  39. // The builder as a stream also returns .EOF if it ran out of memory so this is consistent.
  40. if alloc_err != nil {
  41. return nil, .EOF
  42. }
  43. defer if err != nil { strings.builder_destroy(&b) }
  44. if err = marshal_into_builder(&b, v, flags, temp_allocator); err != nil {
  45. return
  46. }
  47. return b.buf[:], nil
  48. }
  49. // Marshals the given value into a CBOR byte stream written to the given builder.
  50. // See docs on the `marshal_into` proc group for more info.
  51. marshal_into_builder :: proc(b: ^strings.Builder, v: any, flags := ENCODE_SMALL, temp_allocator := context.temp_allocator) -> Marshal_Error {
  52. return marshal_into_writer(strings.to_writer(b), v, flags, temp_allocator)
  53. }
  54. // Marshals the given value into a CBOR byte stream written to the given writer.
  55. // See docs on the `marshal_into` proc group for more info.
  56. marshal_into_writer :: proc(w: io.Writer, v: any, flags := ENCODE_SMALL, temp_allocator := context.temp_allocator) -> Marshal_Error {
  57. encoder := Encoder{flags, w, temp_allocator}
  58. return marshal_into_encoder(encoder, v)
  59. }
  60. // Marshals the given value into a CBOR byte stream written to the given encoder.
  61. // See docs on the `marshal_into` proc group for more info.
  62. marshal_into_encoder :: proc(e: Encoder, v: any) -> (err: Marshal_Error) {
  63. e := e
  64. if e.temp_allocator.procedure == nil {
  65. e.temp_allocator = context.temp_allocator
  66. }
  67. if .Self_Described_CBOR in e.flags {
  68. err_conv(_encode_u64(e, TAG_SELF_DESCRIBED_CBOR, .Tag)) or_return
  69. e.flags -= { .Self_Described_CBOR }
  70. }
  71. if v == nil {
  72. return _encode_nil(e.writer)
  73. }
  74. // Check if type has a tag implementation to use.
  75. if impl, ok := _tag_implementations_type[v.id]; ok {
  76. return impl->marshal(e, v)
  77. }
  78. ti := runtime.type_info_core(type_info_of(v.id))
  79. return _marshal_into_encoder(e, v, ti)
  80. }
  81. _marshal_into_encoder :: proc(e: Encoder, v: any, ti: ^runtime.Type_Info) -> (err: Marshal_Error) {
  82. a := any{v.data, ti.id}
  83. #partial switch info in ti.variant {
  84. case runtime.Type_Info_Named, runtime.Type_Info_Enum, runtime.Type_Info_Bit_Field:
  85. unreachable()
  86. case runtime.Type_Info_Pointer:
  87. switch vv in v {
  88. case Undefined: return _encode_undefined(e.writer)
  89. case Nil: return _encode_nil(e.writer)
  90. }
  91. case runtime.Type_Info_Integer:
  92. switch vv in v {
  93. case Simple: return err_conv(_encode_simple(e.writer, vv))
  94. case Negative_U8: return _encode_u8(e.writer, u8(vv), .Negative)
  95. case Negative_U16: return err_conv(_encode_u16(e, u16(vv), .Negative))
  96. case Negative_U32: return err_conv(_encode_u32(e, u32(vv), .Negative))
  97. case Negative_U64: return err_conv(_encode_u64(e, u64(vv), .Negative))
  98. }
  99. switch i in a {
  100. case i8: return _encode_uint(e.writer, _int_to_uint(i))
  101. case i16: return err_conv(_encode_uint(e, _int_to_uint(i)))
  102. case i32: return err_conv(_encode_uint(e, _int_to_uint(i)))
  103. case i64: return err_conv(_encode_uint(e, _int_to_uint(i)))
  104. case i128: return err_conv(_encode_uint(e, _int_to_uint(i128(i)) or_return))
  105. case int: return err_conv(_encode_uint(e, _int_to_uint(i64(i))))
  106. case u8: return _encode_uint(e.writer, i)
  107. case u16: return err_conv(_encode_uint(e, i))
  108. case u32: return err_conv(_encode_uint(e, i))
  109. case u64: return err_conv(_encode_uint(e, i))
  110. case u128: return err_conv(_encode_uint(e, _u128_to_u64(u128(i)) or_return))
  111. case uint: return err_conv(_encode_uint(e, u64(i)))
  112. case uintptr: return err_conv(_encode_uint(e, u64(i)))
  113. case i16le: return err_conv(_encode_uint(e, _int_to_uint(i16(i))))
  114. case i32le: return err_conv(_encode_uint(e, _int_to_uint(i32(i))))
  115. case i64le: return err_conv(_encode_uint(e, _int_to_uint(i64(i))))
  116. case i128le: return err_conv(_encode_uint(e, _int_to_uint(i128(i)) or_return))
  117. case u16le: return err_conv(_encode_uint(e, u16(i)))
  118. case u32le: return err_conv(_encode_uint(e, u32(i)))
  119. case u64le: return err_conv(_encode_uint(e, u64(i)))
  120. case u128le: return err_conv(_encode_uint(e, _u128_to_u64(u128(i)) or_return))
  121. case i16be: return err_conv(_encode_uint(e, _int_to_uint(i16(i))))
  122. case i32be: return err_conv(_encode_uint(e, _int_to_uint(i32(i))))
  123. case i64be: return err_conv(_encode_uint(e, _int_to_uint(i64(i))))
  124. case i128be: return err_conv(_encode_uint(e, _int_to_uint(i128(i)) or_return))
  125. case u16be: return err_conv(_encode_uint(e, u16(i)))
  126. case u32be: return err_conv(_encode_uint(e, u32(i)))
  127. case u64be: return err_conv(_encode_uint(e, u64(i)))
  128. case u128be: return err_conv(_encode_uint(e, _u128_to_u64(u128(i)) or_return))
  129. }
  130. case runtime.Type_Info_Rune:
  131. buf, w := utf8.encode_rune(a.(rune))
  132. return err_conv(_encode_text(e, string(buf[:w])))
  133. case runtime.Type_Info_Float:
  134. switch f in a {
  135. case f16: return _encode_f16(e.writer, f)
  136. case f32: return _encode_f32(e, f)
  137. case f64: return _encode_f64(e, f)
  138. case f16le: return _encode_f16(e.writer, f16(f))
  139. case f32le: return _encode_f32(e, f32(f))
  140. case f64le: return _encode_f64(e, f64(f))
  141. case f16be: return _encode_f16(e.writer, f16(f))
  142. case f32be: return _encode_f32(e, f32(f))
  143. case f64be: return _encode_f64(e, f64(f))
  144. }
  145. case runtime.Type_Info_Complex:
  146. switch z in a {
  147. case complex32:
  148. arr: [2]Value = {real(z), imag(z)}
  149. return err_conv(_encode_array(e, arr[:]))
  150. case complex64:
  151. arr: [2]Value = {real(z), imag(z)}
  152. return err_conv(_encode_array(e, arr[:]))
  153. case complex128:
  154. arr: [2]Value = {real(z), imag(z)}
  155. return err_conv(_encode_array(e, arr[:]))
  156. }
  157. case runtime.Type_Info_Quaternion:
  158. switch q in a {
  159. case quaternion64:
  160. arr: [4]Value = {imag(q), jmag(q), kmag(q), real(q)}
  161. return err_conv(_encode_array(e, arr[:]))
  162. case quaternion128:
  163. arr: [4]Value = {imag(q), jmag(q), kmag(q), real(q)}
  164. return err_conv(_encode_array(e, arr[:]))
  165. case quaternion256:
  166. arr: [4]Value = {imag(q), jmag(q), kmag(q), real(q)}
  167. return err_conv(_encode_array(e, arr[:]))
  168. }
  169. case runtime.Type_Info_String:
  170. switch s in a {
  171. case string: return err_conv(_encode_text(e, s))
  172. case cstring: return err_conv(_encode_text(e, string(s)))
  173. }
  174. case runtime.Type_Info_Boolean:
  175. switch b in a {
  176. case bool: return _encode_bool(e.writer, b)
  177. case b8: return _encode_bool(e.writer, bool(b))
  178. case b16: return _encode_bool(e.writer, bool(b))
  179. case b32: return _encode_bool(e.writer, bool(b))
  180. case b64: return _encode_bool(e.writer, bool(b))
  181. }
  182. case runtime.Type_Info_Array:
  183. if info.elem.id == byte {
  184. raw := ([^]byte)(v.data)
  185. return err_conv(_encode_bytes(e, raw[:info.count]))
  186. }
  187. err_conv(_encode_u64(e, u64(info.count), .Array)) or_return
  188. if impl, ok := _tag_implementations_type[info.elem.id]; ok {
  189. for i in 0..<info.count {
  190. data := uintptr(v.data) + uintptr(i*info.elem_size)
  191. impl->marshal(e, any{rawptr(data), info.elem.id}) or_return
  192. }
  193. return
  194. }
  195. elem_ti := runtime.type_info_core(type_info_of(info.elem.id))
  196. for i in 0..<info.count {
  197. data := uintptr(v.data) + uintptr(i*info.elem_size)
  198. _marshal_into_encoder(e, any{rawptr(data), info.elem.id}, elem_ti) or_return
  199. }
  200. return
  201. case runtime.Type_Info_Enumerated_Array:
  202. // index := runtime.type_info_base(info.index).variant.(runtime.Type_Info_Enum)
  203. err_conv(_encode_u64(e, u64(info.count), .Array)) or_return
  204. if impl, ok := _tag_implementations_type[info.elem.id]; ok {
  205. for i in 0..<info.count {
  206. data := uintptr(v.data) + uintptr(i*info.elem_size)
  207. impl->marshal(e, any{rawptr(data), info.elem.id}) or_return
  208. }
  209. return
  210. }
  211. elem_ti := runtime.type_info_core(type_info_of(info.elem.id))
  212. for i in 0..<info.count {
  213. data := uintptr(v.data) + uintptr(i*info.elem_size)
  214. _marshal_into_encoder(e, any{rawptr(data), info.elem.id}, elem_ti) or_return
  215. }
  216. return
  217. case runtime.Type_Info_Dynamic_Array:
  218. if info.elem.id == byte {
  219. raw := (^[dynamic]byte)(v.data)
  220. return err_conv(_encode_bytes(e, raw[:]))
  221. }
  222. array := (^mem.Raw_Dynamic_Array)(v.data)
  223. err_conv(_encode_u64(e, u64(array.len), .Array)) or_return
  224. if impl, ok := _tag_implementations_type[info.elem.id]; ok {
  225. for i in 0..<array.len {
  226. data := uintptr(array.data) + uintptr(i*info.elem_size)
  227. impl->marshal(e, any{rawptr(data), info.elem.id}) or_return
  228. }
  229. return
  230. }
  231. elem_ti := runtime.type_info_core(type_info_of(info.elem.id))
  232. for i in 0..<array.len {
  233. data := uintptr(array.data) + uintptr(i*info.elem_size)
  234. _marshal_into_encoder(e, any{rawptr(data), info.elem.id}, elem_ti) or_return
  235. }
  236. return
  237. case runtime.Type_Info_Slice:
  238. if info.elem.id == byte {
  239. raw := (^[]byte)(v.data)
  240. return err_conv(_encode_bytes(e, raw^))
  241. }
  242. array := (^mem.Raw_Slice)(v.data)
  243. err_conv(_encode_u64(e, u64(array.len), .Array)) or_return
  244. if impl, ok := _tag_implementations_type[info.elem.id]; ok {
  245. for i in 0..<array.len {
  246. data := uintptr(array.data) + uintptr(i*info.elem_size)
  247. impl->marshal(e, any{rawptr(data), info.elem.id}) or_return
  248. }
  249. return
  250. }
  251. elem_ti := runtime.type_info_core(type_info_of(info.elem.id))
  252. for i in 0..<array.len {
  253. data := uintptr(array.data) + uintptr(i*info.elem_size)
  254. _marshal_into_encoder(e, any{rawptr(data), info.elem.id}, elem_ti) or_return
  255. }
  256. return
  257. case runtime.Type_Info_Map:
  258. m := (^mem.Raw_Map)(v.data)
  259. err_conv(_encode_u64(e, u64(runtime.map_len(m^)), .Map)) or_return
  260. if m != nil {
  261. if info.map_info == nil {
  262. return _unsupported(v.id, nil)
  263. }
  264. map_cap := uintptr(runtime.map_cap(m^))
  265. ks, vs, hs, _, _ := runtime.map_kvh_data_dynamic(m^, info.map_info)
  266. if .Deterministic_Map_Sorting not_in e.flags {
  267. for bucket_index in 0..<map_cap {
  268. runtime.map_hash_is_valid(hs[bucket_index]) or_continue
  269. key := rawptr(runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index))
  270. value := rawptr(runtime.map_cell_index_dynamic(vs, info.map_info.vs, bucket_index))
  271. marshal_into(e, any{ key, info.key.id }) or_return
  272. marshal_into(e, any{ value, info.value.id }) or_return
  273. }
  274. return
  275. }
  276. // Deterministic_Map_Sorting needs us to sort the entries by the byte contents of the
  277. // encoded key.
  278. //
  279. // This means we have to store and sort them before writing incurring extra (temporary) allocations.
  280. //
  281. // If the map key is a `string` or `cstring` we only allocate space for a dynamic array of entries
  282. // we sort.
  283. //
  284. // If the map key is of another type we also allocate space for encoding the key into.
  285. // To sort a string/cstring we need to first sort by their encoded header/length.
  286. // This fits in 9 bytes at most.
  287. pre_key :: #force_inline proc(e: Encoder, str: string) -> (res: [10]byte) {
  288. e := e
  289. builder := strings.builder_from_slice(res[:])
  290. e.writer = strings.to_stream(&builder)
  291. err := _encode_u64(e, u64(len(str)), .Text)
  292. assert(err == nil)
  293. res[9] = u8(len(builder.buf))
  294. assert(res[9] < 10)
  295. return
  296. }
  297. Encoded_Entry_Fast :: struct($T: typeid) {
  298. pre_key: [10]byte,
  299. key: T,
  300. val_idx: uintptr,
  301. }
  302. Encoded_Entry :: struct {
  303. key: ^[dynamic]byte,
  304. val_idx: uintptr,
  305. }
  306. switch info.key.id {
  307. case string:
  308. entries := make([dynamic]Encoded_Entry_Fast(^[]byte), 0, map_cap, e.temp_allocator) or_return
  309. defer delete(entries)
  310. for bucket_index in 0..<map_cap {
  311. runtime.map_hash_is_valid(hs[bucket_index]) or_continue
  312. key := (^[]byte)(runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index))
  313. append(&entries, Encoded_Entry_Fast(^[]byte){
  314. pre_key = pre_key(e, string(key^)),
  315. key = key,
  316. val_idx = bucket_index,
  317. })
  318. }
  319. slice.sort_by_cmp(entries[:], proc(a, b: Encoded_Entry_Fast(^[]byte)) -> slice.Ordering {
  320. a, b := a, b
  321. pre_cmp := slice.Ordering(bytes.compare(a.pre_key[:a.pre_key[9]], b.pre_key[:b.pre_key[9]]))
  322. if pre_cmp != .Equal {
  323. return pre_cmp
  324. }
  325. return slice.Ordering(bytes.compare(a.key^, b.key^))
  326. })
  327. for &entry in entries {
  328. io.write_full(e.writer, entry.pre_key[:entry.pre_key[9]]) or_return
  329. io.write_full(e.writer, entry.key^) or_return
  330. value := rawptr(runtime.map_cell_index_dynamic(vs, info.map_info.vs, entry.val_idx))
  331. marshal_into(e, any{ value, info.value.id }) or_return
  332. }
  333. return
  334. case cstring:
  335. entries := make([dynamic]Encoded_Entry_Fast(^cstring), 0, map_cap, e.temp_allocator) or_return
  336. defer delete(entries)
  337. for bucket_index in 0..<map_cap {
  338. runtime.map_hash_is_valid(hs[bucket_index]) or_continue
  339. key := (^cstring)(runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index))
  340. append(&entries, Encoded_Entry_Fast(^cstring){
  341. pre_key = pre_key(e, string(key^)),
  342. key = key,
  343. val_idx = bucket_index,
  344. })
  345. }
  346. slice.sort_by_cmp(entries[:], proc(a, b: Encoded_Entry_Fast(^cstring)) -> slice.Ordering {
  347. a, b := a, b
  348. pre_cmp := slice.Ordering(bytes.compare(a.pre_key[:a.pre_key[9]], b.pre_key[:b.pre_key[9]]))
  349. if pre_cmp != .Equal {
  350. return pre_cmp
  351. }
  352. ab := transmute([]byte)string(a.key^)
  353. bb := transmute([]byte)string(b.key^)
  354. return slice.Ordering(bytes.compare(ab, bb))
  355. })
  356. for &entry in entries {
  357. io.write_full(e.writer, entry.pre_key[:entry.pre_key[9]]) or_return
  358. io.write_full(e.writer, transmute([]byte)string(entry.key^)) or_return
  359. value := rawptr(runtime.map_cell_index_dynamic(vs, info.map_info.vs, entry.val_idx))
  360. marshal_into(e, any{ value, info.value.id }) or_return
  361. }
  362. return
  363. case:
  364. entries := make([dynamic]Encoded_Entry, 0, map_cap, e.temp_allocator) or_return
  365. defer delete(entries)
  366. for bucket_index in 0..<map_cap {
  367. runtime.map_hash_is_valid(hs[bucket_index]) or_continue
  368. key := rawptr(runtime.map_cell_index_dynamic(ks, info.map_info.ks, bucket_index))
  369. key_builder := strings.builder_make(0, 8, e.temp_allocator) or_return
  370. marshal_into(Encoder{e.flags, strings.to_stream(&key_builder), e.temp_allocator}, any{ key, info.key.id }) or_return
  371. append(&entries, Encoded_Entry{ &key_builder.buf, bucket_index }) or_return
  372. }
  373. slice.sort_by_cmp(entries[:], proc(a, b: Encoded_Entry) -> slice.Ordering {
  374. return slice.Ordering(bytes.compare(a.key[:], b.key[:]))
  375. })
  376. for entry in entries {
  377. io.write_full(e.writer, entry.key[:]) or_return
  378. delete(entry.key^)
  379. value := rawptr(runtime.map_cell_index_dynamic(vs, info.map_info.vs, entry.val_idx))
  380. marshal_into(e, any{ value, info.value.id }) or_return
  381. }
  382. return
  383. }
  384. }
  385. case runtime.Type_Info_Struct:
  386. switch vv in v {
  387. case Tag: return err_conv(_encode_tag(e, vv))
  388. }
  389. field_name :: #force_inline proc(info: runtime.Type_Info_Struct, i: int) -> string {
  390. if cbor_name := string(reflect.struct_tag_get(reflect.Struct_Tag(info.tags[i]), "cbor")); cbor_name != "" {
  391. return cbor_name
  392. } else {
  393. return info.names[i]
  394. }
  395. }
  396. marshal_entry :: #force_inline proc(e: Encoder, info: runtime.Type_Info_Struct, v: any, i: int) -> Marshal_Error {
  397. id := info.types[i].id
  398. data := rawptr(uintptr(v.data) + info.offsets[i])
  399. field_any := any{data, id}
  400. if tag := string(reflect.struct_tag_get(reflect.Struct_Tag(info.tags[i]), "cbor_tag")); tag != "" {
  401. if impl, ok := _tag_implementations_id[tag]; ok {
  402. return impl->marshal(e, field_any)
  403. }
  404. nr, ok := strconv.parse_u64_of_base(tag, 10)
  405. if !ok { return .Invalid_CBOR_Tag }
  406. if impl, nok := _tag_implementations_nr[nr]; nok {
  407. return impl->marshal(e, field_any)
  408. }
  409. err_conv(_encode_u64(e, nr, .Tag)) or_return
  410. }
  411. return marshal_into(e, field_any)
  412. }
  413. n: u64; {
  414. for _, i in info.names[:info.field_count] {
  415. if field_name(info, i) != "-" {
  416. n += 1
  417. }
  418. }
  419. err_conv(_encode_u64(e, n, .Map)) or_return
  420. }
  421. if .Deterministic_Map_Sorting in e.flags {
  422. Name :: struct {
  423. name: []byte,
  424. field: int,
  425. }
  426. entries := make([dynamic]Name, 0, n, e.temp_allocator) or_return
  427. defer delete(entries)
  428. for _, i in info.names[:info.field_count] {
  429. fname := field_name(info, i)
  430. if fname == "-" {
  431. continue
  432. }
  433. key_builder := strings.builder_make(e.temp_allocator) or_return
  434. err_conv(_encode_text(Encoder{e.flags, strings.to_stream(&key_builder), e.temp_allocator}, fname)) or_return
  435. append(&entries, Name{key_builder.buf[:], i}) or_return
  436. }
  437. // Sort lexicographic on the bytes of the key.
  438. slice.sort_by_cmp(entries[:], proc(a, b: Name) -> slice.Ordering {
  439. return slice.Ordering(bytes.compare(a.name, b.name))
  440. })
  441. for entry in entries {
  442. io.write_full(e.writer, entry.name) or_return
  443. marshal_entry(e, info, v, entry.field) or_return
  444. }
  445. } else {
  446. for _, i in info.names[:info.field_count] {
  447. fname := field_name(info, i)
  448. if fname == "-" {
  449. continue
  450. }
  451. err_conv(_encode_text(e, fname)) or_return
  452. marshal_entry(e, info, v, i) or_return
  453. }
  454. }
  455. return
  456. case runtime.Type_Info_Union:
  457. switch vv in v {
  458. case Value: return err_conv(encode(e, vv))
  459. }
  460. id := reflect.union_variant_typeid(v)
  461. if v.data == nil || id == nil {
  462. return _encode_nil(e.writer)
  463. }
  464. if len(info.variants) == 1 {
  465. return marshal_into(e, any{v.data, id})
  466. }
  467. // Encode a non-nil multi-variant union as the `TAG_OBJECT_TYPE`.
  468. // Which is a tag of an array, where the first element is the textual id/type of the object
  469. // that follows it.
  470. err_conv(_encode_u16(e, TAG_OBJECT_TYPE, .Tag)) or_return
  471. _encode_u8(e.writer, 2, .Array) or_return
  472. vti := reflect.union_variant_type_info(v)
  473. #partial switch vt in vti.variant {
  474. case reflect.Type_Info_Named:
  475. err_conv(_encode_text(e, vt.name)) or_return
  476. case:
  477. builder := strings.builder_make(e.temp_allocator) or_return
  478. defer strings.builder_destroy(&builder)
  479. reflect.write_type(&builder, vti)
  480. err_conv(_encode_text(e, strings.to_string(builder))) or_return
  481. }
  482. return marshal_into(e, any{v.data, vti.id})
  483. case runtime.Type_Info_Bit_Set:
  484. // Store bit_set as big endian just like the protocol.
  485. do_byte_swap := !reflect.bit_set_is_big_endian(v)
  486. switch ti.size * 8 {
  487. case 0:
  488. return _encode_u8(e.writer, 0)
  489. case 8:
  490. x := (^u8)(v.data)^
  491. return _encode_u8(e.writer, x)
  492. case 16:
  493. x := (^u16)(v.data)^
  494. if do_byte_swap { x = intrinsics.byte_swap(x) }
  495. return err_conv(_encode_u16(e, x))
  496. case 32:
  497. x := (^u32)(v.data)^
  498. if do_byte_swap { x = intrinsics.byte_swap(x) }
  499. return err_conv(_encode_u32(e, x))
  500. case 64:
  501. x := (^u64)(v.data)^
  502. if do_byte_swap { x = intrinsics.byte_swap(x) }
  503. return err_conv(_encode_u64(e, x))
  504. case:
  505. panic("unknown bit_size size")
  506. }
  507. }
  508. return _unsupported(v.id, nil)
  509. }