Move TimeDelta to its own file for better reusability

Signed-off-by: Daniel D’Aquino <daniel@daquino.me>
This commit is contained in:
Daniel D’Aquino
2024-08-05 17:57:40 -07:00
parent 384e458118
commit 388d49927b
5 changed files with 38 additions and 34 deletions

View File

@ -1 +1,2 @@
pub mod notification_manager;
mod utils;

View File

@ -12,6 +12,7 @@ mod notepush_env;
use notepush_env::NotePushEnv;
mod api_request_handler;
mod nip98_auth;
mod utils;
#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {

View File

@ -3,8 +3,8 @@ use nostr;
use nostr::bitcoin::hashes::sha256::Hash as Sha256Hash;
use nostr::bitcoin::hashes::Hash;
use nostr::util::hex;
use nostr::Timestamp;
use serde_json::Value;
use super::utils::time_delta::TimeDelta;
pub async fn nip98_verify_auth_header(
auth_header: String,
@ -106,36 +106,3 @@ pub async fn nip98_verify_auth_header(
Ok(note.pubkey)
}
struct TimeDelta {
delta_abs_seconds: u64,
negative: bool,
}
impl TimeDelta {
/// Safely calculate the difference between two timestamps in seconds
/// This function is safer against overflows than subtracting the timestamps directly
fn subtracting(t1: Timestamp, t2: Timestamp) -> TimeDelta {
if t1 > t2 {
TimeDelta {
delta_abs_seconds: (t1 - t2).as_u64(),
negative: false,
}
} else {
TimeDelta {
delta_abs_seconds: (t2 - t1).as_u64(),
negative: true,
}
}
}
}
impl std::fmt::Display for TimeDelta {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.negative {
write!(f, "-{}", self.delta_abs_seconds)
} else {
write!(f, "{}", self.delta_abs_seconds)
}
}
}

1
src/utils/mod.rs Normal file
View File

@ -0,0 +1 @@
pub mod time_delta;

34
src/utils/time_delta.rs Normal file
View File

@ -0,0 +1,34 @@
use nostr_sdk::Timestamp;
pub struct TimeDelta {
pub delta_abs_seconds: u64,
pub negative: bool,
}
impl TimeDelta {
/// Safely calculate the difference between two timestamps in seconds
/// This function is safer against overflows than subtracting the timestamps directly
pub fn subtracting(t1: Timestamp, t2: Timestamp) -> TimeDelta {
if t1 > t2 {
TimeDelta {
delta_abs_seconds: (t1 - t2).as_u64(),
negative: false,
}
} else {
TimeDelta {
delta_abs_seconds: (t2 - t1).as_u64(),
negative: true,
}
}
}
}
impl std::fmt::Display for TimeDelta {
fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
if self.negative {
write!(f, "-{}", self.delta_abs_seconds)
} else {
write!(f, "{}", self.delta_abs_seconds)
}
}
}