From 0ce4a9da65129147e0c3cb7cb4507b97d5e26f62 Mon Sep 17 00:00:00 2001 From: nazeh Date: Tue, 20 Aug 2024 15:16:26 +0300 Subject: [PATCH] feat(common): impl serialize and deserialize for Timestamp --- pubky-common/src/timestamp.rs | 27 +++++++++++++++++++ .../src/database/tables/entries.rs | 7 ++--- 2 files changed, 29 insertions(+), 5 deletions(-) diff --git a/pubky-common/src/timestamp.rs b/pubky-common/src/timestamp.rs index 4c546d5..174c7e3 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 { diff --git a/pubky-homeserver/src/database/tables/entries.rs b/pubky-homeserver/src/database/tables/entries.rs index 22a3aa4..70dafe4 100644 --- a/pubky-homeserver/src/database/tables/entries.rs +++ b/pubky-homeserver/src/database/tables/entries.rs @@ -200,7 +200,7 @@ pub struct Entry { /// Encoding version version: usize, /// Modified at - timestamp: u64, + timestamp: Timestamp, content_hash: [u8; 32], content_length: usize, content_type: String, @@ -211,10 +211,7 @@ pub struct Entry { impl Entry { pub fn new() -> Self { - Self { - timestamp: Timestamp::now().into_inner(), - ..Default::default() - } + Default::default() } // === Setters ===