Browse Source

add uint as hex option

Michael Kutowski 3 years ago
parent
commit
425dec8bb8
1 changed files with 21 additions and 10 deletions
  1. 21 10
      core/encoding/json/marshal.odin

+ 21 - 10
core/encoding/json/marshal.odin

@@ -17,7 +17,7 @@ Marshal_Error :: union #shared_nil {
 	io.Error,
 	io.Error,
 }
 }
 
 
-// supports json specs
+// NOTE careful with MJSON maps & non quotes usage as keys without whitespace will lead to bad results
 Marshal_Options :: struct {
 Marshal_Options :: struct {
 	// output based on spec
 	// output based on spec
 	spec: Specification,
 	spec: Specification,
@@ -28,11 +28,13 @@ Marshal_Options :: struct {
 	// spacing
 	// spacing
 	use_spaces: bool,
 	use_spaces: bool,
 	spaces: int,
 	spaces: int,
-	tabs: int,
 
 
 	// state
 	// state
 	indentation: int,
 	indentation: int,
 
 
+	// option to output uint in JSON5 & MJSON
+	write_uint_as_hex: bool, 
+
 	// mjson output options
 	// mjson output options
 	mjson_keys_use_quotes: bool,
 	mjson_keys_use_quotes: bool,
 	mjson_keys_use_equal_sign: bool,
 	mjson_keys_use_equal_sign: bool,
@@ -109,7 +111,23 @@ marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err:
 		case u128be: u = u128(i)
 		case u128be: u = u128(i)
 		}
 		}
 
 
-		s := strconv.append_bits_128(buf[:], u, 10, info.signed, 8*ti.size, "0123456789", nil)
+		s: string
+
+		// allow uints to be printed as hex
+		if opt.write_uint_as_hex && (opt.spec == .JSON5 || opt.spec == .MJSON) {
+			switch i in a {
+				case u8, u16, u32, u64, u128: {
+					s = strconv.append_bits_128(buf[:], u, 16, info.signed, 8*ti.size, "0123456789abcdef", { .Prefix })
+				}
+
+				case: {
+					s = strconv.append_bits_128(buf[:], u, 10, info.signed, 8*ti.size, "0123456789", nil)
+				}
+			}
+		} else {
+			s = strconv.append_bits_128(buf[:], u, 10, info.signed, 8*ti.size, "0123456789", nil)
+		}
+
 		io.write_string(w, s) or_return
 		io.write_string(w, s) or_return
 
 
 
 
@@ -261,18 +279,11 @@ marshal_to_writer :: proc(w: io.Writer, v: any, opt: ^Marshal_Options) -> (err:
 
 
 					#partial switch info in ti.variant {
 					#partial switch info in ti.variant {
 						case runtime.Type_Info_String: {
 						case runtime.Type_Info_String: {
-							// fmt.eprintln("WAS STRING")
-
 							switch s in a {
 							switch s in a {
 								case string: name = s
 								case string: name = s
 								case cstring: name = string(s)
 								case cstring: name = string(s)
 							}
 							}
 
 
-							// NOTE need to ensure that map keys are valid for mjson and contain no whitespace
-							if opt.spec == .MJSON && !opt.mjson_keys_use_quotes {
-								name, _ = strings.replace_all(name, " ", "_", context.temp_allocator)
-							}
-
 							opt_write_key(w, opt, name) or_return
 							opt_write_key(w, opt, name) or_return
 						}
 						}