marshal.odin 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507
  1. package json
  2. import "core:mem"
  3. import "core:math/bits"
  4. import "core:runtime"
  5. import "core:strconv"
  6. import "core:strings"
  7. import "core:io"
  8. Marshal_Data_Error :: enum {
  9. None,
  10. Unsupported_Type,
  11. }
  12. Marshal_Error :: union #shared_nil {
  13. Marshal_Data_Error,
  14. io.Error,
  15. }
  16. // careful with MJSON maps & non quotes usage as keys without whitespace will lead to bad results
  17. Marshal_Options :: struct {
  18. // output based on spec
  19. spec: Specification,
  20. // use line breaks & tab|spaces
  21. pretty: bool,
  22. // spacing
  23. use_spaces: bool,
  24. spaces: int,
  25. // state
  26. indentation: int,
  27. // option to output uint in JSON5 & MJSON
  28. write_uint_as_hex: bool,
  29. // mjson output options
  30. mjson_keys_use_quotes: bool,
  31. mjson_keys_use_equal_sign: bool,
  32. // mjson state
  33. mjson_skipped_first_braces_start: bool,
  34. mjson_skipped_first_braces_end: bool,
  35. }
  36. marshal :: proc(v: any, opt: Marshal_Options = {}, allocator := context.allocator) -> (data: []byte, err: Marshal_Error) {
  37. b := strings.builder_make(allocator)
  38. defer if err != nil {
  39. strings.builder_destroy(&b)
  40. }
  41. opt := opt
  42. marshal_to_builder(&b, v, &opt) or_return
  43. if len(b.buf) != 0 {
  44. data = b.buf[:]
  45. }
  46. return data, nil
  47. }
  48. marshal_to_builder :: proc(b: ^strings.Builder, v: any, opt: ^Marshal_Options) -> Marshal_Error {
  49. return marshal_to_writer(strings.to_writer(b), v, opt)
  50. }
  51. marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err: Marshal_Error) {
  52. if v == nil {
  53. io.write_string(w, "null") or_return
  54. return
  55. }
  56. ti := runtime.type_info_base(type_info_of(v.id))
  57. a := any{v.data, ti.id}
  58. switch info in ti.variant {
  59. case runtime.Type_Info_Named:
  60. unreachable()
  61. case runtime.Type_Info_Integer:
  62. buf: [40]byte
  63. u: u128
  64. switch i in a {
  65. case i8: u = u128(i)
  66. case i16: u = u128(i)
  67. case i32: u = u128(i)
  68. case i64: u = u128(i)
  69. case i128: u = u128(i)
  70. case int: u = u128(i)
  71. case u8: u = u128(i)
  72. case u16: u = u128(i)
  73. case u32: u = u128(i)
  74. case u64: u = u128(i)
  75. case u128: u = u128(i)
  76. case uint: u = u128(i)
  77. case uintptr: u = u128(i)
  78. case i16le: u = u128(i)
  79. case i32le: u = u128(i)
  80. case i64le: u = u128(i)
  81. case u16le: u = u128(i)
  82. case u32le: u = u128(i)
  83. case u64le: u = u128(i)
  84. case u128le: u = u128(i)
  85. case i16be: u = u128(i)
  86. case i32be: u = u128(i)
  87. case i64be: u = u128(i)
  88. case u16be: u = u128(i)
  89. case u32be: u = u128(i)
  90. case u64be: u = u128(i)
  91. case u128be: u = u128(i)
  92. }
  93. s: string
  94. // allow uints to be printed as hex
  95. if opt.write_uint_as_hex && (opt.spec == .JSON5 || opt.spec == .MJSON) {
  96. switch i in a {
  97. case u8, u16, u32, u64, u128:
  98. s = strconv.append_bits_128(buf[:], u, 16, info.signed, 8*ti.size, "0123456789abcdef", { .Prefix })
  99. case:
  100. s = strconv.append_bits_128(buf[:], u, 10, info.signed, 8*ti.size, "0123456789", nil)
  101. }
  102. } else {
  103. s = strconv.append_bits_128(buf[:], u, 10, info.signed, 8*ti.size, "0123456789", nil)
  104. }
  105. io.write_string(w, s) or_return
  106. case runtime.Type_Info_Rune:
  107. r := a.(rune)
  108. io.write_byte(w, '"') or_return
  109. io.write_escaped_rune(w, r, '"', true) or_return
  110. io.write_byte(w, '"') or_return
  111. case runtime.Type_Info_Float:
  112. switch f in a {
  113. case f16: io.write_f16(w, f) or_return
  114. case f32: io.write_f32(w, f) or_return
  115. case f64: io.write_f64(w, f) or_return
  116. case: return .Unsupported_Type
  117. }
  118. case runtime.Type_Info_Complex:
  119. r, i: f64
  120. switch z in a {
  121. case complex32: r, i = f64(real(z)), f64(imag(z))
  122. case complex64: r, i = f64(real(z)), f64(imag(z))
  123. case complex128: r, i = f64(real(z)), f64(imag(z))
  124. case: return .Unsupported_Type
  125. }
  126. io.write_byte(w, '[') or_return
  127. io.write_f64(w, r) or_return
  128. io.write_string(w, ", ") or_return
  129. io.write_f64(w, i) or_return
  130. io.write_byte(w, ']') or_return
  131. case runtime.Type_Info_Quaternion:
  132. return .Unsupported_Type
  133. case runtime.Type_Info_String:
  134. switch s in a {
  135. case string: io.write_quoted_string(w, s) or_return
  136. case cstring: io.write_quoted_string(w, string(s)) or_return
  137. }
  138. case runtime.Type_Info_Boolean:
  139. val: bool
  140. switch b in a {
  141. case bool: val = bool(b)
  142. case b8: val = bool(b)
  143. case b16: val = bool(b)
  144. case b32: val = bool(b)
  145. case b64: val = bool(b)
  146. }
  147. io.write_string(w, val ? "true" : "false") or_return
  148. case runtime.Type_Info_Any:
  149. return .Unsupported_Type
  150. case runtime.Type_Info_Type_Id:
  151. return .Unsupported_Type
  152. case runtime.Type_Info_Pointer:
  153. return .Unsupported_Type
  154. case runtime.Type_Info_Multi_Pointer:
  155. return .Unsupported_Type
  156. case runtime.Type_Info_Soa_Pointer:
  157. return .Unsupported_Type
  158. case runtime.Type_Info_Procedure:
  159. return .Unsupported_Type
  160. case runtime.Type_Info_Tuple:
  161. return .Unsupported_Type
  162. case runtime.Type_Info_Simd_Vector:
  163. return .Unsupported_Type
  164. case runtime.Type_Info_Relative_Pointer:
  165. return .Unsupported_Type
  166. case runtime.Type_Info_Relative_Slice:
  167. return .Unsupported_Type
  168. case runtime.Type_Info_Matrix:
  169. return .Unsupported_Type
  170. case runtime.Type_Info_Array:
  171. opt_write_start(w, opt, '[') or_return
  172. for i in 0..<info.count {
  173. opt_write_iteration(w, opt, i) or_return
  174. data := uintptr(v.data) + uintptr(i*info.elem_size)
  175. marshal_to_writer(w, any{rawptr(data), info.elem.id}, opt) or_return
  176. }
  177. opt_write_end(w, opt, ']') or_return
  178. case runtime.Type_Info_Enumerated_Array:
  179. index := runtime.type_info_base(info.index).variant.(runtime.Type_Info_Enum)
  180. opt_write_start(w, opt, '[') or_return
  181. for i in 0..<info.count {
  182. opt_write_iteration(w, opt, i) or_return
  183. data := uintptr(v.data) + uintptr(i*info.elem_size)
  184. marshal_to_writer(w, any{rawptr(data), info.elem.id}, opt) or_return
  185. }
  186. opt_write_end(w, opt, ']') or_return
  187. case runtime.Type_Info_Dynamic_Array:
  188. opt_write_start(w, opt, '[') or_return
  189. array := cast(^mem.Raw_Dynamic_Array)v.data
  190. for i in 0..<array.len {
  191. opt_write_iteration(w, opt, i) or_return
  192. data := uintptr(array.data) + uintptr(i*info.elem_size)
  193. marshal_to_writer(w, any{rawptr(data), info.elem.id}, opt) or_return
  194. }
  195. opt_write_end(w, opt, ']') or_return
  196. case runtime.Type_Info_Slice:
  197. opt_write_start(w, opt, '[') or_return
  198. slice := cast(^mem.Raw_Slice)v.data
  199. for i in 0..<slice.len {
  200. opt_write_iteration(w, opt, i) or_return
  201. data := uintptr(slice.data) + uintptr(i*info.elem_size)
  202. marshal_to_writer(w, any{rawptr(data), info.elem.id}, opt) or_return
  203. }
  204. opt_write_end(w, opt, ']') or_return
  205. case runtime.Type_Info_Map:
  206. m := (^mem.Raw_Map)(v.data)
  207. opt_write_start(w, opt, '{') or_return
  208. if m != nil {
  209. if info.generated_struct == nil {
  210. return .Unsupported_Type
  211. }
  212. entries := &m.entries
  213. gs := runtime.type_info_base(info.generated_struct).variant.(runtime.Type_Info_Struct)
  214. ed := runtime.type_info_base(gs.types[1]).variant.(runtime.Type_Info_Dynamic_Array)
  215. entry_type := ed.elem.variant.(runtime.Type_Info_Struct)
  216. entry_size := ed.elem_size
  217. for i in 0..<entries.len {
  218. opt_write_iteration(w, opt, i) or_return
  219. data := uintptr(entries.data) + uintptr(i*entry_size)
  220. key := rawptr(data + entry_type.offsets[2])
  221. value := rawptr(data + entry_type.offsets[3])
  222. // check for string type
  223. {
  224. v := any{key, info.key.id}
  225. ti := runtime.type_info_base(type_info_of(v.id))
  226. a := any{v.data, ti.id}
  227. name: string
  228. #partial switch info in ti.variant {
  229. case runtime.Type_Info_String:
  230. switch s in a {
  231. case string: name = s
  232. case cstring: name = string(s)
  233. }
  234. opt_write_key(w, opt, name) or_return
  235. case: return .Unsupported_Type
  236. }
  237. }
  238. marshal_to_writer(w, any{value, info.value.id}, opt) or_return
  239. }
  240. }
  241. opt_write_end(w, opt, '}') or_return
  242. case runtime.Type_Info_Struct:
  243. opt_write_start(w, opt, '{') or_return
  244. for name, i in info.names {
  245. opt_write_iteration(w, opt, i) or_return
  246. opt_write_key(w, opt, name) or_return
  247. id := info.types[i].id
  248. data := rawptr(uintptr(v.data) + info.offsets[i])
  249. marshal_to_writer(w, any{data, id}, opt) or_return
  250. }
  251. opt_write_end(w, opt, '}') or_return
  252. case runtime.Type_Info_Union:
  253. tag_ptr := uintptr(v.data) + info.tag_offset
  254. tag_any := any{rawptr(tag_ptr), info.tag_type.id}
  255. tag: i64 = -1
  256. switch i in tag_any {
  257. case u8: tag = i64(i)
  258. case i8: tag = i64(i)
  259. case u16: tag = i64(i)
  260. case i16: tag = i64(i)
  261. case u32: tag = i64(i)
  262. case i32: tag = i64(i)
  263. case u64: tag = i64(i)
  264. case i64: tag = i64(i)
  265. case: panic("Invalid union tag type")
  266. }
  267. if v.data == nil || tag == 0 {
  268. io.write_string(w, "null") or_return
  269. } else {
  270. id := info.variants[tag-1].id
  271. return marshal_to_writer(w, any{v.data, id}, opt)
  272. }
  273. case runtime.Type_Info_Enum:
  274. return marshal_to_writer(w, any{v.data, info.base.id}, opt)
  275. case runtime.Type_Info_Bit_Set:
  276. is_bit_set_different_endian_to_platform :: proc(ti: ^runtime.Type_Info) -> bool {
  277. if ti == nil {
  278. return false
  279. }
  280. t := runtime.type_info_base(ti)
  281. #partial switch info in t.variant {
  282. case runtime.Type_Info_Integer:
  283. switch info.endianness {
  284. case .Platform: return false
  285. case .Little: return ODIN_ENDIAN != .Little
  286. case .Big: return ODIN_ENDIAN != .Big
  287. }
  288. }
  289. return false
  290. }
  291. bit_data: u64
  292. bit_size := u64(8*ti.size)
  293. do_byte_swap := is_bit_set_different_endian_to_platform(info.underlying)
  294. switch bit_size {
  295. case 0: bit_data = 0
  296. case 8:
  297. x := (^u8)(v.data)^
  298. bit_data = u64(x)
  299. case 16:
  300. x := (^u16)(v.data)^
  301. if do_byte_swap {
  302. x = bits.byte_swap(x)
  303. }
  304. bit_data = u64(x)
  305. case 32:
  306. x := (^u32)(v.data)^
  307. if do_byte_swap {
  308. x = bits.byte_swap(x)
  309. }
  310. bit_data = u64(x)
  311. case 64:
  312. x := (^u64)(v.data)^
  313. if do_byte_swap {
  314. x = bits.byte_swap(x)
  315. }
  316. bit_data = u64(x)
  317. case: panic("unknown bit_size size")
  318. }
  319. io.write_u64(w, bit_data) or_return
  320. return .Unsupported_Type
  321. }
  322. return
  323. }
  324. // write key as quoted string or with optional quotes in mjson
  325. opt_write_key :: proc(w: io.Writer, opt: ^Marshal_Options, name: string) -> (err: io.Error) {
  326. switch opt.spec {
  327. case .JSON, .JSON5:
  328. io.write_quoted_string(w, name) or_return
  329. io.write_string(w, ": ") or_return
  330. case .MJSON:
  331. if opt.mjson_keys_use_quotes {
  332. io.write_quoted_string(w, name) or_return
  333. } else {
  334. io.write_string(w, name) or_return
  335. }
  336. if opt.mjson_keys_use_equal_sign {
  337. io.write_string(w, " = ") or_return
  338. } else {
  339. io.write_string(w, ": ") or_return
  340. }
  341. }
  342. return
  343. }
  344. // insert start byte and increase indentation on pretty
  345. opt_write_start :: proc(w: io.Writer, opt: ^Marshal_Options, c: byte) -> (err: io.Error) {
  346. // skip mjson starting braces
  347. if opt.spec == .MJSON && !opt.mjson_skipped_first_braces_start {
  348. opt.mjson_skipped_first_braces_start = true
  349. return
  350. }
  351. io.write_byte(w, c) or_return
  352. opt.indentation += 1
  353. if opt.pretty {
  354. io.write_byte(w, '\n') or_return
  355. }
  356. return
  357. }
  358. // insert comma seperation and write indentations
  359. opt_write_iteration :: proc(w: io.Writer, opt: ^Marshal_Options, iteration: int) -> (err: io.Error) {
  360. switch opt.spec {
  361. case .JSON, .JSON5:
  362. if iteration > 0 {
  363. io.write_string(w, ", ") or_return
  364. if opt.pretty {
  365. io.write_byte(w, '\n') or_return
  366. }
  367. }
  368. opt_write_indentation(w, opt) or_return
  369. case .MJSON:
  370. if iteration > 0 {
  371. // on pretty no commas necessary
  372. if opt.pretty {
  373. io.write_byte(w, '\n') or_return
  374. } else {
  375. // comma seperation necessary for non pretty output!
  376. io.write_string(w, ", ") or_return
  377. }
  378. }
  379. opt_write_indentation(w, opt) or_return
  380. }
  381. return
  382. }
  383. // decrease indent, write spacing and insert end byte
  384. opt_write_end :: proc(w: io.Writer, opt: ^Marshal_Options, c: byte) -> (err: io.Error) {
  385. if opt.spec == .MJSON && opt.mjson_skipped_first_braces_start && !opt.mjson_skipped_first_braces_end {
  386. if opt.indentation == 0 {
  387. opt.mjson_skipped_first_braces_end = true
  388. return
  389. }
  390. }
  391. opt.indentation -= 1
  392. if opt.pretty {
  393. io.write_byte(w, '\n') or_return
  394. opt_write_indentation(w, opt) or_return
  395. }
  396. io.write_byte(w, c) or_return
  397. return
  398. }
  399. // writes current indentation level based on options
  400. opt_write_indentation :: proc(w: io.Writer, opt: ^Marshal_Options) -> (err: io.Error) {
  401. if !opt.pretty {
  402. return
  403. }
  404. if opt.use_spaces {
  405. spaces := opt.spaces == 0 ? 4 : opt.spaces
  406. for _ in 0..<opt.indentation * spaces {
  407. io.write_byte(w, ' ') or_return
  408. }
  409. } else {
  410. for _ in 0..<opt.indentation {
  411. io.write_byte(w, '\t') or_return
  412. }
  413. }
  414. return
  415. }