Skip to main content

x402_types/proto/
util.rs

1//! Utility types for protocol serialization.
2//!
3//! This module provides helper types for serializing values in the x402 wire format.
4
5use serde::de::Error;
6use serde::{Deserialize, Deserializer, Serialize, Serializer};
7use std::str::FromStr;
8
9/// A `u64` value that serializes as a string.
10///
11/// Some JSON parsers (particularly in JavaScript) cannot accurately represent
12/// large integers. This type serializes `u64` values as strings to preserve
13/// precision across all platforms.
14///
15/// # Example
16///
17/// ```rust
18/// use x402_types::proto::util::U64String;
19///
20/// let value = U64String::from(12345678901234567890u64);
21/// let json = serde_json::to_string(&value).unwrap();
22/// assert_eq!(json, "\"12345678901234567890\"");
23/// ```
24#[derive(Clone, Debug, Eq, PartialEq)]
25pub struct U64String(u64);
26
27impl U64String {
28    /// Returns the inner `u64` value.
29    pub fn inner(&self) -> u64 {
30        self.0
31    }
32}
33
34impl FromStr for U64String {
35    type Err = <u64 as FromStr>::Err;
36
37    fn from_str(s: &str) -> Result<Self, Self::Err> {
38        s.parse::<u64>().map(Self)
39    }
40}
41
42impl From<u64> for U64String {
43    fn from(value: u64) -> Self {
44        Self(value)
45    }
46}
47
48impl From<U64String> for u64 {
49    fn from(value: U64String) -> Self {
50        value.0
51    }
52}
53
54impl Serialize for U64String {
55    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
56    where
57        S: Serializer,
58    {
59        serializer.serialize_str(&self.0.to_string())
60    }
61}
62
63impl<'de> Deserialize<'de> for U64String {
64    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
65    where
66        D: Deserializer<'de>,
67    {
68        let s = String::deserialize(deserializer)?;
69        s.parse::<u64>().map(Self).map_err(D::Error::custom)
70    }
71}