Skip to content

Commit

Permalink
lsn: add serde_as_u64 mod
Browse files Browse the repository at this point in the history
  • Loading branch information
koivunej committed Oct 9, 2023
1 parent 6717959 commit 0d2b9aa
Showing 1 changed file with 43 additions and 0 deletions.
43 changes: 43 additions & 0 deletions libs/utils/src/lsn.rs
Original file line number Diff line number Diff line change
Expand Up @@ -62,6 +62,49 @@ impl<'de> Deserialize<'de> for Lsn {
}
}

/// Allows (de)serialization of an `Lsn` always as `u64`.
///
/// ### Example
///
/// ```rust
/// # use serde::{Serialize, Deserialize};
/// use utils::lsn::Lsn;
///
/// #[derive(Partialeq, Serialize, Deserialize)]
/// struct Foo {
/// #[serde(with = "utils::lsn::as_u64")]
/// always_u64: Lsn,
/// }
///
/// let orig = Foo { always_u64: Lsn(1234) };
///
/// let res = serde_json::to_string(&).unwrap();
/// assert_eq!(res, r#"{"always_u64": 1234}"#);
///
/// let foo = serde_json::from_str::<Foo>(&res).unwrap();
/// assert_eq!(res, orig);
/// ```
///
pub mod serde_as_u64 {
use super::Lsn;

/// Serializes the Lsn as u64 disregarding the human readability of the format.
///
/// Meant to be used via `#[serde(with = "...")]` or `#[serde(serialize_with = "...")]`.
pub fn serialize<S: serde::Serializer>(lsn: &Lsn, serializer: S) -> Result<S::Ok, S::Error> {
use serde::Serialize;
lsn.0.serialize(serializer)
}

/// Deserializes the Lsn as u64 disregarding the human readability of the format.
///
/// Meant to be used via `#[serde(with = "...")]` or `#[serde(deserialize_with = "...")]`.
pub fn deserialize<'de, D: serde::Deserializer<'de>>(deserializer: D) -> Result<Lsn, D::Error> {
use serde::Deserialize;
u64::deserialize(deserializer).map(Lsn)
}
}

/// We tried to parse an LSN from a string, but failed
#[derive(Debug, PartialEq, Eq, thiserror::Error)]
#[error("LsnParseError")]
Expand Down

0 comments on commit 0d2b9aa

Please sign in to comment.