humantime-2.3.0/.cargo_vcs_info.json0000644000000001360000000000100130250ustar { "git": { "sha1": "7994b7129851ea3b0e5df8bee67870898e52fa1c" }, "path_in_vcs": "" }humantime-2.3.0/.github/dependabot.yml000064400000000000000000000003311046102023000160020ustar 00000000000000version: 2 updates: - package-ecosystem: cargo directory: "/" schedule: interval: weekly time: "3:23" - package-ecosystem: github-actions directory: "/" schedule: interval: weekly time: "3:26" humantime-2.3.0/.github/workflows/rust.yml000064400000000000000000000052721046102023000167400ustar 00000000000000name: Rust on: push: branches: ['main'] tags: ['**'] pull_request: env: CARGO_TERM_COLOR: always RUSTFLAGS: '-D warnings' jobs: test: strategy: matrix: os: [ubuntu-latest, windows-latest, macos-latest] runs-on: ${{ matrix.os }} steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable - run: cargo test --lib --no-default-features - run: cargo test --all-features # TODO: no_std # build-nostd: # name: Build on no_std target (thumbv7em-none-eabi) # runs-on: ubuntu-latest # steps: # - uses: actions/checkout@v3 # - uses: dtolnay/rust-toolchain@master # with: # toolchain: stable # targets: thumbv7em-none-eabi # - run: cargo build --target thumbv7em-none-eabi --lib --release --no-default-features nightly: name: Test nightly compiler runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@nightly - run: cargo test --all-features clippy: name: Check that clippy is happy runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable with: components: clippy - run: cargo clippy --all-features --all-targets rustfmt: name: Check formatting runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@stable with: components: rustfmt - run: cargo fmt -- --check msrv: name: Current MSRV is 1.60.0 runs-on: ubuntu-latest steps: - uses: actions/checkout@v3 # First run `cargo +nightly -Z minimal-verisons check` in order to get a # Cargo.lock with the oldest possible deps # - uses: dtolnay/rust-toolchain@nightly # - run: cargo -Z minimal-versions check --all-features --lib # Now check that `cargo build` works with respect to the oldest possible # deps and the stated MSRV - uses: dtolnay/rust-toolchain@1.60.0 - run: cargo build --all-features --lib semver: name: Check semver compatibility runs-on: ubuntu-latest steps: - name: Checkout sources uses: actions/checkout@v4 with: persist-credentials: false - name: Check semver uses: obi1kenobi/cargo-semver-checks-action@v2 audit: runs-on: ubuntu-latest steps: - uses: actions/checkout@v4 - uses: EmbarkStudios/cargo-deny-action@v2 # TODO: broken - migrate to criterion # bench: # name: Check that benchmarks compile # runs-on: ubuntu-latest # steps: # - uses: actions/checkout@v3 # - uses: dtolnay/rust-toolchain@nightly # - name: Build default (host native) bench # run: cargo build --benches humantime-2.3.0/.gitignore000064400000000000000000000000341046102023000136020ustar 00000000000000/Cargo.lock /.vagga /target humantime-2.3.0/Cargo.lock0000644000000317500000000000100110060ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 4 [[package]] name = "android-tzdata" version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e999941b234f3131b00bc13c22d06e8c5ff726d1b6318ac7eb276997bbb4fef0" [[package]] name = "android_system_properties" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "819e7219dbd41043ac279b19830f2efc897156490d7fd6ea916720117ee66311" dependencies = [ "libc", ] [[package]] name = "autocfg" version = "1.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ace50bade8e6234aa140d9a2f552bbee1db4d353f69b8217bc503490fc1a9f26" [[package]] name = "bencher" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dfdb4953a096c551ce9ace855a604d702e6e62d77fac690575ae347571717f5" [[package]] name = "bitflags" version = "2.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd" [[package]] name = "bumpalo" version = "3.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1628fb46dfa0b37568d12e5edd512553eccf6a22a78e8bde00bb4aed84d5bdbf" [[package]] name = "cc" version = "1.2.16" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "be714c154be609ec7f5dad223a33bf1482fff90472de28f7362806e6d4832b8c" dependencies = [ "shlex", ] [[package]] name = "cfg-if" version = "1.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" [[package]] name = "chrono" version = "0.4.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a7964611d71df112cb1730f2ee67324fcf4d0fc6606acbbe9bfe06df124637c" dependencies = [ "android-tzdata", "iana-time-zone", "js-sys", "num-traits", "wasm-bindgen", "windows-link", ] [[package]] name = "core-foundation-sys" version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" [[package]] name = "deranged" version = "0.3.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b42b6fa04a440b495c8b04d0e71b707c585f83cb9cb28cf8cd0d976c315e31b4" dependencies = [ "powerfmt", ] [[package]] name = "getrandom" version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "43a49c392881ce6d5c3b8cb70f98717b7c07aabbdff06687b9030dbfbe2725f8" dependencies = [ "cfg-if", "libc", "wasi", "windows-targets", ] [[package]] name = "humantime" version = "2.3.0" dependencies = [ "bencher", "chrono", "rand", "time", ] [[package]] name = "iana-time-zone" version = "0.1.61" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "235e081f3925a06703c2d0117ea8b91f042756fd6e7a6e5d901e8ca1a996b220" dependencies = [ "android_system_properties", "core-foundation-sys", "iana-time-zone-haiku", "js-sys", "wasm-bindgen", "windows-core", ] [[package]] name = "iana-time-zone-haiku" version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f" dependencies = [ "cc", ] [[package]] name = "itoa" version = "1.0.15" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a5f13b858c8d314ee3e8f639011f7ccefe71f97f96e50151fb991f267928e2c" [[package]] name = "js-sys" version = "0.3.77" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1cfaf33c695fc6e08064efbc1f72ec937429614f25eef83af942d0e227c3a28f" dependencies = [ "once_cell", "wasm-bindgen", ] [[package]] name = "libc" version = "0.2.171" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" [[package]] name = "log" version = "0.4.26" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e" [[package]] name = "num-conv" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9" [[package]] name = "num-traits" version = "0.2.19" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" dependencies = [ "autocfg", ] [[package]] name = "once_cell" version = "1.21.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cde51589ab56b20a6f686b2c68f7a0bd6add753d697abf720d63f8db3ab7b1ad" [[package]] name = "powerfmt" version = "0.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391" [[package]] name = "ppv-lite86" version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" dependencies = [ "zerocopy", ] [[package]] name = "proc-macro2" version = "1.0.94" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a31971752e70b8b2686d7e46ec17fb38dad4051d94024c88df49b667caea9c84" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "rand" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3779b94aeb87e8bd4e834cee3650289ee9e0d5677f976ecdb6d219e5f4f6cd94" dependencies = [ "rand_chacha", "rand_core", "zerocopy", ] [[package]] name = "rand_chacha" version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" dependencies = [ "ppv-lite86", "rand_core", ] [[package]] name = "rand_core" version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38" dependencies = [ "getrandom", ] [[package]] name = "rustversion" version = "1.0.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eded382c5f5f786b989652c49544c4877d9f015cc22e145a5ea8ea66c2921cd2" [[package]] name = "serde" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5f0e2c6ed6606019b4e29e69dbaba95b11854410e5347d525002456dbbb786b6" dependencies = [ "serde_derive", ] [[package]] name = "serde_derive" version = "1.0.219" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5b0276cf7f2c73365f7157c8123c21cd9a50fbbd844757af28ca1f5925fc2a00" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "shlex" version = "1.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" [[package]] name = "syn" version = "2.0.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b09a44accad81e1ba1cd74a32461ba89dee89095ba17b32f5d03683b1b1fc2a0" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "time" version = "0.3.39" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dad298b01a40a23aac4580b67e3dbedb7cc8402f3592d7f49469de2ea4aecdd8" dependencies = [ "deranged", "itoa", "num-conv", "powerfmt", "serde", "time-core", "time-macros", ] [[package]] name = "time-core" version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "765c97a5b985b7c11d7bc27fa927dc4fe6af3a6dfb021d28deb60d3bf51e76ef" [[package]] name = "time-macros" version = "0.2.20" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8093bc3e81c3bc5f7879de09619d06c9a5a5e45ca44dfeeb7225bae38005c5c" dependencies = [ "num-conv", "time-core", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "wasi" version = "0.13.3+wasi-0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "26816d2e1a4a36a2940b96c5296ce403917633dff8f3440e9b236ed6f6bacad2" dependencies = [ "wit-bindgen-rt", ] [[package]] name = "wasm-bindgen" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1edc8929d7499fc4e8f0be2262a241556cfc54a0bea223790e71446f2aab1ef5" dependencies = [ "cfg-if", "once_cell", "rustversion", "wasm-bindgen-macro", ] [[package]] name = "wasm-bindgen-backend" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f0a0651a5c2bc21487bde11ee802ccaf4c51935d0d3d42a6101f98161700bc6" dependencies = [ "bumpalo", "log", "proc-macro2", "quote", "syn", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-macro" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7fe63fc6d09ed3792bd0897b314f53de8e16568c2b3f7982f468c0bf9bd0b407" dependencies = [ "quote", "wasm-bindgen-macro-support", ] [[package]] name = "wasm-bindgen-macro-support" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ae87ea40c9f689fc23f209965b6fb8a99ad69aeeb0231408be24920604395de" dependencies = [ "proc-macro2", "quote", "syn", "wasm-bindgen-backend", "wasm-bindgen-shared", ] [[package]] name = "wasm-bindgen-shared" version = "0.2.100" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1a05d73b933a847d6cccdda8f838a22ff101ad9bf93e33684f39c1f5f0eece3d" dependencies = [ "unicode-ident", ] [[package]] name = "windows-core" version = "0.52.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "33ab640c8d7e35bf8ba19b884ba838ceb4fba93a4e8c65a9059d08afcfc683d9" dependencies = [ "windows-targets", ] [[package]] name = "windows-link" version = "0.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6dccfd733ce2b1753b03b6d3c65edf020262ea35e20ccdf3e288043e6dd620e3" [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ "windows_aarch64_gnullvm", "windows_aarch64_msvc", "windows_i686_gnu", "windows_i686_gnullvm", "windows_i686_msvc", "windows_x86_64_gnu", "windows_x86_64_gnullvm", "windows_x86_64_msvc", ] [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" [[package]] name = "windows_i686_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" [[package]] name = "windows_i686_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" [[package]] name = "windows_x86_64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" [[package]] name = "wit-bindgen-rt" version = "0.33.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3268f3d866458b787f390cf61f4bbb563b922d091359f9608842999eaee3943c" dependencies = [ "bitflags", ] [[package]] name = "zerocopy" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd97444d05a4328b90e75e503a34bad781f14e28a823ad3557f0750df1ebcbc6" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" version = "0.8.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6352c01d0edd5db859a63e2605f4ea3183ddbd15e2c4a9e7d32184df75e4f154" dependencies = [ "proc-macro2", "quote", "syn", ] humantime-2.3.0/Cargo.toml0000644000000027050000000000100110270ustar # 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" name = "humantime" version = "2.3.0" build = false autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = "A parser and formatter for std::time::{Duration, SystemTime}" homepage = "https://github.com/chronotope/humantime" documentation = "https://docs.rs/humantime" readme = "README.md" keywords = [ "time", "human", "human-friendly", "parser", "duration", ] categories = ["date-and-time"] license = "MIT OR Apache-2.0" repository = "https://github.com/chronotope/humantime" [features] mu = [] [lib] name = "humantime" path = "src/lib.rs" [[bench]] name = "datetime_format" path = "benches/datetime_format.rs" harness = false [[bench]] name = "datetime_parse" path = "benches/datetime_parse.rs" harness = false [dev-dependencies.bencher] version = "0.1.5" [dev-dependencies.chrono] version = "0.4" [dev-dependencies.rand] version = "0.9" [dev-dependencies.time] version = "0.3" features = ["formatting"] humantime-2.3.0/Cargo.toml.orig000064400000000000000000000012631046102023000145060ustar 00000000000000[package] name = "humantime" description = """A parser and formatter for std::time::{Duration, SystemTime}""" license = "MIT OR Apache-2.0" readme = "README.md" keywords = ["time", "human", "human-friendly", "parser", "duration"] homepage = "https://github.com/chronotope/humantime" repository = "https://github.com/chronotope/humantime" documentation = "https://docs.rs/humantime" version = "2.3.0" edition = "2021" categories = ["date-and-time"] [features] mu = [] [dev-dependencies] bencher = "0.1.5" time = { version = "0.3", features = ["formatting"] } chrono = "0.4" rand = "0.9" [[bench]] name = "datetime_format" harness = false [[bench]] name = "datetime_parse" harness = false humantime-2.3.0/LICENSE-APACHE000064400000000000000000000261361046102023000135510ustar 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 {yyyy} {name of copyright owner} 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. humantime-2.3.0/LICENSE-MIT000064400000000000000000000023441046102023000132540ustar 00000000000000Copyright (c) 2016 The humantime Developers Includes parts of http date with the following copyright: Copyright (c) 2016 Pyfisch Includes portions of musl libc with the following copyright: Copyright © 2005-2013 Rich Felker 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. humantime-2.3.0/README.md000064400000000000000000000042731046102023000131020ustar 00000000000000Human Time ========== **Status: stable** [Documentation](https://docs.rs/humantime) | [Github](https://github.com/tailhook/humantime) | [Crate](https://crates.io/crates/humantime) Features: * Parses durations in free form like `15days 2min 2s` * Formats durations in similar form `2years 2min 12us` * Parses and formats timestamp in `rfc3339` format: `2018-01-01T12:53:00Z` * Parses timestamps in a weaker format: `2018-01-01 12:53:00` Timestamp parsing/formatting is super-fast because format is basically fixed. Here are some micro-benchmarks: ``` test result: ok. 0 passed; 0 failed; 26 ignored; 0 measured; 0 filtered out Running target/release/deps/datetime_format-8facb4ac832d9770 running 2 tests test rfc3339_chrono ... bench: 737 ns/iter (+/- 37) test rfc3339_humantime_seconds ... bench: 73 ns/iter (+/- 2) test result: ok. 0 passed; 0 failed; 0 ignored; 2 measured; 0 filtered out Running target/release/deps/datetime_parse-342628f877d7867c running 6 tests test datetime_utc_parse_millis ... bench: 228 ns/iter (+/- 11) test datetime_utc_parse_nanos ... bench: 236 ns/iter (+/- 10) test datetime_utc_parse_seconds ... bench: 204 ns/iter (+/- 18) test rfc3339_humantime_millis ... bench: 28 ns/iter (+/- 1) test rfc3339_humantime_nanos ... bench: 36 ns/iter (+/- 2) test rfc3339_humantime_seconds ... bench: 24 ns/iter (+/- 1) test result: ok. 0 passed; 0 failed; 0 ignored; 6 measured; 0 filtered out ``` See [humantime-serde] for serde integration (previous crate [serde-humantime] looks unmaintained). [serde-humantime]: https://docs.rs/serde-humantime/0.1.1/serde_humantime/ [humantime-serde]: https://docs.rs/humantime-serde License ======= Licensed under either of * Apache License, Version 2.0, (./LICENSE-APACHE or http://www.apache.org/licenses/LICENSE-2.0) * MIT license (./LICENSE-MIT or http://opensource.org/licenses/MIT) at your option. 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. humantime-2.3.0/benches/datetime_format.rs000064400000000000000000000027731046102023000167470ustar 00000000000000#[macro_use] extern crate bencher; use std::io::Write; use std::time::{Duration, UNIX_EPOCH}; use bencher::Bencher; use chrono::{DateTime, Utc}; use humantime::format_rfc3339; fn rfc3339_humantime_seconds(b: &mut Bencher) { let time = UNIX_EPOCH + Duration::new(1_483_228_799, 0); let mut buf = Vec::with_capacity(100); b.iter(|| { buf.truncate(0); write!(&mut buf, "{}", format_rfc3339(time)).unwrap() }); } fn rfc3339_chrono(b: &mut Bencher) { use chrono::format::Fixed::*; use chrono::format::Item; use chrono::format::Item::*; use chrono::format::Numeric::*; use chrono::format::Pad::*; let time = DateTime::::from_timestamp(1_483_228_799, 0).unwrap(); let mut buf = Vec::with_capacity(100); // formatting code from env_logger const ITEMS: &[Item<'static>] = { &[ Numeric(Year, Zero), Literal("-"), Numeric(Month, Zero), Literal("-"), Numeric(Day, Zero), Literal("T"), Numeric(Hour, Zero), Literal(":"), Numeric(Minute, Zero), Literal(":"), Numeric(Second, Zero), Fixed(TimezoneOffsetZ), ] }; b.iter(|| { buf.truncate(0); write!( &mut buf, "{}", time.format_with_items(ITEMS.iter().cloned()) ) .unwrap() }); } benchmark_group!(benches, rfc3339_humantime_seconds, rfc3339_chrono); benchmark_main!(benches); humantime-2.3.0/benches/datetime_parse.rs000064400000000000000000000021231046102023000165560ustar 00000000000000#[macro_use] extern crate bencher; use bencher::Bencher; use chrono::DateTime; use humantime::parse_rfc3339; fn rfc3339_humantime_seconds(b: &mut Bencher) { b.iter(|| parse_rfc3339("2018-02-13T23:08:32Z").unwrap()); } fn datetime_utc_parse_seconds(b: &mut Bencher) { b.iter(|| DateTime::parse_from_rfc3339("2018-02-13T23:08:32Z").unwrap()); } fn rfc3339_humantime_millis(b: &mut Bencher) { b.iter(|| parse_rfc3339("2018-02-13T23:08:32.123Z").unwrap()); } fn datetime_utc_parse_millis(b: &mut Bencher) { b.iter(|| DateTime::parse_from_rfc3339("2018-02-13T23:08:32.123Z").unwrap()); } fn rfc3339_humantime_nanos(b: &mut Bencher) { b.iter(|| parse_rfc3339("2018-02-13T23:08:32.123456983Z").unwrap()); } fn datetime_utc_parse_nanos(b: &mut Bencher) { b.iter(|| DateTime::parse_from_rfc3339("2018-02-13T23:08:32.123456983Z").unwrap()); } benchmark_group!( benches, rfc3339_humantime_seconds, datetime_utc_parse_seconds, rfc3339_humantime_millis, datetime_utc_parse_millis, rfc3339_humantime_nanos, datetime_utc_parse_nanos ); benchmark_main!(benches); humantime-2.3.0/deny.toml000064400000000000000000000000651046102023000134520ustar 00000000000000[licenses] version = 2 allow = ["Apache-2.0", "MIT"] humantime-2.3.0/src/date.rs000064400000000000000000000561401046102023000136750ustar 00000000000000use std::error::Error as StdError; use std::fmt; use std::str; use std::time::{Duration, SystemTime, UNIX_EPOCH}; #[cfg(all( target_pointer_width = "32", not(target_os = "windows"), not(all(target_arch = "wasm32", not(target_os = "emscripten"))) ))] mod max { pub(super) const SECONDS: u64 = ::std::i32::MAX as u64; #[allow(unused)] pub(super) const TIMESTAMP: &'static str = "2038-01-19T03:14:07Z"; } #[cfg(any( target_pointer_width = "64", target_os = "windows", all(target_arch = "wasm32", not(target_os = "emscripten")), ))] mod max { pub(super) const SECONDS: u64 = 253_402_300_800 - 1; // last second of year 9999 #[allow(unused)] pub(super) const TIMESTAMP: &str = "9999-12-31T23:59:59Z"; } /// Error parsing datetime (timestamp) #[derive(Debug, PartialEq, Clone, Copy)] pub enum Error { /// Numeric component is out of range OutOfRange, /// Bad character where digit is expected InvalidDigit, /// Other formatting errors InvalidFormat, } impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::OutOfRange => write!(f, "numeric component is out of range"), Error::InvalidDigit => write!(f, "bad character where digit is expected"), Error::InvalidFormat => write!(f, "timestamp format is invalid"), } } } #[derive(Debug, Clone, PartialEq, Eq)] enum Precision { Smart, Seconds, Millis, Micros, Nanos, } /// A wrapper type that allows you to Display a SystemTime #[derive(Debug, Clone)] pub struct Rfc3339Timestamp(SystemTime, Precision); #[inline] /// Converts two digits given in ASCII to its proper decimal representation. fn two_digits(b1: u8, b2: u8) -> Result { fn two_digits_inner(a: char, b: char) -> Option { let a = a.to_digit(10)?; let b = b.to_digit(10)?; Some((a * 10 + b) as u64) } two_digits_inner(b1 as char, b2 as char).ok_or(Error::InvalidDigit) } /// Parse RFC3339 timestamp `2018-02-14T00:28:07Z` /// /// Supported features: /// - Any precision of fractional digits `2018-02-14T00:28:07.133Z`. /// - The UTC timezone can be indicated with `Z` or `+00:00`. /// /// Unsupported feature: localized timestamps. Only UTC is supported. pub fn parse_rfc3339(s: &str) -> Result { if s.len() < "2018-02-14T00:28:07Z".len() { return Err(Error::InvalidFormat); } let b = s.as_bytes(); if b[10] != b'T' || (b.last() != Some(&b'Z') && !s.ends_with("+00:00")) { return Err(Error::InvalidFormat); } parse_rfc3339_weak(s) } /// Parse RFC3339-like timestamp `2018-02-14 00:28:07` /// /// Supported features: /// /// 1. Any precision of fractional digits `2018-02-14 00:28:07.133`. /// 2. Supports timestamp with or without either of `T`, `Z` or `+00:00`. /// 3. Anything valid for [`parse_rfc3339`](parse_rfc3339) is valid for this function /// /// Unsupported feature: localized timestamps. Only UTC is supported, even if /// `Z` is not specified. /// /// This function is intended to use for parsing human input. Whereas /// `parse_rfc3339` is for strings generated programmatically. pub fn parse_rfc3339_weak(s: &str) -> Result { if s.len() < "2018-02-14T00:28:07".len() { return Err(Error::InvalidFormat); } let b = s.as_bytes(); // for careless slicing if b[4] != b'-' || b[7] != b'-' || (b[10] != b'T' && b[10] != b' ') || b[13] != b':' || b[16] != b':' { return Err(Error::InvalidFormat); } let year = two_digits(b[0], b[1])? * 100 + two_digits(b[2], b[3])?; let month = two_digits(b[5], b[6])?; let day = two_digits(b[8], b[9])?; let hour = two_digits(b[11], b[12])?; let minute = two_digits(b[14], b[15])?; let mut second = two_digits(b[17], b[18])?; if year < 1970 || hour > 23 || minute > 59 || second > 60 { return Err(Error::OutOfRange); } // TODO(tailhook) should we check that leaps second is only on midnight ? if second == 60 { second = 59; } let leap = is_leap_year(year); let (mut ydays, mdays) = match month { 1 => (0, 31), 2 if leap => (31, 29), 2 => (31, 28), 3 => (59, 31), 4 => (90, 30), 5 => (120, 31), 6 => (151, 30), 7 => (181, 31), 8 => (212, 31), 9 => (243, 30), 10 => (273, 31), 11 => (304, 30), 12 => (334, 31), _ => return Err(Error::OutOfRange), }; if day > mdays || day == 0 { return Err(Error::OutOfRange); } ydays += day - 1; if leap && month > 2 { ydays += 1; } let leap_years = ((year - 1) - 1968) / 4 - ((year - 1) - 1900) / 100 + ((year - 1) - 1600) / 400; let days = (year - 1970) * 365 + leap_years + ydays; let time = second + minute * 60 + hour * 3600; let mut nanos = 0; let mut mult = 100_000_000; if b.get(19) == Some(&b'.') { for idx in 20..b.len() { if b[idx] == b'Z' { if idx == b.len() - 1 { break; } return Err(Error::InvalidDigit); } else if b[idx] == b'+' { // start of "+00:00", which must be at the end if idx == b.len() - 6 { break; } return Err(Error::InvalidDigit); } nanos += mult * (b[idx] as char).to_digit(10).ok_or(Error::InvalidDigit)?; mult /= 10; } } else if b.len() != 19 && (b.len() > 25 || (b[19] != b'Z' && (&b[19..] != b"+00:00"))) { return Err(Error::InvalidFormat); } let total_seconds = time + days * 86400; if total_seconds > max::SECONDS { return Err(Error::OutOfRange); } Ok(UNIX_EPOCH + Duration::new(total_seconds, nanos)) } fn is_leap_year(y: u64) -> bool { y % 4 == 0 && (y % 100 != 0 || y % 400 == 0) } /// Format an RFC3339 timestamp `2018-02-14T00:28:07Z` /// /// This function formats timestamp with smart precision: i.e. if it has no /// fractional seconds, they aren't written at all. And up to nine digits if /// they are. /// /// The value is always UTC and ignores system timezone. pub fn format_rfc3339(system_time: SystemTime) -> Rfc3339Timestamp { Rfc3339Timestamp(system_time, Precision::Smart) } /// Format an RFC3339 timestamp `2018-02-14T00:28:07Z` /// /// This format always shows timestamp without fractional seconds. /// /// The value is always UTC and ignores system timezone. pub fn format_rfc3339_seconds(system_time: SystemTime) -> Rfc3339Timestamp { Rfc3339Timestamp(system_time, Precision::Seconds) } /// Format an RFC3339 timestamp `2018-02-14T00:28:07.000Z` /// /// This format always shows milliseconds even if millisecond value is zero. /// /// The value is always UTC and ignores system timezone. pub fn format_rfc3339_millis(system_time: SystemTime) -> Rfc3339Timestamp { Rfc3339Timestamp(system_time, Precision::Millis) } /// Format an RFC3339 timestamp `2018-02-14T00:28:07.000000Z` /// /// This format always shows microseconds even if microsecond value is zero. /// /// The value is always UTC and ignores system timezone. pub fn format_rfc3339_micros(system_time: SystemTime) -> Rfc3339Timestamp { Rfc3339Timestamp(system_time, Precision::Micros) } /// Format an RFC3339 timestamp `2018-02-14T00:28:07.000000000Z` /// /// This format always shows nanoseconds even if nanosecond value is zero. /// /// The value is always UTC and ignores system timezone. pub fn format_rfc3339_nanos(system_time: SystemTime) -> Rfc3339Timestamp { Rfc3339Timestamp(system_time, Precision::Nanos) } impl Rfc3339Timestamp { /// Returns a reference to the [`SystemTime`][] that is being formatted. pub fn get_ref(&self) -> &SystemTime { &self.0 } } impl fmt::Display for Rfc3339Timestamp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { use self::Precision::*; let dur = self .0 .duration_since(UNIX_EPOCH) .expect("all times should be after the epoch"); let secs_since_epoch = dur.as_secs(); let nanos = dur.subsec_nanos(); if secs_since_epoch >= 253_402_300_800 { // year 9999 return Err(fmt::Error); } /* 2000-03-01 (mod 400 year, immediately after feb29 */ const LEAPOCH: i64 = 11017; const DAYS_PER_400Y: i64 = 365 * 400 + 97; const DAYS_PER_100Y: i64 = 365 * 100 + 24; const DAYS_PER_4Y: i64 = 365 * 4 + 1; let days = (secs_since_epoch / 86400) as i64 - LEAPOCH; let secs_of_day = secs_since_epoch % 86400; let mut qc_cycles = days / DAYS_PER_400Y; let mut remdays = days % DAYS_PER_400Y; if remdays < 0 { remdays += DAYS_PER_400Y; qc_cycles -= 1; } let mut c_cycles = remdays / DAYS_PER_100Y; if c_cycles == 4 { c_cycles -= 1; } remdays -= c_cycles * DAYS_PER_100Y; let mut q_cycles = remdays / DAYS_PER_4Y; if q_cycles == 25 { q_cycles -= 1; } remdays -= q_cycles * DAYS_PER_4Y; let mut remyears = remdays / 365; if remyears == 4 { remyears -= 1; } remdays -= remyears * 365; let mut year = 2000 + remyears + 4 * q_cycles + 100 * c_cycles + 400 * qc_cycles; let months = [31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29]; let mut mon = 0; for mon_len in months.iter() { mon += 1; if remdays < *mon_len { break; } remdays -= *mon_len; } let mday = remdays + 1; let mon = if mon + 2 > 12 { year += 1; mon - 10 } else { mon + 2 }; const BUF_INIT: [u8; 30] = *b"0000-00-00T00:00:00.000000000Z"; let mut buf: [u8; 30] = BUF_INIT; buf[0] = b'0' + (year / 1000) as u8; buf[1] = b'0' + (year / 100 % 10) as u8; buf[2] = b'0' + (year / 10 % 10) as u8; buf[3] = b'0' + (year % 10) as u8; buf[5] = b'0' + (mon / 10) as u8; buf[6] = b'0' + (mon % 10) as u8; buf[8] = b'0' + (mday / 10) as u8; buf[9] = b'0' + (mday % 10) as u8; buf[11] = b'0' + (secs_of_day / 3600 / 10) as u8; buf[12] = b'0' + (secs_of_day / 3600 % 10) as u8; buf[14] = b'0' + (secs_of_day / 60 / 10 % 6) as u8; buf[15] = b'0' + (secs_of_day / 60 % 10) as u8; buf[17] = b'0' + (secs_of_day / 10 % 6) as u8; buf[18] = b'0' + (secs_of_day % 10) as u8; let offset = if self.1 == Seconds || nanos == 0 && self.1 == Smart { buf[19] = b'Z'; 19 } else if self.1 == Millis { buf[20] = b'0' + (nanos / 100_000_000) as u8; buf[21] = b'0' + (nanos / 10_000_000 % 10) as u8; buf[22] = b'0' + (nanos / 1_000_000 % 10) as u8; buf[23] = b'Z'; 23 } else if self.1 == Micros { buf[20] = b'0' + (nanos / 100_000_000) as u8; buf[21] = b'0' + (nanos / 10_000_000 % 10) as u8; buf[22] = b'0' + (nanos / 1_000_000 % 10) as u8; buf[23] = b'0' + (nanos / 100_000 % 10) as u8; buf[24] = b'0' + (nanos / 10_000 % 10) as u8; buf[25] = b'0' + (nanos / 1_000 % 10) as u8; buf[26] = b'Z'; 26 } else { buf[20] = b'0' + (nanos / 100_000_000) as u8; buf[21] = b'0' + (nanos / 10_000_000 % 10) as u8; buf[22] = b'0' + (nanos / 1_000_000 % 10) as u8; buf[23] = b'0' + (nanos / 100_000 % 10) as u8; buf[24] = b'0' + (nanos / 10_000 % 10) as u8; buf[25] = b'0' + (nanos / 1_000 % 10) as u8; buf[26] = b'0' + (nanos / 100 % 10) as u8; buf[27] = b'0' + (nanos / 10 % 10) as u8; buf[28] = b'0' + (nanos % 10) as u8; // 29th is 'Z' 29 }; // we know our chars are all ascii f.write_str(str::from_utf8(&buf[..=offset]).expect("Conversion to utf8 failed")) } } #[cfg(test)] mod test { use std::str::from_utf8; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use rand::Rng; use time::format_description::well_known::Rfc3339; use time::UtcDateTime; use super::format_rfc3339_nanos; use super::max; use super::{format_rfc3339, parse_rfc3339, parse_rfc3339_weak}; use super::{format_rfc3339_micros, format_rfc3339_millis}; fn from_sec(sec: u64) -> (String, SystemTime) { let s = UtcDateTime::from_unix_timestamp(sec as i64) .unwrap() .format(&Rfc3339) .unwrap(); let time = UNIX_EPOCH + Duration::new(sec, 0); (s, time) } #[test] #[cfg(all(target_pointer_width = "32", target_os = "linux"))] fn year_after_2038_fails_gracefully() { // next second assert_eq!( parse_rfc3339("2038-01-19T03:14:08Z").unwrap_err(), super::Error::OutOfRange ); assert_eq!( parse_rfc3339("9999-12-31T23:59:59Z").unwrap_err(), super::Error::OutOfRange ); } #[test] fn smoke_tests_parse() { assert_eq!( parse_rfc3339("1970-01-01T00:00:00Z").unwrap(), UNIX_EPOCH + Duration::new(0, 0) ); assert_eq!( parse_rfc3339("1970-01-01T00:00:01Z").unwrap(), UNIX_EPOCH + Duration::new(1, 0) ); assert_eq!( parse_rfc3339("2018-02-13T23:08:32Z").unwrap(), UNIX_EPOCH + Duration::new(1_518_563_312, 0) ); assert_eq!( parse_rfc3339("2012-01-01T00:00:00Z").unwrap(), UNIX_EPOCH + Duration::new(1_325_376_000, 0) ); } #[test] fn smoke_tests_format() { assert_eq!( format_rfc3339(UNIX_EPOCH + Duration::new(0, 0)).to_string(), "1970-01-01T00:00:00Z" ); assert_eq!( format_rfc3339(UNIX_EPOCH + Duration::new(1, 0)).to_string(), "1970-01-01T00:00:01Z" ); assert_eq!( format_rfc3339(UNIX_EPOCH + Duration::new(1_518_563_312, 0)).to_string(), "2018-02-13T23:08:32Z" ); assert_eq!( format_rfc3339(UNIX_EPOCH + Duration::new(1_325_376_000, 0)).to_string(), "2012-01-01T00:00:00Z" ); } #[test] fn smoke_tests_format_millis() { assert_eq!( format_rfc3339_millis(UNIX_EPOCH + Duration::new(0, 0)).to_string(), "1970-01-01T00:00:00.000Z" ); assert_eq!( format_rfc3339_millis(UNIX_EPOCH + Duration::new(1_518_563_312, 123_000_000)) .to_string(), "2018-02-13T23:08:32.123Z" ); } #[test] fn smoke_tests_format_micros() { assert_eq!( format_rfc3339_micros(UNIX_EPOCH + Duration::new(0, 0)).to_string(), "1970-01-01T00:00:00.000000Z" ); assert_eq!( format_rfc3339_micros(UNIX_EPOCH + Duration::new(1_518_563_312, 123_000_000)) .to_string(), "2018-02-13T23:08:32.123000Z" ); assert_eq!( format_rfc3339_micros(UNIX_EPOCH + Duration::new(1_518_563_312, 456_123_000)) .to_string(), "2018-02-13T23:08:32.456123Z" ); } #[test] fn smoke_tests_format_nanos() { assert_eq!( format_rfc3339_nanos(UNIX_EPOCH + Duration::new(0, 0)).to_string(), "1970-01-01T00:00:00.000000000Z" ); assert_eq!( format_rfc3339_nanos(UNIX_EPOCH + Duration::new(1_518_563_312, 123_000_000)) .to_string(), "2018-02-13T23:08:32.123000000Z" ); #[cfg(not(target_os = "windows"))] assert_eq!( format_rfc3339_nanos(UNIX_EPOCH + Duration::new(1_518_563_312, 789_456_123)) .to_string(), "2018-02-13T23:08:32.789456123Z" ); #[cfg(target_os = "windows")] // Not sure what is up with Windows rounding? assert_eq!( format_rfc3339_nanos(UNIX_EPOCH + Duration::new(1_518_563_312, 789_456_123)) .to_string(), "2018-02-13T23:08:32.789456100Z" ); } #[test] fn upper_bound() { let max = UNIX_EPOCH + Duration::new(max::SECONDS, 0); assert_eq!(parse_rfc3339(max::TIMESTAMP).unwrap(), max); assert_eq!(format_rfc3339(max).to_string(), max::TIMESTAMP); } #[test] fn leap_second() { assert_eq!( parse_rfc3339("2016-12-31T23:59:60Z").unwrap(), UNIX_EPOCH + Duration::new(1_483_228_799, 0) ); } #[test] fn first_731_days() { let year_start = 0; // 1970 for day in 0..=365 * 2 { // scan leap year and non-leap year let (s, time) = from_sec(year_start + day * 86400); assert_eq!(parse_rfc3339(&s).unwrap(), time); assert_eq!(format_rfc3339(time).to_string(), s); } } #[test] fn the_731_consecutive_days() { let year_start = 1_325_376_000; // 2012 for day in 0..=365 * 2 { // scan leap year and non-leap year let (s, time) = from_sec(year_start + day * 86400); assert_eq!(parse_rfc3339(&s).unwrap(), time); assert_eq!(format_rfc3339(time).to_string(), s); } } #[test] fn all_86400_seconds() { let day_start = 1_325_376_000; for second in 0..86400 { // scan leap year and non-leap year let (s, time) = from_sec(day_start + second); assert_eq!(parse_rfc3339(&s).unwrap(), time); assert_eq!(format_rfc3339(time).to_string(), s); } } #[test] fn random_past() { let upper = SystemTime::now() .duration_since(UNIX_EPOCH) .unwrap() .as_secs(); for _ in 0..10000 { let sec = rand::rng().random_range(0..upper); let (s, time) = from_sec(sec); assert_eq!(parse_rfc3339(&s).unwrap(), time); assert_eq!(format_rfc3339(time).to_string(), s); } } #[test] fn random_wide_range() { for _ in 0..100_000 { let sec = rand::rng().random_range(0..max::SECONDS); let (s, time) = from_sec(sec); assert_eq!(parse_rfc3339(&s).unwrap(), time); assert_eq!(format_rfc3339(time).to_string(), s); } } #[test] fn milliseconds() { assert_eq!( parse_rfc3339("1970-01-01T00:00:00.123Z").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000_000) ); assert_eq!( format_rfc3339(UNIX_EPOCH + Duration::new(0, 123_000_000)).to_string(), "1970-01-01T00:00:00.123000000Z" ); } #[test] #[should_panic(expected = "OutOfRange")] fn zero_month() { parse_rfc3339("1970-00-01T00:00:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_month() { parse_rfc3339("1970-32-01T00:00:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn zero_day() { parse_rfc3339("1970-01-00T00:00:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_day() { parse_rfc3339("1970-12-35T00:00:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_day2() { parse_rfc3339("1970-02-30T00:00:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_second() { parse_rfc3339("1970-12-30T00:00:78Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_minute() { parse_rfc3339("1970-12-30T00:78:00Z").unwrap(); } #[test] #[should_panic(expected = "OutOfRange")] fn big_hour() { parse_rfc3339("1970-12-30T24:00:00Z").unwrap(); } #[test] fn break_data() { for pos in 0.."2016-12-31T23:59:60Z".len() { let mut s = b"2016-12-31T23:59:60Z".to_vec(); s[pos] = b'x'; parse_rfc3339(from_utf8(&s).unwrap()).unwrap_err(); } } #[test] fn weak_smoke_tests() { assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00").unwrap(), UNIX_EPOCH + Duration::new(0, 0) ); parse_rfc3339("1970-01-01 00:00:00").unwrap_err(); assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00.000123").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000) ); parse_rfc3339("1970-01-01 00:00:00.000123").unwrap_err(); assert_eq!( parse_rfc3339_weak("1970-01-01T00:00:00.000123").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000) ); parse_rfc3339("1970-01-01T00:00:00.000123").unwrap_err(); assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00.000123Z").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000) ); parse_rfc3339("1970-01-01 00:00:00.000123Z").unwrap_err(); assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00Z").unwrap(), UNIX_EPOCH + Duration::new(0, 0) ); parse_rfc3339("1970-01-01 00:00:00Z").unwrap_err(); } #[test] fn parse_offset_00() { assert_eq!( parse_rfc3339("1970-01-01T00:00:00+00:00").unwrap(), UNIX_EPOCH + Duration::new(0, 0) ); assert_eq!( parse_rfc3339("1970-01-01T00:00:01+00:00").unwrap(), UNIX_EPOCH + Duration::new(1, 0) ); assert_eq!( parse_rfc3339("2018-02-13T23:08:32+00:00").unwrap(), UNIX_EPOCH + Duration::new(1_518_563_312, 0) ); assert_eq!( parse_rfc3339("2012-01-01T00:00:00+00:00").unwrap(), UNIX_EPOCH + Duration::new(1_325_376_000, 0) ); // invalid assert_eq!( parse_rfc3339("2012-01-01T00:00:00 +00:00"), Err(super::Error::InvalidFormat) ); assert_eq!( parse_rfc3339("2012-01-01T00:00:00+00"), Err(super::Error::InvalidFormat) ); } #[test] fn weak_parse_offset_00() { assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00+00:00").unwrap(), UNIX_EPOCH + Duration::new(0, 0) ); assert_eq!( parse_rfc3339_weak("1970-01-01 00:00:00.000123+00:00").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000) ); assert_eq!( parse_rfc3339_weak("1970-01-01T00:00:00.000123+00:00").unwrap(), UNIX_EPOCH + Duration::new(0, 123_000) ); // invalid parse_rfc3339("2012-01-01T+00:00:00").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.00+0123").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.0000123+00:00").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.0000123+00:00abcd").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.0000123+02:00").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.0000123+00").unwrap_err(); parse_rfc3339("1970-01-01 00:00:00.0000123+").unwrap_err(); } } humantime-2.3.0/src/duration.rs000064400000000000000000000723151046102023000146070ustar 00000000000000use std::error::Error as StdError; use std::fmt; use std::str::{Chars, FromStr}; use std::time::Duration; /// Error parsing human-friendly duration #[derive(Debug, PartialEq, Clone)] pub enum Error { /// Invalid character during parsing /// /// More specifically anything that is not alphanumeric is prohibited /// /// The field is an byte offset of the character in the string. InvalidCharacter(usize), /// Non-numeric value where number is expected /// /// This usually means that either time unit is broken into words, /// e.g. `m sec` instead of `msec`, or just number is omitted, /// for example `2 hours min` instead of `2 hours 1 min` /// /// The field is an byte offset of the errorneous character /// in the string. NumberExpected(usize), /// Unit in the number is not one of allowed units /// /// See documentation of `parse_duration` for the list of supported /// time units. /// /// The two fields are start and end (exclusive) of the slice from /// the original string, containing errorneous value UnknownUnit { /// Start of the invalid unit inside the original string start: usize, /// End of the invalid unit inside the original string end: usize, /// The unit verbatim unit: String, /// A number associated with the unit value: u64, }, /// The numeric value exceeds the limits of this library. /// /// This can mean two things: /// - The value is too large to be useful. /// For instance, the maximum duration written with subseconds unit is about 3000 years. /// - The attempted precision is not supported. /// For instance, a duration of `0.5ns` is not supported, /// because durations below one nanosecond cannot be represented. // NOTE: it would be more logical to create a separate `NumberPrecisionLimit` error, // but that would be a breaking change. Reconsider this for the next major version. NumberOverflow, /// The value was an empty string (or consists only whitespace) Empty, } impl StdError for Error {} impl fmt::Display for Error { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { match self { Error::InvalidCharacter(offset) => write!(f, "invalid character at {}", offset), Error::NumberExpected(offset) => write!(f, "expected number at {}", offset), Error::UnknownUnit { unit, value, .. } if unit.is_empty() => { write!(f, "time unit needed, for example {0}sec or {0}ms", value) } Error::UnknownUnit { unit, .. } => { write!( f, "unknown time unit {:?}, \ supported units: ns, us/µs, ms, sec, min, hours, days, \ weeks, months, years (and few variations)", unit ) } Error::NumberOverflow => write!(f, "number is too large or cannot be represented without a lack of precision (values below 1ns are not supported)"), Error::Empty => write!(f, "value was empty"), } } } /// A wrapper type that allows you to Display a Duration #[derive(Debug, Clone)] pub struct FormattedDuration(Duration); trait OverflowOp: Sized { fn mul(self, other: Self) -> Result; fn add(self, other: Self) -> Result; fn div(self, other: Self) -> Result; } impl OverflowOp for u64 { fn mul(self, other: Self) -> Result { self.checked_mul(other).ok_or(Error::NumberOverflow) } fn add(self, other: Self) -> Result { self.checked_add(other).ok_or(Error::NumberOverflow) } fn div(self, other: Self) -> Result { match self % other { 0 => Ok(self / other), _ => Err(Error::NumberOverflow), } } } #[derive(Debug, Clone, Copy)] struct Fraction { numerator: u64, denominator: u64, } struct Parser<'a> { iter: Chars<'a>, src: &'a str, } impl Parser<'_> { fn parse(mut self) -> Result { let mut n = self.parse_first_char()?.ok_or(Error::Empty)?; // integer part let mut out = Duration::ZERO; 'outer: loop { let mut frac = None; // fractional part let mut off = self.off(); while let Some(c) = self.iter.next() { match c { '0'..='9' => { n = n .checked_mul(10) .and_then(|x| x.checked_add(c as u64 - '0' as u64)) .ok_or(Error::NumberOverflow)?; } c if c.is_whitespace() => {} 'a'..='z' | 'A'..='Z' | 'µ' => { break; } '.' => { // decimal separator, the fractional part begins now frac = Some(self.parse_fractional_part(&mut off)?); break; } _ => { return Err(Error::InvalidCharacter(off)); } } off = self.off(); } let start = off; let mut off = self.off(); while let Some(c) = self.iter.next() { match c { '0'..='9' => { self.parse_unit(n, frac, start, off, &mut out)?; n = c as u64 - '0' as u64; continue 'outer; } c if c.is_whitespace() => break, 'a'..='z' | 'A'..='Z' | 'µ' => {} _ => { return Err(Error::InvalidCharacter(off)); } } off = self.off(); } self.parse_unit(n, frac, start, off, &mut out)?; n = match self.parse_first_char()? { Some(n) => n, None => return Ok(out), }; } } fn parse_first_char(&mut self) -> Result, Error> { let off = self.off(); for c in self.iter.by_ref() { match c { '0'..='9' => { return Ok(Some(c as u64 - '0' as u64)); } c if c.is_whitespace() => continue, _ => { return Err(Error::NumberExpected(off)); } } } Ok(None) } fn parse_fractional_part(&mut self, off: &mut usize) -> Result { let mut numerator = 0u64; let mut denominator = 1u64; let mut zeros = true; while let Some(c) = self.iter.next() { match c { '0' => { denominator = denominator.checked_mul(10).ok_or(Error::NumberOverflow)?; if !zeros { numerator = numerator.checked_mul(10).ok_or(Error::NumberOverflow)?; } } '1'..='9' => { zeros = false; denominator = denominator.checked_mul(10).ok_or(Error::NumberOverflow)?; numerator = numerator .checked_mul(10) .and_then(|x| x.checked_add(c as u64 - '0' as u64)) .ok_or(Error::NumberOverflow)?; } c if c.is_whitespace() => {} 'a'..='z' | 'A'..='Z' | 'µ' => { break; } _ => { return Err(Error::InvalidCharacter(*off)); } }; // update the offset used by the parsing loop *off = self.off(); } if denominator == 1 { // no digits were given after the separator, e.g. "1." return Err(Error::InvalidCharacter(*off)); } Ok(Fraction { numerator, denominator, }) } fn off(&self) -> usize { self.src.len() - self.iter.as_str().len() } fn parse_unit( &mut self, n: u64, frac: Option, start: usize, end: usize, out: &mut Duration, ) -> Result<(), Error> { let unit = match Unit::from_str(&self.src[start..end]) { Ok(u) => u, Err(()) => { return Err(Error::UnknownUnit { start, end, unit: self.src[start..end].to_owned(), value: n, }); } }; // add the integer part let (sec, nsec) = match unit { Unit::Nanosecond => (0u64, n), Unit::Microsecond => (0u64, n.mul(1000)?), Unit::Millisecond => (0u64, n.mul(1_000_000)?), Unit::Second => (n, 0), Unit::Minute => (n.mul(60)?, 0), Unit::Hour => (n.mul(3600)?, 0), Unit::Day => (n.mul(86400)?, 0), Unit::Week => (n.mul(86400 * 7)?, 0), Unit::Month => (n.mul(2_630_016)?, 0), // 30.44d Unit::Year => (n.mul(31_557_600)?, 0), // 365.25d }; add_current(sec, nsec, out)?; // add the fractional part if let Some(Fraction { numerator: n, denominator: d, }) = frac { let (sec, nsec) = match unit { Unit::Nanosecond => return Err(Error::NumberOverflow), Unit::Microsecond => (0, n.mul(1000)?.div(d)?), Unit::Millisecond => (0, n.mul(1_000_000)?.div(d)?), Unit::Second => (0, n.mul(1_000_000_000)?.div(d)?), Unit::Minute => (0, n.mul(60_000_000_000)?.div(d)?), Unit::Hour => (n.mul(3600)?.div(d)?, 0), Unit::Day => (n.mul(86400)?.div(d)?, 0), Unit::Week => (n.mul(86400 * 7)?.div(d)?, 0), Unit::Month => (n.mul(2_630_016)?.div(d)?, 0), // 30.44d Unit::Year => (n.mul(31_557_600)?.div(d)?, 0), // 365.25d }; add_current(sec, nsec, out)?; } Ok(()) } } fn add_current(mut sec: u64, nsec: u64, out: &mut Duration) -> Result<(), Error> { let mut nsec = (out.subsec_nanos() as u64).add(nsec)?; if nsec > 1_000_000_000 { sec = sec.add(nsec / 1_000_000_000)?; nsec %= 1_000_000_000; } sec = out.as_secs().add(sec)?; *out = Duration::new(sec, nsec as u32); Ok(()) } enum Unit { Nanosecond, Microsecond, Millisecond, Second, Minute, Hour, Day, Week, Month, Year, } impl FromStr for Unit { type Err = (); fn from_str(s: &str) -> Result { match s { "nanos" | "nsec" | "ns" => Ok(Self::Nanosecond), "usec" | "us" | "µs" => Ok(Self::Microsecond), "millis" | "msec" | "ms" => Ok(Self::Millisecond), "seconds" | "second" | "secs" | "sec" | "s" => Ok(Self::Second), "minutes" | "minute" | "min" | "mins" | "m" => Ok(Self::Minute), "hours" | "hour" | "hr" | "hrs" | "h" => Ok(Self::Hour), "days" | "day" | "d" => Ok(Self::Day), "weeks" | "week" | "wk" | "wks" | "w" => Ok(Self::Week), "months" | "month" | "M" => Ok(Self::Month), "years" | "year" | "yr" | "yrs" | "y" => Ok(Self::Year), _ => Err(()), } } } /// Parse duration object `1hour 12min 5s` /// /// The duration object is a concatenation of time spans. Where each time /// span is an integer number and a suffix. Supported suffixes: /// /// * `nsec`, `ns` -- nanoseconds /// * `usec`, `us`, `µs` -- microseconds /// * `msec`, `ms` -- milliseconds /// * `seconds`, `second`, `sec`, `s` /// * `minutes`, `minute`, `min`, `m` /// * `hours`, `hour`, `hr`, `hrs`, `h` /// * `days`, `day`, `d` /// * `weeks`, `week`, `wk`, `wks`, `w` /// * `months`, `month`, `M` -- defined as 30.44 days /// * `years`, `year`, `yr`, `yrs`, `y` -- defined as 365.25 days /// /// # Examples /// /// ``` /// use std::time::Duration; /// use humantime::parse_duration; /// /// assert_eq!(parse_duration("2h 37min"), Ok(Duration::new(9420, 0))); /// assert_eq!(parse_duration("32ms"), Ok(Duration::new(0, 32_000_000))); /// assert_eq!(parse_duration("4.2s"), Ok(Duration::new(4, 200_000_000))); /// ``` pub fn parse_duration(s: &str) -> Result { if s == "0" { return Ok(Duration::ZERO); } Parser { iter: s.chars(), src: s, } .parse() } /// Formats duration into a human-readable string /// /// Note: this format is guaranteed to have same value when using /// parse_duration, but we can change some details of the exact composition /// of the value. /// /// # Examples /// /// ``` /// use std::time::Duration; /// use humantime::format_duration; /// /// let val1 = Duration::new(9420, 0); /// assert_eq!(format_duration(val1).to_string(), "2h 37m"); /// let val2 = Duration::new(0, 32_000_000); /// assert_eq!(format_duration(val2).to_string(), "32ms"); /// ``` pub fn format_duration(val: Duration) -> FormattedDuration { FormattedDuration(val) } fn item_plural(f: &mut fmt::Formatter, started: &mut bool, name: &str, value: u64) -> fmt::Result { if value > 0 { if *started { f.write_str(" ")?; } write!(f, "{}{}", value, name)?; if value > 1 { f.write_str("s")?; } *started = true; } Ok(()) } fn item(f: &mut fmt::Formatter, started: &mut bool, name: &str, value: u32) -> fmt::Result { if value > 0 { if *started { f.write_str(" ")?; } write!(f, "{}{}", value, name)?; *started = true; } Ok(()) } impl FormattedDuration { /// Returns a reference to the [`Duration`][] that is being formatted. pub fn get_ref(&self) -> &Duration { &self.0 } } impl fmt::Display for FormattedDuration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { let secs = self.0.as_secs(); let nanos = self.0.subsec_nanos(); if secs == 0 && nanos == 0 { f.write_str("0s")?; return Ok(()); } let years = secs / 31_557_600; // 365.25d let ydays = secs % 31_557_600; let months = ydays / 2_630_016; // 30.44d let mdays = ydays % 2_630_016; let days = mdays / 86400; let day_secs = mdays % 86400; let hours = day_secs / 3600; let minutes = day_secs % 3600 / 60; let seconds = day_secs % 60; let millis = nanos / 1_000_000; let micros = nanos / 1000 % 1000; let nanosec = nanos % 1000; let started = &mut false; item_plural(f, started, "year", years)?; item_plural(f, started, "month", months)?; item_plural(f, started, "day", days)?; item(f, started, "h", hours as u32)?; item(f, started, "m", minutes as u32)?; item(f, started, "s", seconds as u32)?; item(f, started, "ms", millis)?; #[cfg(feature = "mu")] item(f, started, "µs", micros)?; #[cfg(not(feature = "mu"))] item(f, started, "us", micros)?; item(f, started, "ns", nanosec)?; Ok(()) } } #[cfg(test)] mod test { use std::time::Duration; use rand::Rng; use super::Error; use super::{format_duration, parse_duration}; #[test] #[allow(clippy::cognitive_complexity)] fn test_units() { assert_eq!(parse_duration("17nsec"), Ok(Duration::new(0, 17))); assert_eq!(parse_duration("17nanos"), Ok(Duration::new(0, 17))); assert_eq!(parse_duration("33ns"), Ok(Duration::new(0, 33))); assert_eq!(parse_duration("3usec"), Ok(Duration::new(0, 3000))); assert_eq!(parse_duration("78us"), Ok(Duration::new(0, 78000))); assert_eq!(parse_duration("163µs"), Ok(Duration::new(0, 163000))); assert_eq!(parse_duration("31msec"), Ok(Duration::new(0, 31_000_000))); assert_eq!(parse_duration("31millis"), Ok(Duration::new(0, 31_000_000))); assert_eq!(parse_duration("6ms"), Ok(Duration::new(0, 6_000_000))); assert_eq!(parse_duration("3000s"), Ok(Duration::new(3000, 0))); assert_eq!(parse_duration("300sec"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("300secs"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("50seconds"), Ok(Duration::new(50, 0))); assert_eq!(parse_duration("1second"), Ok(Duration::new(1, 0))); assert_eq!(parse_duration("100m"), Ok(Duration::new(6000, 0))); assert_eq!(parse_duration("12min"), Ok(Duration::new(720, 0))); assert_eq!(parse_duration("12mins"), Ok(Duration::new(720, 0))); assert_eq!(parse_duration("1minute"), Ok(Duration::new(60, 0))); assert_eq!(parse_duration("7minutes"), Ok(Duration::new(420, 0))); assert_eq!(parse_duration("2h"), Ok(Duration::new(7200, 0))); assert_eq!(parse_duration("7hr"), Ok(Duration::new(25200, 0))); assert_eq!(parse_duration("7hrs"), Ok(Duration::new(25200, 0))); assert_eq!(parse_duration("1hour"), Ok(Duration::new(3600, 0))); assert_eq!(parse_duration("24hours"), Ok(Duration::new(86400, 0))); assert_eq!(parse_duration("1day"), Ok(Duration::new(86400, 0))); assert_eq!(parse_duration("2days"), Ok(Duration::new(172_800, 0))); assert_eq!(parse_duration("365d"), Ok(Duration::new(31_536_000, 0))); assert_eq!(parse_duration("1week"), Ok(Duration::new(604_800, 0))); assert_eq!(parse_duration("7weeks"), Ok(Duration::new(4_233_600, 0))); assert_eq!( parse_duration("104wks"), Ok(Duration::new(2 * 31_449_600, 0)) ); assert_eq!(parse_duration("100wk"), Ok(Duration::new(60_480_000, 0))); assert_eq!(parse_duration("52w"), Ok(Duration::new(31_449_600, 0))); assert_eq!(parse_duration("1month"), Ok(Duration::new(2_630_016, 0))); assert_eq!( parse_duration("3months"), Ok(Duration::new(3 * 2_630_016, 0)) ); assert_eq!(parse_duration("12M"), Ok(Duration::new(31_560_192, 0))); assert_eq!(parse_duration("1year"), Ok(Duration::new(31_557_600, 0))); assert_eq!( parse_duration("7years"), Ok(Duration::new(7 * 31_557_600, 0)) ); assert_eq!( parse_duration("15yrs"), Ok(Duration::new(15 * 31_557_600, 0)) ); assert_eq!( parse_duration("10yr"), Ok(Duration::new(10 * 31_557_600, 0)) ); assert_eq!(parse_duration("17y"), Ok(Duration::new(536_479_200, 0))); } #[test] fn test_fractional_bad_input() { assert!(matches!( parse_duration("1.s"), Err(Error::InvalidCharacter(_)) )); assert!(matches!( parse_duration("1..s"), Err(Error::InvalidCharacter(_)) )); assert!(matches!( parse_duration(".1s"), Err(Error::NumberExpected(_)) )); assert!(matches!(parse_duration("."), Err(Error::NumberExpected(_)))); assert_eq!( parse_duration("0.000123456789s"), Err(Error::NumberOverflow) ); } #[test] fn test_fractional_units() { // nanos for input in &["17.5nsec", "5.1nanos", "0.0005ns"] { let bad_ns_frac = parse_duration(input); assert!( matches!(bad_ns_frac, Err(Error::NumberOverflow)), "fractions of nanoseconds should fail, but got {bad_ns_frac:?}" ); } // micros assert_eq!(parse_duration("3.1usec"), Ok(Duration::new(0, 3100))); assert_eq!(parse_duration("3.1us"), Ok(Duration::new(0, 3100))); assert_eq!(parse_duration("3.01us"), Ok(Duration::new(0, 3010))); assert_eq!(parse_duration("3.001us"), Ok(Duration::new(0, 3001))); for input in &["3.0001us", "0.0001us", "0.123456us"] { let bad_ms_frac = parse_duration(input); assert!( matches!(bad_ms_frac, Err(Error::NumberOverflow)), "too small fractions of microseconds should fail, but got {bad_ms_frac:?}" ); } // millis assert_eq!(parse_duration("31.1msec"), Ok(Duration::new(0, 31_100_000))); assert_eq!( parse_duration("31.1millis"), Ok(Duration::new(0, 31_100_000)) ); assert_eq!(parse_duration("31.1ms"), Ok(Duration::new(0, 31_100_000))); assert_eq!(parse_duration("31.01ms"), Ok(Duration::new(0, 31_010_000))); assert_eq!(parse_duration("31.001ms"), Ok(Duration::new(0, 31_001_000))); assert_eq!( parse_duration("31.0001ms"), Ok(Duration::new(0, 31_000_100)) ); assert_eq!( parse_duration("31.00001ms"), Ok(Duration::new(0, 31_000_010)) ); assert_eq!( parse_duration("31.000001ms"), Ok(Duration::new(0, 31_000_001)) ); assert!(matches!( parse_duration("31.0000001ms"), Err(Error::NumberOverflow) )); // seconds assert_eq!(parse_duration("300.0sec"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("300.0secs"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("300.0seconds"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("300.0s"), Ok(Duration::new(300, 0))); assert_eq!(parse_duration("0.0s"), Ok(Duration::new(0, 0))); assert_eq!(parse_duration("0.2s"), Ok(Duration::new(0, 200_000_000))); assert_eq!(parse_duration("1.2s"), Ok(Duration::new(1, 200_000_000))); assert_eq!(parse_duration("1.02s"), Ok(Duration::new(1, 20_000_000))); assert_eq!(parse_duration("1.002s"), Ok(Duration::new(1, 2_000_000))); assert_eq!(parse_duration("1.0002s"), Ok(Duration::new(1, 200_000))); assert_eq!(parse_duration("1.00002s"), Ok(Duration::new(1, 20_000))); assert_eq!(parse_duration("1.000002s"), Ok(Duration::new(1, 2_000))); assert_eq!(parse_duration("1.0000002s"), Ok(Duration::new(1, 200))); assert_eq!(parse_duration("1.00000002s"), Ok(Duration::new(1, 20))); assert_eq!(parse_duration("1.000000002s"), Ok(Duration::new(1, 2))); assert_eq!( parse_duration("1.123456789s"), Ok(Duration::new(1, 123_456_789)) ); assert!(matches!( parse_duration("1.0000000002s"), Err(Error::NumberOverflow) )); assert!(matches!( parse_duration("0.0000000002s"), Err(Error::NumberOverflow) )); // minutes assert_eq!(parse_duration("100.0m"), Ok(Duration::new(6000, 0))); assert_eq!(parse_duration("12.1min"), Ok(Duration::new(726, 0))); assert_eq!(parse_duration("12.1mins"), Ok(Duration::new(726, 0))); assert_eq!(parse_duration("1.5minute"), Ok(Duration::new(90, 0))); assert_eq!(parse_duration("1.5minutes"), Ok(Duration::new(90, 0))); // hours assert_eq!(parse_duration("2.0h"), Ok(Duration::new(7200, 0))); assert_eq!(parse_duration("2.0hr"), Ok(Duration::new(7200, 0))); assert_eq!(parse_duration("2.0hrs"), Ok(Duration::new(7200, 0))); assert_eq!(parse_duration("2.0hours"), Ok(Duration::new(7200, 0))); assert_eq!(parse_duration("2.5h"), Ok(Duration::new(9000, 0))); assert_eq!(parse_duration("0.5h"), Ok(Duration::new(1800, 0))); // days assert_eq!( parse_duration("1.5day"), Ok(Duration::new(86400 + 86400 / 2, 0)) ); assert_eq!( parse_duration("1.5days"), Ok(Duration::new(86400 + 86400 / 2, 0)) ); assert_eq!( parse_duration("1.5d"), Ok(Duration::new(86400 + 86400 / 2, 0)) ); assert!(matches!( parse_duration("0.00000005d"), Err(Error::NumberOverflow) )); } #[test] fn test_fractional_combined() { assert_eq!(parse_duration("7.120us 3ns"), Ok(Duration::new(0, 7123))); assert_eq!(parse_duration("7.123us 4ns"), Ok(Duration::new(0, 7127))); assert_eq!( parse_duration("1.234s 789ns"), Ok(Duration::new(1, 234_000_789)) ); assert_eq!( parse_duration("1.234s 0.789us"), Ok(Duration::new(1, 234_000_789)) ); assert_eq!( parse_duration("1.234567s 0.789us"), Ok(Duration::new(1, 234_567_789)) ); assert_eq!( parse_duration("1.234s 1.345ms 1.678us 1ns"), Ok(Duration::new(1, 235_346_679)) ); assert_eq!( parse_duration("1.234s 0.345ms 0.678us 0ns"), Ok(Duration::new(1, 234_345_678)) ); assert_eq!( parse_duration("1.234s0.345ms0.678us0ns"), Ok(Duration::new(1, 234_345_678)) ); } #[test] fn allow_0_with_no_unit() { assert_eq!(parse_duration("0"), Ok(Duration::new(0, 0))); } #[test] fn test_combo() { assert_eq!( parse_duration("20 min 17 nsec "), Ok(Duration::new(1200, 17)) ); assert_eq!(parse_duration("2h 15m"), Ok(Duration::new(8100, 0))); } #[test] fn all_86400_seconds() { for second in 0..86400 { // scan leap year and non-leap year let d = Duration::new(second, 0); assert_eq!(d, parse_duration(&format_duration(d).to_string()).unwrap()); } } #[test] fn random_second() { for _ in 0..10000 { let sec = rand::rng().random_range(0..253_370_764_800); let d = Duration::new(sec, 0); assert_eq!(d, parse_duration(&format_duration(d).to_string()).unwrap()); } } #[test] fn random_any() { for _ in 0..10000 { let sec = rand::rng().random_range(0..253_370_764_800); let nanos = rand::rng().random_range(0..1_000_000_000); let d = Duration::new(sec, nanos); assert_eq!(d, parse_duration(&format_duration(d).to_string()).unwrap()); } } #[test] fn test_overlow() { // Overflow on subseconds is earlier because of how we do conversion // we could fix it, but I don't see any good reason for this assert_eq!( parse_duration("100000000000000000000ns"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("100000000000000000us"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("100000000000000ms"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("100000000000000000000s"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("10000000000000000000m"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("1000000000000000000h"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("100000000000000000d"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("10000000000000000w"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("1000000000000000M"), Err(Error::NumberOverflow) ); assert_eq!( parse_duration("10000000000000y"), Err(Error::NumberOverflow) ); } #[test] fn test_nice_error_message() { assert_eq!( parse_duration("123").unwrap_err().to_string(), "time unit needed, for example 123sec or 123ms" ); assert_eq!( parse_duration("10 months 1").unwrap_err().to_string(), "time unit needed, for example 1sec or 1ms" ); assert_eq!( parse_duration("10nights").unwrap_err().to_string(), "unknown time unit \"nights\", supported units: \ ns, us/µs, ms, sec, min, hours, days, weeks, months, \ years (and few variations)" ); } #[cfg(feature = "mu")] #[test] fn test_format_micros() { assert_eq!( format_duration(Duration::from_micros(123)).to_string(), "123µs" ); } #[cfg(not(feature = "mu"))] #[test] fn test_format_micros() { assert_eq!( format_duration(Duration::from_micros(123)).to_string(), "123us" ); } #[test] fn test_error_cases() { assert_eq!( parse_duration("\0").unwrap_err().to_string(), "expected number at 0" ); assert_eq!( parse_duration("\r").unwrap_err().to_string(), "value was empty" ); assert_eq!( parse_duration("1~").unwrap_err().to_string(), "invalid character at 1" ); assert_eq!( parse_duration("1Nå").unwrap_err().to_string(), "invalid character at 2" ); assert_eq!(parse_duration("222nsec221nanosmsec7s5msec572s").unwrap_err().to_string(), "unknown time unit \"nanosmsec\", supported units: ns, us/µs, ms, sec, min, hours, days, weeks, months, years (and few variations)"); } } humantime-2.3.0/src/lib.rs000064400000000000000000000023211046102023000135160ustar 00000000000000//! Human-friendly time parser and formatter //! //! Features: //! //! * Parses durations in free form like `15days 2min 2s` //! * Formats durations in similar form `2years 2min 12us` //! * Parses and formats timestamp in `rfc3339` format: `2018-01-01T12:53:00Z` //! * Parses timestamps in a weaker format: `2018-01-01 12:53:00` //! //! Timestamp parsing/formatting is super-fast because format is basically //! fixed. //! //! See [humantime-serde] for serde integration (previous crate [serde-humantime] looks unmaintained). //! //! [serde-humantime]: https://docs.rs/serde-humantime/0.1.1/serde_humantime/ //! [humantime-serde]: https://docs.rs/humantime-serde #![forbid(unsafe_code)] #![warn(missing_debug_implementations, missing_docs, unreachable_pub)] mod date; mod duration; mod wrapper; pub use self::date::Rfc3339Timestamp; pub use self::date::{ format_rfc3339, format_rfc3339_micros, format_rfc3339_millis, format_rfc3339_nanos, format_rfc3339_seconds, }; pub use self::date::{parse_rfc3339, parse_rfc3339_weak, Error as TimestampError}; pub use self::duration::{format_duration, FormattedDuration}; pub use self::duration::{parse_duration, Error as DurationError}; pub use self::wrapper::{Duration, Timestamp}; humantime-2.3.0/src/wrapper.rs000064400000000000000000000056471046102023000144460ustar 00000000000000use std::fmt; use std::ops::Deref; use std::str::FromStr; use std::time::{Duration as StdDuration, SystemTime}; use crate::date::{self, format_rfc3339, parse_rfc3339_weak}; use crate::duration::{self, format_duration, parse_duration}; /// A wrapper for duration that has `FromStr` implementation /// /// This is useful if you want to use it somewhere where `FromStr` is /// expected. /// /// See `parse_duration` for the description of the format. /// /// # Example /// /// ``` /// use std::time::Duration; /// let x: Duration; /// x = "12h 5min 2ns".parse::().unwrap().into(); /// assert_eq!(x, Duration::new(12*3600 + 5*60, 2)) /// ``` /// #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Default)] pub struct Duration(StdDuration); /// A wrapper for SystemTime that has `FromStr` implementation /// /// This is useful if you want to use it somewhere where `FromStr` is /// expected. /// /// See `parse_rfc3339_weak` for the description of the format. The "weak" /// format is used as it's more pemissive for human input as this is the /// expected use of the type (e.g. command-line parsing). /// /// # Example /// /// ``` /// use std::time::SystemTime; /// let x: SystemTime; /// x = "2018-02-16T00:31:37Z".parse::().unwrap().into(); /// assert_eq!(humantime::format_rfc3339(x).to_string(), "2018-02-16T00:31:37Z"); /// ``` /// #[derive(Debug, Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] pub struct Timestamp(SystemTime); impl AsRef for Duration { fn as_ref(&self) -> &StdDuration { &self.0 } } impl Deref for Duration { type Target = StdDuration; fn deref(&self) -> &StdDuration { &self.0 } } impl From for StdDuration { fn from(val: Duration) -> Self { val.0 } } impl From for Duration { fn from(dur: StdDuration) -> Duration { Duration(dur) } } impl FromStr for Duration { type Err = duration::Error; fn from_str(s: &str) -> Result { parse_duration(s).map(Duration) } } impl fmt::Display for Duration { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { format_duration(self.0).fmt(f) } } impl AsRef for Timestamp { fn as_ref(&self) -> &SystemTime { &self.0 } } impl Deref for Timestamp { type Target = SystemTime; fn deref(&self) -> &SystemTime { &self.0 } } impl From for SystemTime { fn from(val: Timestamp) -> Self { val.0 } } impl From for Timestamp { fn from(dur: SystemTime) -> Timestamp { Timestamp(dur) } } impl FromStr for Timestamp { type Err = date::Error; fn from_str(s: &str) -> Result { parse_rfc3339_weak(s).map(Timestamp) } } impl fmt::Display for Timestamp { fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { format_rfc3339(self.0).fmt(f) } }