1#[cfg(not(feature = "std"))]
17use alloc::{format, string::String, string::ToString, vec::Vec};
18
19use base64::{engine::general_purpose::STANDARD, Engine as _};
20
21#[cfg(feature = "std")]
25pub fn canonical_json(value: &serde_json::Value) -> Vec<u8> {
26 let mut out = String::new();
27 encode_value(value, &mut out);
28 out.into_bytes()
29}
30
31#[cfg(feature = "std")]
32fn encode_value(v: &serde_json::Value, out: &mut String) {
33 use serde_json::Value;
34 match v {
35 Value::Null => out.push_str("null"),
36 Value::Bool(true) => out.push_str("true"),
37 Value::Bool(false) => out.push_str("false"),
38 Value::Number(n) => out.push_str(&encode_number(n)),
39 Value::String(s) => encode_string(s, out),
40 Value::Array(arr) => {
41 out.push('[');
42 for (i, item) in arr.iter().enumerate() {
43 if i > 0 {
44 out.push(',');
45 }
46 encode_value(item, out);
47 }
48 out.push(']');
49 }
50 Value::Object(obj) => {
51 let mut keys: Vec<&String> = obj.keys().collect();
53 keys.sort();
54 out.push('{');
55 let mut first = true;
56 for k in keys {
57 let val = &obj[k];
58 if val.is_null() {
60 continue;
61 }
62 if !first {
63 out.push(',');
64 }
65 encode_string(k, out);
66 out.push(':');
67 encode_value(val, out);
68 first = false;
69 }
70 out.push('}');
71 }
72 }
73}
74
75#[cfg(feature = "std")]
81fn encode_number(n: &serde_json::Number) -> String {
82 if let Some(i) = n.as_i64() {
83 return i.to_string();
84 }
85 if let Some(u) = n.as_u64() {
86 return u.to_string();
87 }
88 if let Some(f) = n.as_f64() {
89 if f.is_finite() && f.fract() == 0.0 && f.abs() < 1e15 {
90 return (f as i64).to_string();
92 }
93 return f.to_string();
94 }
95 n.to_string()
96}
97
98fn encode_string(s: &str, out: &mut String) {
99 out.push('"');
100 for c in s.chars() {
101 match c {
102 '"' => out.push_str("\\\""),
103 '\\' => out.push_str("\\\\"),
104 '\u{0008}' => out.push_str("\\b"),
105 '\u{0009}' => out.push_str("\\t"),
106 '\u{000A}' => out.push_str("\\n"),
107 '\u{000C}' => out.push_str("\\f"),
108 '\u{000D}' => out.push_str("\\r"),
109 '\u{2028}' => out.push_str("\\u2028"),
110 '\u{2029}' => out.push_str("\\u2029"),
111 c if (c as u32) < 0x20 => {
112 out.push_str(&format!("\\u{:04x}", c as u32));
113 }
114 c => out.push(c),
116 }
117 }
118 out.push('"');
119}
120
121pub fn base64_std_encode(data: &[u8]) -> String {
123 STANDARD.encode(data)
124}
125
126pub fn base64_std_decode(s: &str) -> Result<Vec<u8>, base64::DecodeError> {
128 STANDARD.decode(s)
129}
130
131pub fn hex_encode(data: &[u8]) -> String {
133 hex::encode(data)
134}
135
136pub fn hex_decode(s: &str) -> Result<Vec<u8>, hex::FromHexError> {
138 hex::decode(s)
139}
140
141pub fn encode_str(s: &str, out: &mut String) {
150 encode_string(s, out);
151}
152
153pub fn encode_i64(n: i64, out: &mut String) {
155 out.push_str(&n.to_string());
156}
157
158pub fn encode_i32(n: i32, out: &mut String) {
160 out.push_str(&n.to_string());
161}
162
163pub fn encode_f64(n: f64, out: &mut String) {
166 if n.is_finite() && n.fract() == 0.0 && n.abs() < 1e15 {
167 out.push_str(&(n as i64).to_string());
168 } else {
169 out.push_str(&n.to_string());
170 }
171}
172
173pub fn encode_bool(b: bool, out: &mut String) {
175 out.push_str(if b { "true" } else { "false" });
176}
177
178pub fn encode_bytes_b64(b: &[u8], out: &mut String) {
180 let s = base64_std_encode(b);
181 encode_string(&s, out);
182}
183
184pub fn encode_str_array(arr: &[String], out: &mut String) {
186 out.push('[');
187 for (i, s) in arr.iter().enumerate() {
188 if i > 0 {
189 out.push(',');
190 }
191 encode_string(s, out);
192 }
193 out.push(']');
194}
195
196pub fn encode_points_array(pts: &[[f64; 2]], out: &mut String) {
198 out.push('[');
199 for (i, pt) in pts.iter().enumerate() {
200 if i > 0 {
201 out.push(',');
202 }
203 out.push('[');
204 encode_f64(pt[0], out);
205 out.push(',');
206 encode_f64(pt[1], out);
207 out.push(']');
208 }
209 out.push(']');
210}
211
212pub fn encode_constraint(c: &crate::types::Constraint, out: &mut String) {
215 match c.kind.as_str() {
216 "geo_circle" => {
217 out.push('{');
219 out.push_str("\"lat\":"); encode_f64(c.lat, out);
220 out.push_str(",\"lon\":"); encode_f64(c.lon, out);
221 out.push_str(",\"radius_m\":"); encode_f64(c.radius_m, out);
222 out.push_str(",\"type\":"); encode_string(&c.kind, out);
223 out.push('}');
224 }
225 "geo_polygon" => {
226 out.push('{');
228 out.push_str("\"points\":"); encode_points_array(&c.points, out);
229 out.push_str(",\"type\":"); encode_string(&c.kind, out);
230 out.push('}');
231 }
232 "geo_bbox" => {
233 out.push('{');
236 let has_alt = c.min_alt_m != 0.0 || c.max_alt_m != 0.0;
237 if has_alt {
238 out.push_str("\"max_alt_m\":"); encode_f64(c.max_alt_m, out);
239 out.push(',');
240 }
241 out.push_str("\"max_lat\":"); encode_f64(c.max_lat, out);
242 out.push_str(",\"max_lon\":"); encode_f64(c.max_lon, out);
243 if has_alt {
244 out.push_str(",\"min_alt_m\":"); encode_f64(c.min_alt_m, out);
245 }
246 out.push_str(",\"min_lat\":"); encode_f64(c.min_lat, out);
247 out.push_str(",\"min_lon\":"); encode_f64(c.min_lon, out);
248 out.push_str(",\"type\":"); encode_string(&c.kind, out);
249 out.push('}');
250 }
251 "time_window" => {
252 out.push('{');
254 out.push_str("\"end\":"); encode_string(&c.end, out);
255 out.push_str(",\"start\":"); encode_string(&c.start, out);
256 out.push_str(",\"type\":"); encode_string(&c.kind, out);
257 out.push_str(",\"tz\":"); encode_string(&c.tz, out);
258 out.push('}');
259 }
260 "max_speed_mps" => {
261 out.push('{');
263 out.push_str("\"max_mps\":"); encode_f64(c.max_mps, out);
264 out.push_str(",\"type\":"); encode_string(&c.kind, out);
265 out.push('}');
266 }
267 "max_amount" => {
268 out.push('{');
270 out.push_str("\"currency\":"); encode_string(&c.currency, out);
271 out.push_str(",\"max_amount\":"); encode_f64(c.max_amount, out);
272 out.push_str(",\"type\":"); encode_string(&c.kind, out);
273 out.push('}');
274 }
275 "max_rate" => {
276 out.push('{');
278 out.push_str("\"count\":"); encode_i64(c.count, out);
279 out.push_str(",\"type\":"); encode_string(&c.kind, out);
280 out.push_str(",\"window_s\":"); encode_i64(c.window_s, out);
281 out.push('}');
282 }
283 "resource_path" => {
284 out.push('{');
286 if let Some(prefix) = &c.path_prefix {
287 out.push_str("\"path_prefix\":"); encode_string(prefix, out);
288 out.push(',');
289 }
290 out.push_str("\"resource_id\":"); encode_string(&c.resource_id, out);
291 out.push_str(",\"type\":"); encode_string(&c.kind, out);
292 out.push('}');
293 }
294 _ => {
297 out.push('{');
298 if let Some(params) = &c.params {
299 out.push_str("\"params\":"); encode_params_object(params, out);
300 out.push(',');
301 }
302 out.push_str("\"type\":"); encode_string(&c.kind, out);
303 out.push('}');
304 }
305 }
306}
307
308pub fn encode_params_object(
311 map: &alloc::collections::BTreeMap<String, crate::types::ParamsValue>,
312 out: &mut String,
313) {
314 out.push('{');
315 for (i, (k, v)) in map.iter().enumerate() {
316 if i > 0 {
317 out.push(',');
318 }
319 encode_string(k, out);
320 out.push(':');
321 encode_params_value(v, out);
322 }
323 out.push('}');
324}
325
326pub fn encode_params_value(v: &crate::types::ParamsValue, out: &mut String) {
328 use crate::types::ParamsValue;
329 match v {
330 ParamsValue::Null => out.push_str("null"),
331 ParamsValue::Bool(b) => encode_bool(*b, out),
332 ParamsValue::Int(n) => encode_i64(*n, out),
333 ParamsValue::Str(s) => encode_string(s, out),
334 ParamsValue::Array(items) => {
335 out.push('[');
336 for (i, item) in items.iter().enumerate() {
337 if i > 0 {
338 out.push(',');
339 }
340 encode_params_value(item, out);
341 }
342 out.push(']');
343 }
344 ParamsValue::Object(map) => encode_params_object(map, out),
345 }
346}
347
348pub fn encode_constraints(cs: &[crate::types::Constraint], out: &mut String) {
350 out.push('[');
351 for (i, c) in cs.iter().enumerate() {
352 if i > 0 {
353 out.push(',');
354 }
355 encode_constraint(c, out);
356 }
357 out.push(']');
358}
359
360pub fn encode_hybrid_pub_key(pk: &crate::types::HybridPublicKey, out: &mut String) {
363 out.push('{');
364 out.push_str("\"ed25519\":"); encode_bytes_b64(&pk.ed25519, out);
365 out.push_str(",\"ml_dsa_65\":"); encode_bytes_b64(&pk.ml_dsa_65, out);
366 out.push('}');
367}
368
369pub fn encode_hybrid_sig(sig: &crate::types::HybridSignature, out: &mut String) {
371 out.push('{');
372 out.push_str("\"ed25519\":"); encode_bytes_b64(&sig.ed25519, out);
373 out.push_str(",\"ml_dsa_65\":"); encode_bytes_b64(&sig.ml_dsa_65, out);
374 out.push('}');
375}
376
377pub mod base64_bytes {
379 #[cfg(not(feature = "std"))]
380 use alloc::{format, string::String, vec::Vec};
381 use super::{base64_std_decode, base64_std_encode};
382 use serde::{de::Error, Deserialize, Deserializer, Serializer};
383
384 pub fn serialize<S>(bytes: &[u8], serializer: S) -> Result<S::Ok, S::Error>
385 where
386 S: Serializer,
387 {
388 serializer.serialize_str(&base64_std_encode(bytes))
389 }
390
391 pub fn deserialize<'de, D>(deserializer: D) -> Result<Vec<u8>, D::Error>
392 where
393 D: Deserializer<'de>,
394 {
395 let s = String::deserialize(deserializer)?;
396 base64_std_decode(&s).map_err(|e| D::Error::custom(format!("base64 decode: {e}")))
397 }
398}
399
400pub mod wire_int {
415 use serde::{de::Error as DeError, ser::Error as SerError, Deserialize, Deserializer, Serializer};
416
417 pub const MAX_SAFE_INTEGER: i64 = (1 << 53) - 1;
419
420 pub fn in_domain(v: i64) -> bool {
422 (-MAX_SAFE_INTEGER..=MAX_SAFE_INTEGER).contains(&v)
423 }
424
425 pub fn deserialize<'de, D>(deserializer: D) -> Result<i64, D::Error>
426 where
427 D: Deserializer<'de>,
428 {
429 let v = i64::deserialize(deserializer)?;
430 if !in_domain(v) {
431 return Err(D::Error::custom(
432 "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
433 ));
434 }
435 Ok(v)
436 }
437
438 pub fn serialize<S>(v: &i64, serializer: S) -> Result<S::Ok, S::Error>
441 where
442 S: Serializer,
443 {
444 if !in_domain(*v) {
445 return Err(S::Error::custom(
446 "integer outside the safe-integer range [-(2^53-1), 2^53-1]",
447 ));
448 }
449 serializer.serialize_i64(*v)
450 }
451}