refactor: simplify handling of WASM web-time (#1042)

This commit is contained in:
Paolo Barbolini
2025-02-17 10:05:22 +01:00
committed by GitHub
parent 5748af4c98
commit 9cdefcea09
5 changed files with 22 additions and 24 deletions

View File

@@ -219,6 +219,7 @@ mod executor;
#[cfg(feature = "builder")]
#[cfg_attr(docsrs, doc(cfg(feature = "builder")))]
pub mod message;
mod time;
pub mod transport;
use std::error::Error as StdError;

View File

@@ -347,11 +347,7 @@ fn dkim_canonicalize_headers<'a>(
/// `dkim_config`
pub fn dkim_sign(message: &mut Message, dkim_config: &DkimConfig) {
#[cfg(feature = "web")]
dkim_sign_fixed_time(
message,
dkim_config,
crate::message::to_std_systemtime(web_time::SystemTime::now()),
);
dkim_sign_fixed_time(message, dkim_config, crate::time::now());
#[cfg(not(feature = "web"))]
dkim_sign_fixed_time(message, dkim_config, SystemTime::now());
}

View File

@@ -21,12 +21,7 @@ impl Date {
///
/// Shortcut for `Date::new(SystemTime::now())`
pub fn now() -> Self {
#[cfg(not(feature = "web"))]
return Self::new(SystemTime::now());
#[cfg(feature = "web")]
return Self::new(crate::message::to_std_systemtime(
web_time::SystemTime::now(),
));
Self::new(crate::time::now())
}
}

View File

@@ -277,10 +277,7 @@ impl MessageBuilder {
/// Shortcut for `self.date(SystemTime::now())`, it is automatically inserted
/// if no date has been provided.
pub fn date_now(self) -> Self {
#[cfg(not(feature = "web"))]
return self.date(SystemTime::now());
#[cfg(feature = "web")]
return self.date(to_std_systemtime(web_time::SystemTime::now()));
self.date(crate::time::now())
}
/// Set or add mailbox to `ReplyTo` header
@@ -626,17 +623,8 @@ fn make_message_id() -> String {
iter::repeat_with(fastrand::alphanumeric).take(36).collect()
}
#[cfg(feature = "web")]
pub(crate) fn to_std_systemtime(time: web_time::SystemTime) -> std::time::SystemTime {
let duration = time
.duration_since(web_time::SystemTime::UNIX_EPOCH)
.unwrap();
std::time::SystemTime::UNIX_EPOCH + duration
}
#[cfg(test)]
mod test {
use std::time::{Duration, SystemTime};
use pretty_assertions::assert_eq;

18
src/time.rs Normal file
View File

@@ -0,0 +1,18 @@
use std::time::SystemTime;
#[cfg(feature = "web")]
pub(crate) fn now() -> SystemTime {
fn to_std_systemtime(time: web_time::SystemTime) -> std::time::SystemTime {
let duration = time
.duration_since(web_time::SystemTime::UNIX_EPOCH)
.unwrap();
SystemTime::UNIX_EPOCH + duration
}
to_std_systemtime(web_time::SystemTime::now())
}
#[cfg(not(feature = "web"))]
pub(crate) fn now() -> SystemTime {
SystemTime::now()
}