feat(common): impl serialize and deserialize for Timestamp

This commit is contained in:
nazeh
2024-08-20 15:16:26 +03:00
parent 6ed8af7dff
commit 0ce4a9da65
2 changed files with 29 additions and 5 deletions

View File

@@ -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<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 {

View File

@@ -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 ===