web-time-1.1.0/.cargo_vcs_info.json0000644000000001360000000000100125440ustar { "git": { "sha1": "2d200ded30bbcab66f6a4bfa277ac546685728db" }, "path_in_vcs": "" }web-time-1.1.0/CHANGELOG.md000064400000000000000000000034601046102023000131500ustar 00000000000000# Changelog All notable changes to this project will be documented in this file. The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/), and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). ## [1.1.0] - 2024-03-01 ### Added - Add Serde de/serialization support for `SystemTime` through a `serde` crate feature. ## [1.0.0] - 2024-01-14 ### Added - V1 release. ## [0.2.4] - 2023-12-24 ### Added - Added `web` module containing a platform-specific extension trait to `SystemTime`, allowing conversion from and to `std::time::SystemTime`. ### Changed - Improve performance of `SystemTime` by using `Duration` internally. ## [0.2.3] - 2023-10-23 ### Changed - Improve accuracy of `Instant::now()`. ## [0.2.2] - 2023-10-08 ### Fixed - Time conversion for `Instant`. ## [0.2.1] - 2023-10-07 [YANKED] ### Changed - Bump MSRV to v1.60. ### Removed - Unnecessary `once_cell` dependency. ## [0.2.0] - 2023-03-28 ### Added - Export [`TryFromFloatSecsError`] without breaking MSRV. [`TryFromFloatSecsError`]: https://doc.rust-lang.org/std/time/struct.TryFromFloatSecsError.html ## [0.1.0] - 2023-03-27 ### Added - Initial commit. [Unreleased]: https://github.com/daxpedda/web-time/compare/v1.1.0...HEAD [1.1.0]: https://github.com/daxpedda/web-time/compare/v1.0.0...v1.1.0 [1.0.0]: https://github.com/daxpedda/web-time/compare/v0.2.4...v1.0.0 [0.2.4]: https://github.com/daxpedda/web-time/compare/v0.2.3...v0.2.4 [0.2.3]: https://github.com/daxpedda/web-time/compare/v0.2.2...v0.2.3 [0.2.2]: https://github.com/daxpedda/web-time/compare/v0.2.1...v0.2.2 [0.2.1]: https://github.com/daxpedda/web-time/compare/v0.2.0...v0.2.1 [0.2.0]: https://github.com/daxpedda/web-time/compare/v0.1.0...v0.2.0 [0.1.0]: https://github.com/daxpedda/web-time/releases/tag/v0.1.0 web-time-1.1.0/Cargo.lock0000644000000236460000000000100105320ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "bumpalo" version = "3.15.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ea184aa71bb362a1157c896979544cc23974e08fd265f29ea96b59f0b4a555b" [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "console_error_panic_hook" version = "0.1.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a06aeb73f470f66dcdbf7223caeebb85984942f22f1adb2a088cf9668146bbbc" dependencies = [ "cfg-if", "wasm-bindgen", ] [[package]] name = "futures-channel" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eac8f7d7865dcb88bd4373ab671c8cf4508703796caa2b1985a9ca867b3fcb78" dependencies = [ "futures-core", ] [[package]] name = "futures-core" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dfc6580bb841c5a68e9ef15c77ccc837b40a7504914d52e47b8b0e9bbda25a1d" [[package]] name = "futures-task" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38d84fa142264698cdce1a9f9172cf383a0c82de1bddcf3092901442c4097004" [[package]] name = "futures-util" version = "0.3.30" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3d6401deb83407ab3da39eba7e33987a73c3df0c82b4bb5813ee871c19c41d48" dependencies = [ "futures-core", "futures-task", "pin-project-lite", "pin-utils", ] [[package]] name = "getrandom" version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5" dependencies = [ "cfg-if", "js-sys", "libc", "wasi", "wasm-bindgen", ] [[package]] name = "itoa" version = "1.0.10" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c" [[package]] name = "js-sys" version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "406cda4b368d531c842222cf9d2600a9a4acce8d29423695379c6868a143a9ee" dependencies = [ "wasm-bindgen", ] [[package]] name = "libc" version = "0.2.153" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c198f91728a82281a64e1f4f9eeb25d82cb32a5de251c6bd1b5154d63a8e7bd" [[package]] name = "log" version = "0.4.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f" [[package]] name = "once_cell" version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92" [[package]] name = "pin-project-lite" version = "0.2.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8afb450f006bf6385ca15ef45d71d2288452bc3683ce2e2cacc0d18e4be60b58" [[package]] name = "pin-utils" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8b870d8c151b6f2fb93e84a13146138f05d02ed11c7e7c54f8826aaaf7c9f184" [[package]] name = "pollster" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "22686f4785f02a4fcc856d3b3bb19bf6c8160d103f7a99cc258bddd0251dc7f2" dependencies = [ "pollster-macro", ] [[package]] name = "pollster-macro" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ea78f0ef4193055a4b09814ce6bcb572ad1174d6023e2f00a9ea1a798d18d301" dependencies = [ "proc-macro2", "quote", "syn 1.0.109", ] [[package]] name = "ppv-lite86" version = "0.2.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de" [[package]] name = "proc-macro2" version = "1.0.78" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e2422ad645d89c99f8f3e6b88a9fdeca7fabeac836b1002371c4367c8f984aae" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.35" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "291ec9ab5efd934aaf503a6466c5d5251535d108ee747472c3977cc5acc868ef" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.8.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404" dependencies = [ "libc", "rand_chacha", "rand_core", ] [[package]] name = "rand_chacha" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.6.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" dependencies = [ "getrandom", ] [[package]] name = "ryu" version = "1.0.17" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1" [[package]] name = "scoped-tls" version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e1cf6437eb19a8f4a6cc0f7dca544973b0b78843adbfeb3683d1a94a0024a294" [[package]] name = "serde" version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3fb1c873e1b9b056a4dc4c0c198b24c3ffa059243875552b2bd0933b1aee4ce2" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.197" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7eb0b34b42edc17f6b7cac84a52a1c5f0e1bb2227e997ca9011ea3dd34e8610b" dependencies = [ "proc-macro2", "quote", "syn 2.0.51", ] [[package]] name = "serde_json" version = "1.0.114" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c5f09b1bd632ef549eaa9f60a1f8de742bdbc698e6cee2095fc84dde5f549ae0" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "static_assertions" version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2eb9349b6444b326872e140eb1cf5e7c522154d69e7a0ffb0fb81c06b37543f" [[package]] name = "syn" version = "1.0.109" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "syn" version = "2.0.51" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6ab617d94515e94ae53b8406c628598680aa0c9587474ecbe58188f7b345d66c" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "unicode-ident" version = "1.0.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" [[package]] name = "wasi" version = "0.11.0+wasi-snapshot-preview1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423" [[package]] name = "wasm-bindgen" version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c1e124130aee3fb58c5bdd6b639a0509486b0338acaaae0c84a5124b0f588b7f" dependencies = [ "cfg-if", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c9e7e1900c352b609c8488ad12639a311045f40a35491fb69ba8c12f758af70b" dependencies = [ "bumpalo", "log", "once_cell", "proc-macro2", "quote", "syn 2.0.51", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-futures" version = "0.4.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "877b9c3f61ceea0e56331985743b13f3d25c406a7098d45180fb5f09bc19ed97" dependencies = [ "cfg-if", "js-sys", "wasm-bindgen", "web-sys", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b30af9e2d358182b5c7449424f017eba305ed32a7010509ede96cdc4696c46ed" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "642f325be6301eb8107a83d12a8ac6c1e1c54345a7ef1a9261962dfefda09e66" dependencies = [ "proc-macro2", "quote", "syn 2.0.51", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.91" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f186bd2dcf04330886ce82d6f33dd75a7bfcf69ecf5763b89fcde53b6ac9838" [[package]] name = "wasm-bindgen-test" version = "0.3.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "143ddeb4f833e2ed0d252e618986e18bfc7b0e52f2d28d77d05b2f045dd8eb61" dependencies = [ "console_error_panic_hook", "js-sys", "scoped-tls", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test-macro", ] [[package]] name = "wasm-bindgen-test-macro" version = "0.3.41" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a5211b7550606857312bba1d978a8ec75692eae187becc5e680444fffc5e6f89" dependencies = [ "proc-macro2", "quote", "syn 2.0.51", ] [[package]] name = "web-sys" version = "0.3.68" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "96565907687f7aceb35bc5fc03770a8a0471d82e479f25832f54a0e3f4b28446" dependencies = [ "js-sys", "wasm-bindgen", ] [[package]] name = "web-time" version = "1.1.0" dependencies = [ "futures-channel", "futures-util", "getrandom", "js-sys", "pollster", "rand", "serde", "serde_json", "static_assertions", "wasm-bindgen", "wasm-bindgen-futures", "wasm-bindgen-test", "web-sys", ] web-time-1.1.0/Cargo.toml0000644000000136200000000000100105440ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.60" name = "web-time" version = "1.1.0" include = [ "CHANGELOG.md", "LICENSE-*", "src/**/*", ] autobenches = false description = "Drop-in replacement for std::time for Wasm in browsers" readme = "README.md" keywords = [ "instant", "wasm", "web", "systemtime", "time", ] categories = [ "api-bindings", "date-and-time", "wasm", ] license = "MIT OR Apache-2.0" repository = "https://github.com/daxpedda/web-time" [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg=docsrs"] targets = ["wasm32-unknown-unknown"] [profile.bench] lto = true codegen-units = 1 [[example]] name = "benchmark" path = "benches/benchmark.rs" [[test]] name = "serde" path = "tests/serde.rs" required-features = ["serde"] [dev-dependencies.static_assertions] version = "1" [features] serde = ["dep:serde"] [target."cfg(all(target_family = \"wasm\", target_feature = \"atomics\"))".dev-dependencies.futures-channel] version = "0.3" features = ["alloc"] default-features = false [target."cfg(all(target_family = \"wasm\", target_feature = \"atomics\"))".dev-dependencies.futures-util] version = "0.3" default-features = false [target."cfg(all(target_family = \"wasm\", target_feature = \"atomics\"))".dev-dependencies.web-sys] version = "0.3" features = ["WorkerGlobalScope"] [target."cfg(all(target_family = \"wasm\", target_os = \"unknown\"))".dependencies.js-sys] version = "0.3.20" [target."cfg(all(target_family = \"wasm\", target_os = \"unknown\"))".dependencies.serde] version = "1" optional = true [target."cfg(all(target_family = \"wasm\", target_os = \"unknown\"))".dependencies.wasm-bindgen] version = "0.2.70" default-features = false [target."cfg(not(target_family = \"wasm\"))".dev-dependencies.pollster] version = "0.3" features = ["macro"] [target."cfg(target_family = \"wasm\")".dev-dependencies.getrandom] version = "0.2" features = ["js"] [target."cfg(target_family = \"wasm\")".dev-dependencies.rand] version = "0.8" [target."cfg(target_family = \"wasm\")".dev-dependencies.serde_json] version = "1" [target."cfg(target_family = \"wasm\")".dev-dependencies.wasm-bindgen-futures] version = "0.4" [target."cfg(target_family = \"wasm\")".dev-dependencies.wasm-bindgen-test] version = "0.3" [target."cfg(target_family = \"wasm\")".dev-dependencies.web-sys] version = "0.3" features = [ "CssStyleDeclaration", "Document", "Element", "HtmlTableElement", "HtmlTableRowElement", "Performance", "Window", ] [lints.clippy] absolute_paths = "warn" allow_attributes = "warn" allow_attributes_without_reason = "warn" as_conversions = "warn" assertions_on_result_states = "warn" clone_on_ref_ptr = "warn" create_dir = "warn" dbg_macro = "warn" decimal_literal_representation = "warn" default_union_representation = "warn" empty_drop = "warn" empty_structs_with_brackets = "warn" equatable_if_let = "allow" error_impl_error = "warn" exit = "warn" explicit_deref_methods = "allow" filetype_is_file = "warn" float_cmp_const = "warn" fn_to_numeric_cast_any = "warn" format_push_string = "warn" future_not_send = "allow" get_unwrap = "warn" if_then_some_else_none = "warn" impl_trait_in_params = "warn" indexing_slicing = "warn" infinite_loop = "warn" large_include_file = "warn" lossy_float_literal = "warn" min_ident_chars = "warn" missing_assert_message = "warn" missing_asserts_for_indexing = "warn" missing_docs_in_private_items = "warn" mixed_read_write_in_expression = "warn" module_inception = "allow" module_name_repetitions = "allow" mutex_atomic = "warn" non_ascii_literal = "warn" option_if_let_else = "allow" partial_pub_fields = "warn" print_stderr = "warn" print_stdout = "warn" pub_without_shorthand = "warn" rc_buffer = "warn" rc_mutex = "warn" redundant_pub_crate = "allow" redundant_type_annotations = "warn" ref_patterns = "warn" rest_pat_in_fully_bound_structs = "warn" same_name_method = "warn" self_named_module_files = "warn" semicolon_outside_block = "warn" single_char_lifetime_names = "warn" str_to_string = "warn" string_add = "warn" string_lit_chars_any = "warn" string_slice = "warn" string_to_string = "warn" suspicious_xor_used_as_pow = "warn" tabs_in_doc_comments = "allow" todo = "warn" try_err = "warn" undocumented_unsafe_blocks = "warn" unimplemented = "warn" unnecessary_safety_doc = "warn" unnecessary_self_imports = "warn" unneeded_field_pattern = "warn" unseparated_literal_suffix = "warn" unwrap_used = "warn" use_debug = "warn" verbose_file_reads = "warn" [lints.clippy.cargo] level = "warn" priority = -1 [lints.clippy.nursery] level = "warn" priority = -1 [lints.clippy.pedantic] level = "warn" priority = -1 [lints.rust] deprecated_in_future = "warn" ffi_unwind_calls = "warn" macro_use_extern_crate = "warn" meta_variable_misuse = "warn" missing_abi = "warn" missing_copy_implementations = "warn" missing_debug_implementations = "warn" missing_docs = "warn" non_ascii_idents = "warn" single_use_lifetimes = "warn" trivial_casts = "warn" trivial_numeric_casts = "warn" unreachable_pub = "warn" unsafe_code = "deny" unsafe_op_in_unsafe_fn = "warn" unused_import_braces = "warn" unused_lifetimes = "warn" unused_qualifications = "warn" [lints.rust.future_incompatible] level = "warn" priority = -1 [lints.rust.rust_2018_compatibility] level = "warn" priority = -1 [lints.rust.rust_2018_idioms] level = "warn" priority = -1 [lints.rust.rust_2021_compatibility] level = "warn" priority = -1 [lints.rust.unused] level = "warn" priority = -1 [lints.rustdoc.all] level = "warn" priority = -1 web-time-1.1.0/Cargo.toml.orig000064400000000000000000000115551046102023000142320ustar 00000000000000[package] autobenches = false categories = ["api-bindings", "date-and-time", "wasm"] description = "Drop-in replacement for std::time for Wasm in browsers" edition = "2021" include = ["CHANGELOG.md", "LICENSE-*", "src/**/*"] keywords = ["instant", "wasm", "web", "systemtime", "time"] license = "MIT OR Apache-2.0" name = "web-time" repository = "https://github.com/daxpedda/web-time" rust-version = "1.60" version = "1.1.0" [features] serde = ["dep:serde"] [target.'cfg(all(target_family = "wasm", target_os = "unknown"))'.dependencies] js-sys = "0.3.20" serde = { version = "1", optional = true } wasm-bindgen = { version = "0.2.70", default-features = false } [dev-dependencies] static_assertions = "1" [target.'cfg(not(target_family = "wasm"))'.dev-dependencies] pollster = { version = "0.3", features = ["macro"] } [target.'cfg(target_family = "wasm")'.dev-dependencies] getrandom = { version = "0.2", features = ["js"] } rand = "0.8" serde_json = "1" wasm-bindgen-futures = "0.4" wasm-bindgen-test = "0.3" web-sys = { version = "0.3", features = [ "CssStyleDeclaration", "Document", "Element", "HtmlTableElement", "HtmlTableRowElement", "Performance", "Window", ] } [target.'cfg(all(target_family = "wasm", target_feature = "atomics"))'.dev-dependencies] futures-channel = { version = "0.3", default-features = false, features = ["alloc"] } futures-util = { version = "0.3", default-features = false } wasm-worker = { git = "https://github.com/daxpedda/wasm-worker", rev = "8b3e6324bdb5d44d5565b6981ce74ee773da9e3f" } web-sys = { version = "0.3", features = ["WorkerGlobalScope"] } [profile.bench] codegen-units = 1 lto = true [[example]] name = "benchmark" path = "benches/benchmark.rs" [[test]] name = "serde" path = "tests/serde.rs" required-features = ["serde"] [package.metadata.docs.rs] all-features = true rustdoc-args = ["--cfg=docsrs"] targets = ["wasm32-unknown-unknown"] [lints.rust] # Rust groups. future_incompatible = { level = "warn", priority = -1 } rust_2018_compatibility = { level = "warn", priority = -1 } rust_2018_idioms = { level = "warn", priority = -1 } rust_2021_compatibility = { level = "warn", priority = -1 } unused = { level = "warn", priority = -1 } # Rust lints. deprecated_in_future = "warn" ffi_unwind_calls = "warn" macro_use_extern_crate = "warn" meta_variable_misuse = "warn" missing_abi = "warn" missing_copy_implementations = "warn" missing_debug_implementations = "warn" missing_docs = "warn" non_ascii_idents = "warn" single_use_lifetimes = "warn" trivial_casts = "warn" trivial_numeric_casts = "warn" unreachable_pub = "warn" unsafe_code = "deny" unsafe_op_in_unsafe_fn = "warn" unused_import_braces = "warn" unused_lifetimes = "warn" unused_qualifications = "warn" [lints.clippy] # Clippy groups. cargo = { level = "warn", priority = -1 } nursery = { level = "warn", priority = -1 } pedantic = { level = "warn", priority = -1 } # Clippy restriction lints. absolute_paths = "warn" allow_attributes = "warn" allow_attributes_without_reason = "warn" as_conversions = "warn" assertions_on_result_states = "warn" clone_on_ref_ptr = "warn" create_dir = "warn" dbg_macro = "warn" decimal_literal_representation = "warn" default_union_representation = "warn" empty_drop = "warn" empty_structs_with_brackets = "warn" error_impl_error = "warn" exit = "warn" filetype_is_file = "warn" float_cmp_const = "warn" fn_to_numeric_cast_any = "warn" format_push_string = "warn" get_unwrap = "warn" if_then_some_else_none = "warn" impl_trait_in_params = "warn" indexing_slicing = "warn" infinite_loop = "warn" large_include_file = "warn" lossy_float_literal = "warn" min_ident_chars = "warn" missing_assert_message = "warn" missing_asserts_for_indexing = "warn" missing_docs_in_private_items = "warn" mixed_read_write_in_expression = "warn" mutex_atomic = "warn" non_ascii_literal = "warn" partial_pub_fields = "warn" print_stderr = "warn" print_stdout = "warn" pub_without_shorthand = "warn" rc_buffer = "warn" rc_mutex = "warn" redundant_type_annotations = "warn" ref_patterns = "warn" rest_pat_in_fully_bound_structs = "warn" same_name_method = "warn" self_named_module_files = "warn" semicolon_outside_block = "warn" single_char_lifetime_names = "warn" str_to_string = "warn" string_add = "warn" string_lit_chars_any = "warn" string_slice = "warn" string_to_string = "warn" suspicious_xor_used_as_pow = "warn" todo = "warn" try_err = "warn" undocumented_unsafe_blocks = "warn" unimplemented = "warn" unnecessary_safety_doc = "warn" unnecessary_self_imports = "warn" unneeded_field_pattern = "warn" unseparated_literal_suffix = "warn" unwrap_used = "warn" use_debug = "warn" verbose_file_reads = "warn" # Allowed Clippy lints. equatable_if_let = "allow" explicit_deref_methods = "allow" future_not_send = "allow" module_inception = "allow" module_name_repetitions = "allow" option_if_let_else = "allow" redundant_pub_crate = "allow" tabs_in_doc_comments = "allow" [lints.rustdoc] all = { level = "warn", priority = -1 } web-time-1.1.0/LICENSE-APACHE000064400000000000000000000261121046102023000132620ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2023 dAxpeDDa Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. web-time-1.1.0/LICENSE-MIT000064400000000000000000000020511046102023000127660ustar 00000000000000MIT License Copyright (c) 2023 dAxpeDDa Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. web-time-1.1.0/README.md000064400000000000000000000127611046102023000126220ustar 00000000000000# web-time [![Crates.io Version](https://img.shields.io/crates/v/web-time.svg)](https://crates.io/crates/web-time) [![Live Build Status](https://img.shields.io/github/checks-status/daxpedda/web-time/main?label=CI)](https://github.com/daxpedda/web-time/actions?query=branch%3Amain) [![Docs.rs Documentation](https://img.shields.io/docsrs/web-time?label=docs.rs)](https://docs.rs/crate/web-time) [![Main Documentation](https://img.shields.io/github/actions/workflow/status/daxpedda/web-time/documentation.yml?branch=main&label=main%20docs )](https://daxpedda.github.io/web-time/web_time/index.html) ## Description Complete drop-in replacement for [`std::time`] that works in browsers. Currently [`Instant::now()`] and [`SystemTime::now()`] will simply panic when using the `wasm32-unknown-unknown` target. This implementation uses [`Performance.now()`] for [`Instant`] and [`Date.now()`] for [`SystemTime`] to offer a drop-in replacement that works in browsers. At the same time the library will simply re-export [`std::time`] when not using the `wasm32-unknown-unknown` target and will not pull in any dependencies. Additionally, if compiled with `target-feature = "atomics"` it will synchronize the timestamps to account for different context's, like web workers. See [`Performance.timeOrigin`] for more information. Using `-Ctarget-feature=+nontrapping-fptoint` will improve the performance of [`Instant::now()`] and [`SystemTime::now()`], but the vast majority of the time is still spent going through JS. ## Target This library specifically targets browsers, that support [`Performance.now()`], with the `wasm32-unknown-unknown` target. Emscripten is not supported. WASI doesn't require support as it has it's own native API to deal with [`std::time`]. Furthermore it depends on [`wasm-bindgen`], which is required. This library will continue to depend on it until a viable alternative presents itself, in which case multiple ecosystems could be supported. ## Note ### Ticking during sleep Currently a known bug is affecting browsers on operating system other then Windows. This bug prevents [`Instant`] from continuing to tick when the context is asleep. This doesn't necessarily conflict with Rusts requirements of [`Instant`], but might still be unexpected. See [the MDN documentation on this](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#ticking_during_sleep) for more information. ### Context support The implementation of [`Instant::now()`] relies on the availability of the [`Performance` object], a lack thereof will cause a panic. This can happen if called from a [worklet]. ## Usage You can simply import the types you need: ```rust use web_time::{Instant, SystemTime}; let now = Instant::now(); let time = SystemTime::now(); ``` ## Features ### `serde` Implements [`serde::Deserialize`] and [`serde::Serialize`] for [`SystemTime`]. ## MSRV As this library heavily relies on [`wasm-bindgen`] the MSRV depends on it. At the point of time this was written the MSRV is 1.60. ## Alternatives [instant](https://crates.io/crates/instant) [![Crates.io](https://img.shields.io/crates/v/instant.svg)](https://crates.io/crates/instant) is a popular alternative! However the API it implements doesn't match [`std::time`] exactly. ## Changelog See the [CHANGELOG] file for details. ## Contributing See the [CONTRIBUTING] file for details. ## Attribution Inspiration was taken from the [instant](https://github.com/sebcrozet/instant/tree/v0.1.12) project. Additional insight was taken from the [time](https://github.com/time-rs/time/tree/v0.3.20) project. ## License Licensed under either of - Apache License, Version 2.0 ([LICENSE-APACHE] or ) - MIT license ([LICENSE-MIT] or ) at your option. ### Copyright A majority of the code and documentation was taken from [`std::time`]. For license information see [#License](https://github.com/rust-lang/rust/tree/1.68.1#license). ### Contribution Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. [CHANGELOG]: https://github.com/daxpedda/web-time/blob/v1.1.0/CHANGELOG.md [CONTRIBUTING]: https://github.com/daxpedda/web-time/blob/v1.1.0/CONTRIBUTING.md [LICENSE-MIT]: https://github.com/daxpedda/web-time/blob/v1.1.0/LICENSE-MIT [LICENSE-APACHE]: https://github.com/daxpedda/web-time/blob/v1.1.0/LICENSE-APACHE [worklet]: https://developer.mozilla.org/en-US/docs/Web/API/Worklet [`Date.now()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html [`Instant::now()`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now [`SystemTime`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html [`SystemTime::now()`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.now [`std::time`]: https://doc.rust-lang.org/stable/std/time/ [`performance.now()`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now [`Performance.timeOrigin`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin [`Performance` object]: https://developer.mozilla.org/en-US/docs/Web/API/performance_property [`serde::Deserialize`]: https://docs.rs/serde/1/serde/trait.Deserialize.html [`serde::Serialize`]: https://docs.rs/serde/1/serde/trait.Serialize.html [`wasm-bindgen`]: https://crates.io/crates/wasm-bindgen web-time-1.1.0/src/lib.rs000064400000000000000000000135041046102023000132420ustar 00000000000000//! # Description //! //! Complete drop-in replacement for [`std::time`] that works in browsers. //! //! Currently [`Instant::now()`] and [`SystemTime::now()`] will simply panic //! when using the `wasm32-unknown-unknown` target. This implementation uses //! [`Performance.now()`] for [`Instant`] and [`Date.now()`] for [`SystemTime`] //! to offer a drop-in replacement that works in browsers. //! //! At the same time the library will simply re-export [`std::time`] when not //! using the `wasm32-unknown-unknown` target and will not pull in any //! dependencies. //! //! Additionally, if compiled with `target-feature = "atomics"` it will //! synchronize the timestamps to account for different context's, like web //! workers. See [`Performance.timeOrigin`] for more information. //! //! Using `-Ctarget-feature=+nontrapping-fptoint` will improve the performance //! of [`Instant::now()`] and [`SystemTime::now()`], but the vast majority of //! the time is still spent going through JS. //! //! # Target //! //! This library specifically targets browsers, that support //! [`Performance.now()`], with the `wasm32-unknown-unknown` target. Emscripten //! is not supported. WASI doesn't require support as it has it's own native API //! to deal with [`std::time`]. //! //! Furthermore it depends on [`wasm-bindgen`], which is required. This library //! will continue to depend on it until a viable alternative presents itself, in //! which case multiple ecosystems could be supported. //! //! # Note //! //! ## Ticking during sleep //! //! Currently a known bug is affecting browsers on operating system other then //! Windows. This bug prevents [`Instant`] from continuing to tick when the //! context is asleep. This doesn't necessarily conflict with Rusts requirements //! of [`Instant`], but might still be unexpected. //! //! See [the MDN documentation on this](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now#ticking_during_sleep) for more information. //! //! ## Context support //! //! The implementation of [`Instant::now()`] relies on the availability of the //! [`Performance` object], a lack thereof will cause a panic. This can happen //! if called from a [worklet]. //! //! # Usage //! //! You can simply import the types you need: //! ```rust //! use web_time::{Instant, SystemTime}; //! //! let now = Instant::now(); //! let time = SystemTime::now(); //! ``` //! //! # Features //! //! ## `serde` //! //! Implements [`serde::Deserialize`] and [`serde::Serialize`] for //! [`SystemTime`]. //! //! # MSRV //! //! As this library heavily relies on [`wasm-bindgen`] the MSRV depends on it. //! At the point of time this was written the MSRV is 1.60. //! //! # Alternatives //! //! [instant](https://crates.io/crates/instant) [![Crates.io](https://img.shields.io/crates/v/instant.svg)](https://crates.io/crates/instant) is a popular alternative! However the API it implements doesn't match [`std::time`] exactly. //! //! # Contributing //! //! See the [CONTRIBUTING] file for details. //! //! # Attribution //! //! Inspiration was taken from the [instant](https://github.com/sebcrozet/instant/tree/v0.1.12) project. //! //! Additional insight was taken from the [time](https://github.com/time-rs/time/tree/v0.3.20) project. //! //! # Changelog //! //! See the [CHANGELOG] file for details. //! //! # License //! //! Licensed under either of //! //! - Apache License, Version 2.0 ([LICENSE-APACHE] or ) //! - MIT license ([LICENSE-MIT] or ) //! //! at your option. //! //! ## Copyright //! //! A majority of the code and documentation was taken from [`std::time`]. For //! license information see [#License](https://github.com/rust-lang/rust/tree/1.68.1#license). //! //! ## Contribution //! //! Unless you explicitly state otherwise, any contribution intentionally //! submitted for inclusion in the work by you, as defined in the Apache-2.0 //! license, shall be dual licensed as above, without any additional terms or //! conditions. //! //! [CHANGELOG]: https://github.com/daxpedda/web-time/blob/v1.1.0/CHANGELOG.md //! [CONTRIBUTING]: https://github.com/daxpedda/web-time/blob/v1.1.0/CONTRIBUTING.md //! [LICENSE-MIT]: https://github.com/daxpedda/web-time/blob/v1.1.0/LICENSE-MIT //! [LICENSE-APACHE]: https://github.com/daxpedda/web-time/blob/v1.1.0/LICENSE-APACHE //! [worklet]: https://developer.mozilla.org/en-US/docs/Web/API/Worklet //! [`Date.now()`]: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/now //! [`Instant`]: https://doc.rust-lang.org/std/time/struct.Instant.html //! [`Instant::now()`]: https://doc.rust-lang.org/std/time/struct.Instant.html#method.now //! [`SystemTime`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html //! [`SystemTime::now()`]: https://doc.rust-lang.org/std/time/struct.SystemTime.html#method.now //! [`std::time`]: https://doc.rust-lang.org/stable/std/time/ //! [`performance.now()`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/now //! [`Performance.timeOrigin`]: https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin //! [`Performance` object]: https://developer.mozilla.org/en-US/docs/Web/API/performance_property #![cfg_attr( any(not(feature = "serde"), not(target_family = "wasm")), doc = "[`serde::Deserialize`]: https://docs.rs/serde/1/serde/trait.Deserialize.html", doc = "[`serde::Serialize`]: https://docs.rs/serde/1/serde/trait.Serialize.html" )] //! [`wasm-bindgen`]: https://crates.io/crates/wasm-bindgen #![cfg_attr(docsrs, feature(doc_cfg))] #[cfg(all(target_family = "wasm", target_os = "unknown"))] mod time; #[cfg(any(all(target_family = "wasm", target_os = "unknown"), docsrs))] #[cfg_attr(docsrs, doc(cfg(Web)))] pub mod web; #[cfg(not(all(target_family = "wasm", target_os = "unknown")))] pub use std::time::*; #[cfg(all(target_family = "wasm", target_os = "unknown"))] pub use self::time::*; web-time-1.1.0/src/time/instant.rs000064400000000000000000000162401046102023000151120ustar 00000000000000//! Re-implementation of [`std::time::Instant`]. use std::ops::{Add, AddAssign, Sub, SubAssign}; use std::time::Duration; use super::js::PERFORMANCE; #[cfg(target_feature = "atomics")] thread_local! { static ORIGIN: f64 = PERFORMANCE.with(super::js::Performance::time_origin); } /// See [`std::time::Instant`]. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct Instant(Duration); impl Instant { /// See [`std::time::Instant::now()`]. /// /// # Panics /// /// This call will panic if the [`Performance` object] was not found, e.g. /// calling from a [worklet]. /// /// [`Performance` object]: https://developer.mozilla.org/en-US/docs/Web/API/performance_property /// [worklet]: https://developer.mozilla.org/en-US/docs/Web/API/Worklet #[must_use] pub fn now() -> Self { let now = PERFORMANCE.with(|performance| { #[cfg(target_feature = "atomics")] return ORIGIN.with(|origin| performance.now() + origin); #[cfg(not(target_feature = "atomics"))] performance.now() }); Self(time_stamp_to_duration(now)) } /// See [`std::time::Instant::duration_since()`]. #[must_use] pub fn duration_since(&self, earlier: Self) -> Duration { self.checked_duration_since(earlier).unwrap_or_default() } /// See [`std::time::Instant::checked_duration_since()`]. #[must_use] #[allow(clippy::missing_const_for_fn)] pub fn checked_duration_since(&self, earlier: Self) -> Option { self.0.checked_sub(earlier.0) } /// See [`std::time::Instant::saturating_duration_since()`]. #[must_use] pub fn saturating_duration_since(&self, earlier: Self) -> Duration { self.checked_duration_since(earlier).unwrap_or_default() } /// See [`std::time::Instant::elapsed()`]. #[must_use] pub fn elapsed(&self) -> Duration { Self::now() - *self } /// See [`std::time::Instant::checked_add()`]. pub fn checked_add(&self, duration: Duration) -> Option { self.0.checked_add(duration).map(Instant) } /// See [`std::time::Instant::checked_sub()`]. pub fn checked_sub(&self, duration: Duration) -> Option { self.0.checked_sub(duration).map(Instant) } } impl Add for Instant { type Output = Self; /// # Panics /// /// This function may panic if the resulting point in time cannot be /// represented by the underlying data structure. See /// [`Instant::checked_add`] for a version without panic. fn add(self, other: Duration) -> Self { self.checked_add(other) .expect("overflow when adding duration to instant") } } impl AddAssign for Instant { fn add_assign(&mut self, other: Duration) { *self = *self + other; } } impl Sub for Instant { type Output = Self; fn sub(self, other: Duration) -> Self { self.checked_sub(other) .expect("overflow when subtracting duration from instant") } } impl Sub for Instant { type Output = Duration; /// Returns the amount of time elapsed from another instant to this one, /// or zero duration if that instant is later than this one. fn sub(self, other: Self) -> Duration { self.duration_since(other) } } impl SubAssign for Instant { fn sub_assign(&mut self, other: Duration) { *self = *self - other; } } /// Converts a `DOMHighResTimeStamp` to a [`Duration`]. /// /// # Note /// /// Keep in mind that like [`Duration::from_secs_f64()`] this doesn't do perfect /// rounding. #[allow( clippy::as_conversions, clippy::cast_possible_truncation, clippy::cast_sign_loss )] fn time_stamp_to_duration(time_stamp: f64) -> Duration { Duration::from_millis(time_stamp.trunc() as u64) + Duration::from_nanos((time_stamp.fract() * 1.0e6).round() as u64) } #[cfg(test)] mod test { use std::time::Duration; use rand::distributions::Uniform; use rand::Rng; use wasm_bindgen_test::wasm_bindgen_test; wasm_bindgen_test::wasm_bindgen_test_configure!(run_in_browser); // According to . const MAXIMUM_ACCURATE_SECS: u64 = 285_616 * 365 * 24 * 60 * 60; #[allow(clippy::as_conversions, clippy::cast_precision_loss)] const MAXIMUM_ACCURATE_MILLIS: f64 = MAXIMUM_ACCURATE_SECS as f64 * 1_000.; #[derive(Debug)] struct ControlDuration(Duration); impl ControlDuration { fn new(time_stamp: f64) -> Self { // See . let time_stamp = Duration::from_secs_f64(time_stamp); let secs = time_stamp.as_secs() / 1000; let carry = time_stamp.as_secs() - secs * 1000; #[allow(clippy::as_conversions, clippy::cast_possible_truncation)] let extra_nanos = (carry * 1_000_000_000 / 1000) as u32; // CHANGED: Added rounding. let nanos = time_stamp.subsec_micros() + u32::from(time_stamp.subsec_nanos() % 1000 > 499) + extra_nanos; // CHANGED: Removed check that would fail because of the additional time added // by rounding. Self(Duration::new(secs, nanos)) } } impl PartialEq for ControlDuration { fn eq(&self, duration: &Duration) -> bool { // Our control `Duration` has perfect accuracy, unlike // [`super::time_stamp_to_duration()`]. if self.0 == *duration { true } else if let Some(diff) = self.0.checked_sub(*duration) { diff == Duration::from_nanos(1) } else { false } } } #[wasm_bindgen_test] fn sanity() { #[track_caller] fn assert(time_stamp: f64, result: Duration) { let control = ControlDuration::new(time_stamp); let duration = super::time_stamp_to_duration(time_stamp); assert_eq!(control, result, "control and expected result are different"); assert_eq!(control, duration); } assert(0.000_000, Duration::ZERO); assert(0.000_000_4, Duration::ZERO); assert(0.000_000_5, Duration::from_nanos(1)); assert(0.000_001, Duration::from_nanos(1)); assert(0.000_001_4, Duration::from_nanos(1)); assert(0.000_001_5, Duration::from_nanos(2)); assert(0.999_999, Duration::from_nanos(999_999)); assert(0.999_999_4, Duration::from_nanos(999_999)); assert(0.999_999_5, Duration::from_millis(1)); assert(1., Duration::from_millis(1)); assert(1.000_000_4, Duration::from_millis(1)); assert(1.000_000_5, Duration::from_nanos(1_000_001)); assert(1.000_001, Duration::from_nanos(1_000_001)); assert(1.000_001_4, Duration::from_nanos(1_000_001)); assert(1.000_001_5, Duration::from_nanos(1_000_002)); assert(999.999_999, Duration::from_nanos(999_999_999)); assert(999.999_999_4, Duration::from_nanos(999_999_999)); assert(999.999_999_5, Duration::from_secs(1)); assert(1000., Duration::from_secs(1)); assert(1_000.000_000_4, Duration::from_secs(1)); assert(1_000.000_000_5, Duration::from_nanos(1_000_000_001)); assert(1_000.000_001, Duration::from_nanos(1_000_000_001)); assert(1_000.000_001_4, Duration::from_nanos(1_000_000_001)); assert(1_000.000_001_5, Duration::from_nanos(1_000_000_002)); assert( MAXIMUM_ACCURATE_MILLIS, Duration::from_secs(MAXIMUM_ACCURATE_SECS), ); } #[wasm_bindgen_test] fn fuzzing() { let mut random = rand::thread_rng().sample_iter(Uniform::new_inclusive(0., MAXIMUM_ACCURATE_MILLIS)); for _ in 0..10_000_000 { let time_stamp = random.next().unwrap(); let control = ControlDuration::new(time_stamp); let duration = super::time_stamp_to_duration(time_stamp); assert_eq!(control, duration); } } } web-time-1.1.0/src/time/js.rs000064400000000000000000000024331046102023000140450ustar 00000000000000//! Bindings to the JS API. use wasm_bindgen::prelude::wasm_bindgen; use wasm_bindgen::{JsCast, JsValue}; #[wasm_bindgen] extern "C" { /// Type for the [global object](https://developer.mozilla.org/en-US/docs/Glossary/Global_object). type Global; /// Returns the [`Performance`](https://developer.mozilla.org/en-US/docs/Web/API/Performance) object. #[wasm_bindgen(method, getter)] fn performance(this: &Global) -> JsValue; /// Type for the [`Performance` object](https://developer.mozilla.org/en-US/docs/Web/API/Performance). pub(super) type Performance; /// Binding to [`Performance.now()`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/now). #[wasm_bindgen(method)] pub(super) fn now(this: &Performance) -> f64; /// Binding to [`Performance.timeOrigin`](https://developer.mozilla.org/en-US/docs/Web/API/Performance/timeOrigin). #[cfg(target_feature = "atomics")] #[wasm_bindgen(method, getter, js_name = timeOrigin)] pub(super) fn time_origin(this: &Performance) -> f64; } thread_local! { pub(super) static PERFORMANCE: Performance = { let global: Global = js_sys::global().unchecked_into(); let performance = global.performance(); if performance.is_undefined() { panic!("`Performance` object not found") } else { performance.unchecked_into() } }; } web-time-1.1.0/src/time/mod.rs000064400000000000000000000005051046102023000142060ustar 00000000000000//! Re-implementation of [`std::time`]. mod instant; mod js; #[cfg(feature = "serde")] mod serde; mod system_time; pub use std::time::*; pub use self::instant::Instant; pub use self::system_time::{SystemTime, SystemTimeError}; /// See [`std::time::UNIX_EPOCH`]. pub const UNIX_EPOCH: SystemTime = SystemTime::UNIX_EPOCH; web-time-1.1.0/src/time/serde.rs000064400000000000000000000114071046102023000145340ustar 00000000000000//! Serde serialization and de-serialization for `SystemTime`. It aims to be //! compatible with Serde's implementation for [`std::time::SystemTime`]. //! //! This implementation was copied from Serde's //! [`Deserialize`](https://github.com/serde-rs/serde/blob/5fa711d75d91173aafc6019e03cf8af6ac9ba7b2/serde/src/de/impls.rs#L2168-L2314), //! and //! [`Sserialize`](https://github.com/serde-rs/serde/blob/5fa711d75d91173aafc6019e03cf8af6ac9ba7b2/serde/src/ser/impls.rs#L730-L747) //! implementation. #![allow(warnings)] // CHANGED: Replaced occurrences of `tri!` macro with `?`. use std::fmt; use std::time::Duration; use serde::de::{Error, MapAccess, SeqAccess, Visitor}; use serde::{Deserialize, Deserializer, Serialize, Serializer}; use super::SystemTime; impl<'de> Deserialize<'de> for SystemTime { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { // Reuse duration enum Field { Secs, Nanos, } impl<'de> Deserialize<'de> for Field { fn deserialize(deserializer: D) -> Result where D: Deserializer<'de>, { struct FieldVisitor; impl<'de> Visitor<'de> for FieldVisitor { type Value = Field; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("`secs_since_epoch` or `nanos_since_epoch`") } fn visit_str(self, value: &str) -> Result where E: Error, { match value { "secs_since_epoch" => Ok(Field::Secs), "nanos_since_epoch" => Ok(Field::Nanos), _ => Err(Error::unknown_field(value, FIELDS)), } } fn visit_bytes(self, value: &[u8]) -> Result where E: Error, { match value { b"secs_since_epoch" => Ok(Field::Secs), b"nanos_since_epoch" => Ok(Field::Nanos), _ => { let value = String::from_utf8_lossy(value); Err(Error::unknown_field(&value, FIELDS)) } } } } deserializer.deserialize_identifier(FieldVisitor) } } fn check_overflow(secs: u64, nanos: u32) -> Result<(), E> where E: Error, { static NANOS_PER_SEC: u32 = 1_000_000_000; match secs.checked_add((nanos / NANOS_PER_SEC) as u64) { Some(_) => Ok(()), None => Err(E::custom("overflow deserializing SystemTime epoch offset")), } } struct DurationVisitor; impl<'de> Visitor<'de> for DurationVisitor { type Value = Duration; fn expecting(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result { formatter.write_str("struct SystemTime") } fn visit_seq(self, mut seq: A) -> Result where A: SeqAccess<'de>, { let secs: u64 = match seq.next_element()? { Some(value) => value, None => { return Err(Error::invalid_length(0, &self)); } }; let nanos: u32 = match seq.next_element()? { Some(value) => value, None => { return Err(Error::invalid_length(1, &self)); } }; check_overflow(secs, nanos)?; Ok(Duration::new(secs, nanos)) } fn visit_map(self, mut map: A) -> Result where A: MapAccess<'de>, { let mut secs: Option = None; let mut nanos: Option = None; while let Some(key) = map.next_key()? { match key { Field::Secs => { if secs.is_some() { return Err(::duplicate_field( "secs_since_epoch", )); } secs = Some(map.next_value()?); } Field::Nanos => { if nanos.is_some() { return Err(::duplicate_field( "nanos_since_epoch", )); } nanos = Some(map.next_value()?); } } } let secs = match secs { Some(secs) => secs, None => return Err(::missing_field("secs_since_epoch")), }; let nanos = match nanos { Some(nanos) => nanos, None => return Err(::missing_field("nanos_since_epoch")), }; check_overflow(secs, nanos)?; Ok(Duration::new(secs, nanos)) } } const FIELDS: &[&str] = &["secs_since_epoch", "nanos_since_epoch"]; let duration = deserializer.deserialize_struct("SystemTime", FIELDS, DurationVisitor)?; // CHANGED: Insert `Duration` directly. let ret = Ok(Self(duration)); ret } } impl Serialize for SystemTime { fn serialize(&self, serializer: S) -> Result where S: Serializer, { use serde::ser::SerializeStruct; // CHANGED: Take `Duration` directly. let duration_since_epoch = self.0; let mut state = serializer.serialize_struct("SystemTime", 2)?; state.serialize_field("secs_since_epoch", &duration_since_epoch.as_secs())?; state.serialize_field("nanos_since_epoch", &duration_since_epoch.subsec_nanos())?; state.end() } } web-time-1.1.0/src/time/system_time.rs000064400000000000000000000060361046102023000157760ustar 00000000000000//! Re-implementation of [`std::time::SystemTime`]. use std::error::Error; use std::fmt::{self, Display, Formatter}; use std::ops::{Add, AddAssign, Sub, SubAssign}; use std::time::Duration; /// See [`std::time::SystemTime`]. #[derive(Clone, Copy, Debug, Eq, Hash, Ord, PartialEq, PartialOrd)] pub struct SystemTime(pub(crate) Duration); impl SystemTime { /// See [`std::time::SystemTime::UNIX_EPOCH`]. pub const UNIX_EPOCH: Self = Self(Duration::ZERO); /// See [`std::time::SystemTime::now()`]. #[must_use] #[allow(clippy::missing_panics_doc)] pub fn now() -> Self { #[allow(clippy::as_conversions, clippy::cast_possible_truncation)] let ms = js_sys::Date::now() as i64; let ms = ms.try_into().expect("found negative timestamp"); Self(Duration::from_millis(ms)) } /// See [`std::time::SystemTime::duration_since()`]. #[allow(clippy::missing_errors_doc, clippy::trivially_copy_pass_by_ref)] pub fn duration_since(&self, earlier: Self) -> Result { if self.0 < earlier.0 { Err(SystemTimeError(earlier.0 - self.0)) } else { Ok(self.0 - earlier.0) } } /// See [`std::time::SystemTime::elapsed()`]. #[allow(clippy::missing_errors_doc, clippy::trivially_copy_pass_by_ref)] pub fn elapsed(&self) -> Result { Self::now().duration_since(*self) } /// See [`std::time::SystemTime::checked_add()`]. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn checked_add(&self, duration: Duration) -> Option { self.0.checked_add(duration).map(SystemTime) } /// See [`std::time::SystemTime::checked_sub()`]. #[allow(clippy::trivially_copy_pass_by_ref)] pub fn checked_sub(&self, duration: Duration) -> Option { self.0.checked_sub(duration).map(SystemTime) } } impl Add for SystemTime { type Output = Self; /// # Panics /// /// This function may panic if the resulting point in time cannot be /// represented by the underlying data structure. See /// [`SystemTime::checked_add`] for a version without panic. fn add(self, dur: Duration) -> Self { self.checked_add(dur) .expect("overflow when adding duration to instant") } } impl AddAssign for SystemTime { fn add_assign(&mut self, other: Duration) { *self = *self + other; } } impl Sub for SystemTime { type Output = Self; fn sub(self, dur: Duration) -> Self { self.checked_sub(dur) .expect("overflow when subtracting duration from instant") } } impl SubAssign for SystemTime { fn sub_assign(&mut self, other: Duration) { *self = *self - other; } } /// See [`std::time::SystemTimeError`]. #[derive(Clone, Debug)] #[allow(missing_copy_implementations)] pub struct SystemTimeError(Duration); impl SystemTimeError { /// See [`std::time::SystemTimeError::duration()`]. #[must_use] #[allow(clippy::missing_const_for_fn)] pub fn duration(&self) -> Duration { self.0 } } impl Display for SystemTimeError { fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result { write!(formatter, "second time provided was later than self") } } impl Error for SystemTimeError {} web-time-1.1.0/src/web.rs000064400000000000000000000030701046102023000132460ustar 00000000000000//! Platform-specific extensions to [`web-time`](crate) for the Web platform. #![allow(clippy::absolute_paths)] use std::time::SystemTime as StdSystemTime; use crate::SystemTime; /// Web-specific extension to [`web_time::SystemTime`](crate::SystemTime). pub trait SystemTimeExt { /// Convert [`web_time::SystemTime`](crate::SystemTime) to /// [`std::time::SystemTime`]. /// /// # Note /// /// This might give a misleading impression of compatibility! /// /// Considering this functionality will probably be used to interact with /// incompatible APIs of other dependencies, care should be taken that the /// dependency in question doesn't call [`std::time::SystemTime::now()`] /// internally, which would panic. fn to_std(self) -> std::time::SystemTime; /// Convert [`std::time::SystemTime`] to /// [`web_time::SystemTime`](crate::SystemTime). /// /// # Note /// /// This might give a misleading impression of compatibility! /// /// Considering this functionality will probably be used to interact with /// incompatible APIs of other dependencies, care should be taken that the /// dependency in question doesn't call [`std::time::SystemTime::now()`] /// internally, which would panic. fn from_std(time: std::time::SystemTime) -> SystemTime; } impl SystemTimeExt for SystemTime { fn to_std(self) -> std::time::SystemTime { StdSystemTime::UNIX_EPOCH + self.0 } fn from_std(time: std::time::SystemTime) -> SystemTime { Self::UNIX_EPOCH + time .duration_since(StdSystemTime::UNIX_EPOCH) .expect("found `SystemTime` earlier then unix epoch") } }