From 19dd3cb2ba1f08edef327edd752113f4f8a37a2f Mon Sep 17 00:00:00 2001 From: nazeh Date: Mon, 26 Aug 2024 14:24:37 +0300 Subject: [PATCH] feat(common): add serde to Timestamp --- Cargo.lock | 1 + pubky-common/Cargo.toml | 13 +++++++++++- pubky-common/src/timestamp.rs | 40 +++++++++++++++++++++++++++++++++++ 3 files changed, 53 insertions(+), 1 deletion(-) diff --git a/Cargo.lock b/Cargo.lock index 65b7b0b..72bffff 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -635,6 +635,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" dependencies = [ "pkcs8", + "serde", "signature", ] diff --git a/pubky-common/Cargo.toml b/pubky-common/Cargo.toml index 0a9df3b..202a815 100644 --- a/pubky-common/Cargo.toml +++ b/pubky-common/Cargo.toml @@ -14,8 +14,19 @@ pkarr = "2.1.0" rand = "0.8.5" thiserror = "1.0.60" postcard = { version = "1.0.8", features = ["alloc"] } -serde = { version = "1.0.204", features = ["derive"] } crypto_secretbox = { version = "0.1.1", features = ["std"] } +serde = { version = "1.0.204", features = ["derive"], optional = true } + [target.'cfg(target_arch = "wasm32")'.dependencies] js-sys = "0.3.69" + +[dev-dependencies] +postcard = "1.0.8" + +[features] + +serde = ["dep:serde", "ed25519-dalek/serde"] +full = ['serde'] + +default = ['full'] diff --git a/pubky-common/src/timestamp.rs b/pubky-common/src/timestamp.rs index 4c546d5..0235f66 100644 --- a/pubky-common/src/timestamp.rs +++ b/pubky-common/src/timestamp.rs @@ -1,5 +1,6 @@ //! Monotonic unix timestamp in microseconds +use serde::{Deserialize, Serialize}; use std::fmt::Display; use std::{ ops::{Add, Sub}, @@ -83,6 +84,12 @@ impl Timestamp { } } +impl Default for Timestamp { + fn default() -> Self { + Timestamp::now() + } +} + impl Display for Timestamp { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { let bytes: [u8; 8] = self.into(); @@ -155,6 +162,26 @@ impl Sub for &Timestamp { } } +impl Serialize for Timestamp { + fn serialize(&self, serializer: S) -> Result + where + S: serde::Serializer, + { + let bytes = self.to_bytes(); + bytes.serialize(serializer) + } +} + +impl<'de> Deserialize<'de> for Timestamp { + fn deserialize(deserializer: D) -> Result + where + D: serde::Deserializer<'de>, + { + let bytes: [u8; 8] = Deserialize::deserialize(deserializer)?; + Ok(Timestamp(u64::from_be_bytes(bytes))) + } +} + #[cfg(not(target_arch = "wasm32"))] /// Return the number of microseconds since [SystemTime::UNIX_EPOCH] fn system_time() -> u64 { @@ -237,4 +264,17 @@ mod tests { assert_eq!(decoded, timestamp) } + + #[test] + fn serde() { + let timestamp = Timestamp::now(); + + let serialized = postcard::to_allocvec(×tamp).unwrap(); + + assert_eq!(serialized, timestamp.to_bytes()); + + let deserialized: Timestamp = postcard::from_bytes(&serialized).unwrap(); + + assert_eq!(deserialized, timestamp); + } }