From 05499bd1609f9ac4dd5f39e0bbf70da529179aed Mon Sep 17 00:00:00 2001 From: Jakub Wieczorek Date: Tue, 30 Jan 2024 15:17:42 +0100 Subject: [PATCH] Enable wasm32 compatibility by using web_time::SystemTime. --- Cargo.toml | 4 ++++ src/generator.rs | 6 ++---- src/lib.rs | 2 ++ src/time.rs | 4 ++-- src/time_utils.rs | 9 +++++++++ 5 files changed, 19 insertions(+), 6 deletions(-) create mode 100644 src/time_utils.rs diff --git a/Cargo.toml b/Cargo.toml index bc6d0ca..c206ef4 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -24,6 +24,10 @@ uuid = { version = "1.1", optional = true } postgres-types = { version = "0.2.6", optional = true } bytes = { version = "1.4.0", optional = true } +[target.wasm32-unknown-unknown.dependencies] +getrandom = { version = "0.2", features = ["js"] } +web-time = "1" + [dev-dependencies] bencher = "0.1" serde_derive = "1.0" diff --git a/src/generator.rs b/src/generator.rs index 772e62d..601e7b1 100644 --- a/src/generator.rs +++ b/src/generator.rs @@ -42,8 +42,7 @@ impl Generator { /// assert!(ulid1 < ulid2); /// ``` pub fn generate(&mut self) -> Result { - let now = SystemTime::now(); - self.generate_from_datetime(now) + self.generate_from_datetime(crate::time_utils::now()) } /// Generate a new Ulid matching the given DateTime. @@ -91,8 +90,7 @@ impl Generator { where R: rand::Rng + ?Sized, { - let now = SystemTime::now(); - self.generate_from_datetime_with_source(now, source) + self.generate_from_datetime_with_source(crate::time_utils::now(), source) } /// Generate a new monotonic increasing Ulid with the given source matching the given DateTime diff --git a/src/lib.rs b/src/lib.rs index 83878ba..bf29d3d 100755 --- a/src/lib.rs +++ b/src/lib.rs @@ -44,6 +44,8 @@ mod postgres; pub mod serde; #[cfg(feature = "std")] mod time; +#[cfg(feature = "std")] +mod time_utils; #[cfg(feature = "uuid")] mod uuid; diff --git a/src/time.rs b/src/time.rs index 9f736ac..b1a1d23 100644 --- a/src/time.rs +++ b/src/time.rs @@ -11,7 +11,7 @@ impl Ulid { /// let my_ulid = Ulid::new(); /// ``` pub fn new() -> Ulid { - Ulid::from_datetime(SystemTime::now()) + Ulid::from_datetime(crate::time_utils::now()) } /// Creates a new Ulid using data from the given random number generator @@ -25,7 +25,7 @@ impl Ulid { /// let ulid = Ulid::with_source(&mut rng); /// ``` pub fn with_source(source: &mut R) -> Ulid { - Ulid::from_datetime_with_source(SystemTime::now(), source) + Ulid::from_datetime_with_source(crate::time_utils::now(), source) } /// Creates a new Ulid with the given datetime diff --git a/src/time_utils.rs b/src/time_utils.rs new file mode 100644 index 0000000..77c2cc8 --- /dev/null +++ b/src/time_utils.rs @@ -0,0 +1,9 @@ +pub(crate) fn now() -> std::time::SystemTime { + #[cfg(target_arch = "wasm32")] + { + use web_time::web::SystemTimeExt; + return web_time::SystemTime::now().to_std(); + } + #[cfg(not(target_arch = "wasm32"))] + return std::time::SystemTime::now(); +}