Skip to content

Commit

Permalink
feat(common): add serde to Timestamp
Browse files Browse the repository at this point in the history
  • Loading branch information
Nuhvi committed Aug 26, 2024
1 parent 620e2ad commit 19dd3cb
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 1 deletion.
1 change: 1 addition & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

13 changes: 12 additions & 1 deletion pubky-common/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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']
40 changes: 40 additions & 0 deletions pubky-common/src/timestamp.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
//! Monotonic unix timestamp in microseconds
use serde::{Deserialize, Serialize};
use std::fmt::Display;
use std::{
ops::{Add, Sub},
Expand Down Expand Up @@ -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();
Expand Down Expand Up @@ -155,6 +162,26 @@ impl Sub<u64> for &Timestamp {
}
}

impl Serialize for Timestamp {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: serde::Serializer,
{
let bytes = self.to_bytes();
bytes.serialize(serializer)
}
}

impl<'de> Deserialize<'de> for Timestamp {
fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
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 {
Expand Down Expand Up @@ -237,4 +264,17 @@ mod tests {

assert_eq!(decoded, timestamp)
}

#[test]
fn serde() {
let timestamp = Timestamp::now();

let serialized = postcard::to_allocvec(&timestamp).unwrap();

assert_eq!(serialized, timestamp.to_bytes());

let deserialized: Timestamp = postcard::from_bytes(&serialized).unwrap();

assert_eq!(deserialized, timestamp);
}
}

0 comments on commit 19dd3cb

Please sign in to comment.