Convert a `Value` into a `TokenStream`. The `Value` is constructed, not parsed from a JSON string.
(value: Value)
| 71 | |
| 72 | /// Convert a `Value` into a `TokenStream`. |
| 73 | /// |
| 74 | /// The `Value` is constructed, not parsed from a JSON string. |
| 75 | pub fn json_value_expr(value: Value) -> TokenStream { |
| 76 | match value { |
| 77 | Value::Null => quote! { |
| 78 | ::serde_json::Value::Null |
| 79 | }, |
| 80 | Value::Bool(bool) => quote! { |
| 81 | ::serde_json::Value::Bool(#bool) |
| 82 | }, |
| 83 | Value::Number(number) => { |
| 84 | if let Some(n) = number.as_u64() { |
| 85 | quote! { |
| 86 | ::serde_json::Value::Number(::serde_json::Number::from(#n)) |
| 87 | } |
| 88 | } else if let Some(n) = number.as_i64() { |
| 89 | quote! { |
| 90 | ::serde_json::Value::Number(::serde_json::Number::from(#n)) |
| 91 | } |
| 92 | } else if let Some(n) = number.as_f64() { |
| 93 | quote! { |
| 94 | ::serde_json::Value::Number(::serde_json::Number::from_f64(#n).expect("Unreachable, f64 is finite")) |
| 95 | } |
| 96 | } else { |
| 97 | // This is needed when the arbitrary-precision feature flag is enabled on serde_json |
| 98 | let s = number.to_string(); |
| 99 | quote! { |
| 100 | ::serde_json::Value::Number(#s.parse().expect(concat!("This was a valid number at compile time: ", #s))) |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | Value::String(string) => quote! { |
| 105 | ::serde_json::Value::String(::std::string::String::from(#string)) |
| 106 | }, |
| 107 | Value::Array(array) => { |
| 108 | let array = array.into_iter().map(json_value_expr); |
| 109 | quote! { |
| 110 | ::serde_json::Value::Array(vec![#(#array),*]) |
| 111 | } |
| 112 | } |
| 113 | Value::Object(object) => { |
| 114 | let len = object.len(); |
| 115 | |
| 116 | let mut keys = Vec::with_capacity(len); |
| 117 | let mut values = Vec::with_capacity(len); |
| 118 | for (key, value) in object { |
| 119 | keys.push(key); |
| 120 | values.push(json_value_expr(value)); |
| 121 | } |
| 122 | |
| 123 | quote! { |
| 124 | ::serde_json::Value::Object({ |
| 125 | let mut map = ::serde_json::Map::with_capacity(#len); |
| 126 | #(map.insert(::std::string::String::from(#keys), #values);)* |
| 127 | map |
| 128 | }) |
| 129 | } |
| 130 | } |
no test coverage detected