What changed, and why it matters
This commit updates two helper Rust libraries (anyhow and time) inside the BitBox02 firmware source tree because those libraries had published security advisories (RustSec). The change is a routine dependency upgrade, not a fix for a new bug in BitBox's own code. It mostly swaps in newer, already-public library versions and refreshes the vendored copies and lockfiles. The security benefit is removing known-vulnerable dependency versions from the build, but the commit itself does not introduce or patch any exploit in BitBox02 firmware.
Verify that the new dependency versions resolve the cited RustSec advisories (e.g., RUSTSEC-2024-0024 for time, and any relevant anyhow advisory) and that the firmware still builds and passes its test suite. Continue monitoring RustSec for future advisories on these crates.
Security signals we found
Dependency update triggered by RustSec advisories
Vendored third-party crate source replaced with newer versions
Cargo.lock files updated to reflect new crate versions
No BitBox02 application logic changed
Crypto dependency graph explicitly unchanged
Evidence from the diff
The commit upgrades the pinned/vendored Rust crates anyhow (1.0.31 → 1.0.104) and time (with its support crates time-core, deranged, num-conv) and updates the Cargo.lock files in src/rust, src/rust/util, and the simulator test crates. The commit message explicitly states the motivation: the pinned versions of time and anyhow have RustSec advisories. The diff is almost entirely vendored upstream source files, checksums, and lockfile entries. No BitBox02 application code is modified. The crypto dependency graph is intentionally left unchanged. This is a supply-chain hygiene change rather than a direct vulnerability patch.
Changed components
external/vendor/anyhowexternal/vendor/timeexternal/vendor/time-coreexternal/vendor/derangedexternal/vendor/num-convsrc/rust/Cargo.locksrc/rust/util/Cargo.tomltest/simulator-graphical/Cargo.locktest/simulator-graphical-bb03/Cargo.lockInspect captured patch +44092 / −6724
### external/vendor/anyhow/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"4b1c1dd8b11d4fc1c9a338127acda7b1e2f4658e77e7e274be83d1e8fce985bd",".github/workflows/ci.yml":"79af432ca1390932bcc7f238508800c6ef7ddc7f40e93436ec32f65a49d14f81","Cargo.toml":"21a48fbff0c6c0c47cf7af970348c3701cc8220e04a191d3a00def58250317f1","Cargo.toml.orig":"c0cc2a5b264f17842939698336cfe01003428ccbdeeb9b9465b54cd95b412c2c","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"0d9c5facc3db17123752af8c3dbcdb9bb3785c8ed046b27de26669e4e87f131c","build.rs":"d8b58acc2cd88d627763135b3b25b46f276e2672ef740efb7fb5b1404fb230d8","src/backtrace.rs":"a82a8ffae2c68ee385dc78d8ec8cb6f3351234f0ad6af7e87df2371593e0f6aa","src/chain.rs":"1627608ce95c3484d26e1742a1b8b533b74c6159916b717bacffae3ae53731f9","src/context.rs":"f2be36af9588c924ed087bcb7bd681d330889e54b8f98cdc2aba93512a28762e","src/error.rs":"2c6a51880c7379265f7f7b6557e7bed808ff0f3267337a0c77dbbc1d2c4662e7","src/fmt.rs":"dd0593a2e20487165ec5889e72cc8833eee4fa69ac258420428eede8e17f2213","src/kind.rs":"8481a8b7835eebb3859a8c32c217bf9c73543cfc62e3916b98d39af8b063125c","src/lib.rs":"9ca1763c7964b9a547456121b2e5af099a0622e369e8c991e9cd46ad793c08ce","src/macros.rs":"77722190b58a6106b21aefd3b5d4f136a076afcdbc0fae21562d99e2c22912e1","src/wrapper.rs":"1229beca67dbd95ca77c9ecce282272acc55276c267c58cb73a75388b4693dda","tests/common/mod.rs":"f9088c2d7afafa64ff730b629272045b776bfafc2f5957508242da630635f2e1","tests/compiletest.rs":"0a52a44786aea1c299c695bf948b2ed2081e4cc344e5c2cadceab4eb03d0010d","tests/drop/mod.rs":"464bc1ddeae307eac906928286ec3edb77057c5c1302e02150d3649e2b861f1a","tests/test_autotrait.rs":"981e792db353be2f14c7a1cabe43b5f1329c168cb7679077cc2be786a0920d48","tests/test_backtrace.rs":"0e50edbb33b6bd07ba89ff3db72fb7c688ba2a4371fccdbbb20309ab02948b6a","tests/test_boxed.rs":"98a45325b1e86d4c5d3094ab99cd1ada1f771c505d2d7322f0afcbe7bdb71cfa","tests/test_chain.rs":"f28efeae7395d1c395e6f1a647b4199c25a00410ade45248c145c6fcf2fb448a","tests/test_context.rs":"f82c915b182df1a604a4cd558a03b1a821414983d6f6af6822398104cea70676","tests/test_convert.rs":"62840be1ee8022ba5e8c0d3fc1752a1526b2c47d4cceecff2b86790524c3b3ea","tests/test_downcast.rs":"253d6f54e554965023b378b037827ec6289c4779a7a7c12706e19c2731d219fe","tests/test_fmt.rs":"17572596f257aac9aa2ec4620e292ca6a954128b94772bb948399fab53832e70","tests/test_macros.rs":"c7d3d5e0b756f59d4858035025fb341d031369c88486fd9f961ee16bae6c78bf","tests/test_repr.rs":"dbb9b04ddbe1ab31eb5331ea69f05bb3a147299da2275a3d4dcc92947b5591b9","tests/test_source.rs":"b80723cf635a4f8c4df21891b34bfab9ed2b2aa407e7a2f826d24e334cd5f88e","tests/ui/no-impl.rs":"fab6cbf2f6ea510b86f567dfb3b7c31250a9fd71ae5d110dbb9188be569ec593","tests/ui/no-impl.stderr":"7c2c3f46c266a437300591f10be330f937ac6a0a2213ed5030a9fbc895e2d100"},"package":"85bb70cc08ec97ca5450e6eba421deeea5f172c0fc61f78b5357b2a8e8be195f"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"9f5691d9965b8418415cfe8872a667089542a23a1d746bad08476ccda5e6269c",".github/FUNDING.yml":"b017158736b3c9751a2d21edfce7fe61c8954e2fced8da8dd3013c2f3e295bd9",".github/workflows/ci.yml":"40e9434834e8ba84207ef6a401da6b154fa4220a4847230284d6aae63d8a39ac","Cargo.lock":"c7b6dd9adcad0b26ce812afdb8539e1d93994a0735a90eb0dd7ce8535e3e7ffa","Cargo.toml":"249789761ff37004dda628765f0c9e60a61fa43cbbd2d364789dca0c789eeb59","Cargo.toml.orig":"1b03bd9d21f63835f0449cf1456e6143a15efd6b7803bc5b7787643db62b6f53","LICENSE-APACHE":"62c7a1e35f56406896d7aa7ca52d0cc0d272ac022b5d2796e7d6905db8a3636a","LICENSE-MIT":"23f18e03dc49df91622fe2a76176497404e46ced8a715d9d2b67a7446571cca3","README.md":"86f5b88c45b2b9b7eefa0ad66c11918a607319cad683f01123ff38db68b4a49b","build.rs":"89d1baedcff59822ed692d3a33f131c211a213bdec33c83f68b54110d9c64223","rust-toolchain.toml":"6bbb61302978c736b2da03e4fb40e3beab908f85d533ab46fd541e637b5f3e0f","src/backtrace.rs":"621ec5d9e2f31883d0384ae00fc536d1ea359da989d2e0d1be1ba03482c8f920","src/chain.rs":"85af447405f075633fab186b7f1c94d7f33a36474f239c50a961b2d6197d5426","src/context.rs":"8b106e43df7a66fbc3e85b87a4d7f8a780d43d3ee0cd1ae86c571950ecf07d13","src/ensure.rs":"709524741c8f9365e01cb36fc2349a8724513de02cf9e253809a93af8d6a7b6e","src/error.rs":"2a78ee4e5f8d6b4476c761f77473362b9ed12f5402e4701001e7d04d628ba030","src/fmt.rs":"2cca8c7f3cab636fdb17433ca2b1fda0e8d28bb20d4647b87c991dacd8f06cdf","src/kind.rs":"ddcabf15b3b47a4ef16ed361c45cc0cc82e7be90622995ff6c04b3fec78bb04f","src/lib.rs":"ea7f436f6bf4b356ff30ec922b50b40ead0ade28b123341a8de7f310311fd44c","src/macros.rs":"696e6a8aac614525a29697aedc7561e98beccf3d43aed3ada1cc93daa99da8ba","src/nightly.rs":"1c0aeadfcdbe22f8f807b185dec1a7448c378bddb37689714944b60473b58049","src/ptr.rs":"a114639d26f4feca7e186106342334cdf2e2176f892149aa331ace72e5d81410","src/wrapper.rs":"079218e1d8c9374f52311b1c7971f7fbdeba4d7af1b0749c0d535010f1232697","tests/common/mod.rs":"f9088c2d7afafa64ff730b629272045b776bfafc2f5957508242da630635f2e1","tests/compiletest.rs":"4e381aa8ca3eabb7ac14d1e0c3700b3223e47640547a6988cfa13ad68255f60f","tests/drop/mod.rs":"08c3e553c1cc0d2dbd936fc45f4b5b1105057186affd6865e8d261e05f0f0646","tests/test_autotrait.rs":"ba9bc18416115cb48fd08675a3e7fc89584de7926dad6b2be6645dc13d5931df","tests/test_backtrace.rs":"60afdd7ee5850dc22625ff486fe41c47fd322db874a93c4871ddfed2bf603930","tests/test_boxed.rs":"6b26db0e2eb72afe9af7352ea820837aab90f8d486294616dd5dc34c1b94038c","tests/test_chain.rs":"3a8a8d7569913bd98c0e27c69d0bda35101e7fde7c056ed57cdd8ed018e4cbcb","tests/test_context.rs":"a4cb7d9a6d488d902eb5ac516d2b5e4135f46caaa2d151580ed9ba83c2a90b57","tests/test_convert.rs":"7e7a8b4772a427a911014ac4d1083f9519000e786177f898808980dd9bdfde61","tests/test_downcast.rs":"797e69a72d125758c4c4897e5dc776d549d52cc9a6a633e0a33193f588a62b88","tests/test_ensure.rs":"6ef8823153d6aba31dda8438b9e51984e6b7377d585addbaf87162b39d733cd9","tests/test_ffi.rs":"c6e6bf39e6b2cf9aacea12e3e4da4e1e1edb7fc906d231e5baf45812a08de3c4","tests/test_fmt.rs":"0e49b48f08e4faaf03e2f202e1efc5250018876c4e1b01b8379d7a38ae8df870","tests/test_macros.rs":"3eb6ec9024cf8812da48de35b733d5a69ed942907fb4e6c67ec471cd4bcef562","tests/test_repr.rs":"034dee888abd08741e11ac2e95ef4fcb2ab3943d0a76e8e976db404658e1a252","tests/test_source.rs":"b80723cf635a4f8c4df21891b34bfab9ed2b2aa407e7a2f826d24e334cd5f88e","tests/ui/chained-comparison.rs":"6504b03d95b5acc232a7f4defc9f343b2be6733bf475fa0992e8e6545b912bd4","tests/ui/chained-comparison.stderr":"7f1d0a8c251b0ede2d30b3087ec157fc660945c97a642c4a5acf5a14ec58de34","tests/ui/empty-ensure.rs":"ab5bf37c846a0d689f26ce9257a27228411ed64154f9c950f1602d88a355d94b","tests/ui/empty-ensure.stderr":"315782f5f4246290fe190e3767b22c3dcaffaabc19c5ace0373537d53e765278","tests/ui/ensure-nonbool.rs":"7e57cb93fbcd82959b36586ed6bd2ad978b051fe5facd5274651fde6b1600905","tests/ui/ensure-nonbool.stderr":"e3dfbaedd66fdfc524f8462305760c7978c4268ca7e1cd872d7ecde5d3b455bd","tests/ui/must-use.rs":"fb59860b43f673bf4a430a6036ba463e95028844d8dd4243cfe5ebc7f2be582f","tests/ui/must-use.stderr":"8b1cb7fca632396a22bb3a642f2df3ab62b3e9a87951e20fa40bdd548d002162","tests/ui/no-impl.rs":"fab6cbf2f6ea510b86f567dfb3b7c31250a9fd71ae5d110dbb9188be569ec593","tests/ui/no-impl.stderr":"c472de95483aa234728c7f57039c88fc3456892838329976a75cd167c3c172c9","tests/ui/temporary-value.rs":"4dcc96271b2403e6372cf4cfc813445e5ce4365fc6e156b6bc38274098499a70","tests/ui/temporary-value.stderr":"7f99cd914d2d423d77274e1b859b5ad151cde8224e42687e50622c26118fd47f","tests/ui/wrong-interpolation.rs":"9c44d4674c2dccd27b9dedd03341346ec02d993b41793ee89b5755202e7e367e","tests/ui/wrong-interpolation.stderr":"301e60e2eb9401782c7dc0b3580613a4cb2aafd4cc8065734a630a62e1161aa5"},"package":"330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"}
\ No newline at end of file
### external/vendor/anyhow/.cargo_vcs_info.json
@@ -1,5 +1,6 @@
{
"git": {
- "sha1": "144763cf9958ac32ce56a8c107c2120a66f6e39d"
- }
-}
+ "sha1": "1dbe1862aae650423e3361fbd20b7d17c5109cc3"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
### external/vendor/anyhow/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: dtolnay
### external/vendor/anyhow/.github/workflows/ci.yml
@@ -3,44 +3,144 @@ name: CI
on:
push:
pull_request:
+ workflow_dispatch:
schedule: [cron: "40 1 * * *"]
+permissions:
+ contents: read
+
+env:
+ RUSTFLAGS: -Dwarnings
+
jobs:
+ pre_ci:
+ uses: dtolnay/.github/.github/workflows/pre_ci.yml@master
+
test:
name: Rust ${{matrix.rust}}
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
- rust: [nightly, beta, stable]
+ rust: [nightly, beta, stable, 1.85.0]
+ timeout-minutes: 45
steps:
- - uses: actions/checkout@v2
+ - uses: actions/checkout@v7
- uses: dtolnay/rust-toolchain@master
with:
toolchain: ${{matrix.rust}}
+ components: rust-src
+ - name: Enable type layout randomization
+ run: echo RUSTFLAGS=${RUSTFLAGS}\ -Zrandomize-layout >> $GITHUB_ENV
+ if: matrix.rust == 'nightly'
+ - name: Enable nightly-only tests
+ run: echo RUSTFLAGS=${RUSTFLAGS}\ --cfg=anyhow_nightly_testing >> $GITHUB_ENV
+ if: matrix.rust == 'nightly'
- run: cargo test
- run: cargo check --no-default-features
+ - run: cargo check
+ - uses: actions/upload-artifact@v7
+ if: matrix.rust == 'nightly' && always()
+ with:
+ name: Cargo.lock
+ path: Cargo.lock
+ continue-on-error: true
- nostd:
- name: Rust 1.36.0
+ build:
+ name: Rust ${{matrix.rust}}
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
+ strategy:
+ fail-fast: false
+ matrix:
+ rust: [1.68.0]
+ timeout-minutes: 45
steps:
- - uses: actions/checkout@v2
- - uses: dtolnay/rust-toolchain@1.36.0
- - run: cargo check --no-default-features
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@master
+ with:
+ toolchain: ${{matrix.rust}}
+ components: rust-src
+ - run: cargo check --manifest-path tests/crate/Cargo.toml
+ - run: cargo check --manifest-path tests/crate/Cargo.toml --no-default-features
- msrv:
- name: Rust 1.34.0
+ minimal:
+ name: Minimal versions
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
runs-on: ubuntu-latest
+ timeout-minutes: 45
steps:
- - uses: actions/checkout@v2
- - uses: dtolnay/rust-toolchain@1.34.0
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@nightly
+ - run: cargo generate-lockfile -Z minimal-versions
+ - run: cargo check --locked
+
+ windows:
+ name: Windows
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
+ runs-on: windows-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@stable
+ with:
+ components: rust-src
- run: cargo check
+ doc:
+ name: Documentation
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ env:
+ RUSTDOCFLAGS: -Dwarnings
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@nightly
+ with:
+ components: rust-src
+ - uses: dtolnay/install@cargo-docs-rs
+ - run: cargo docs-rs
+
clippy:
name: Clippy
runs-on: ubuntu-latest
+ if: github.event_name != 'pull_request'
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@nightly
+ with:
+ components: clippy, rust-src
+ - run: cargo clippy --tests -- -Dclippy::all -Dclippy::pedantic
+
+ miri:
+ name: Miri
+ needs: pre_ci
+ if: needs.pre_ci.outputs.continue
+ runs-on: ubuntu-latest
+ timeout-minutes: 45
+ steps:
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@miri
+ - run: cargo miri setup
+ - run: cargo miri test
+ env:
+ MIRIFLAGS: -Zmiri-strict-provenance
+
+ outdated:
+ name: Outdated
+ runs-on: ubuntu-latest
+ if: github.event_name != 'pull_request'
+ timeout-minutes: 45
steps:
- - uses: actions/checkout@v2
- - uses: dtolnay/rust-toolchain@clippy
- - run: cargo clippy -- -Dclippy::all
+ - uses: actions/checkout@v7
+ - uses: dtolnay/rust-toolchain@stable
+ - uses: dtolnay/install@cargo-outdated
+ - run: cargo outdated --workspace --exit-code 1
### external/vendor/anyhow/Cargo.lock
@@ -0,0 +1,355 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "anyhow"
+version = "1.0.104"
+dependencies = [
+ "futures",
+ "rustversion",
+ "syn 3.0.0",
+ "thiserror",
+ "trybuild",
+]
+
+[[package]]
+name = "dissimilar"
+version = "1.0.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "aeda16ab4059c5fd2a83f2b9c9e9c981327b18aa8e3b313f7e6563799d4f093e"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "futures"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a88cf1f829d945f548cf8fec32c61b1f202b6d93b45848602fc02af4b12ad218"
+dependencies = [
+ "futures-channel",
+ "futures-core",
+ "futures-io",
+ "futures-sink",
+ "futures-task",
+ "futures-util",
+]
+
+[[package]]
+name = "futures-channel"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "262590f4fe6afeb0bc83be1daa64e52657fe185690a958af7f3ad0e92085c5ae"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+]
+
+[[package]]
+name = "futures-core"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2cd50c473c80f6d7c3670a752354b8e569b1a7cbfdc0419ec88e5edad85e0dc7"
+
+[[package]]
+name = "futures-io"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4577ecaa3c4f96589d473f679a71b596316f6641bc350038b962a5daf0085d7a"
+
+[[package]]
+name = "futures-sink"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e34418ac499d6305c2fb5ad0ed2f6ac998c5f8ca209b4510f7f94242c647e307"
+
+[[package]]
+name = "futures-task"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b231ed28831efb4a61a08580c4bc233ec56bc009f4cd8f52da2c3cb97df0c109"
+
+[[package]]
+name = "futures-util"
+version = "0.3.33"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a77a90a256fce34da66415271e30f94ee91c57b04b8a2c042d9cf3220179deaa"
+dependencies = [
+ "futures-core",
+ "futures-sink",
+ "futures-task",
+ "pin-project-lite",
+]
+
+[[package]]
+name = "glob"
+version = "0.3.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
+
+[[package]]
+name = "hashbrown"
+version = "0.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "indexmap"
+version = "2.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[package]]
+name = "memchr"
+version = "2.8.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"
+
+[[package]]
+name = "pin-project-lite"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
+
+[[package]]
+name = "proc-macro2"
+version = "1.0.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.46"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "rustversion"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"
+
+[[package]]
+name = "serde"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
+dependencies = [
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_derive"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.150"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "serde_spanned"
+version = "1.1.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6662b5879511e06e8999a8a235d848113e942c9124f211511b16466ee2995f26"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.119"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "872831b642d1a07999a962a351ed35b955ea2cfc8f3862091e2a240a84f17297"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "syn"
+version = "3.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f2fac314a64dc9a36e61a9eb4261a5e9bbfbc922b27e518af97bc32b926cf967"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "target-triple"
+version = "1.0.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c3a6bfce3d99adfa72d24750a61f782f3036a81e7f86d8841ee1326deaebd171"
+
+[[package]]
+name = "termcolor"
+version = "1.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755"
+dependencies = [
+ "winapi-util",
+]
+
+[[package]]
+name = "thiserror"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
+dependencies = [
+ "thiserror-impl",
+]
+
+[[package]]
+name = "thiserror-impl"
+version = "2.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "syn 2.0.119",
+]
+
+[[package]]
+name = "toml"
+version = "1.1.3+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "53c96ecdfa941c8fc4fcaed14f99ada8ebed502eef533015095a07e3301d4c3c"
+dependencies = [
+ "indexmap",
+ "serde_core",
+ "serde_spanned",
+ "toml_datetime",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
+]
+
+[[package]]
+name = "toml_datetime"
+version = "1.1.1+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3165f65f62e28e0115a00b2ebdd37eb6f3b641855f9d636d3cd4103767159ad7"
+dependencies = [
+ "serde_core",
+]
+
+[[package]]
+name = "toml_parser"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526"
+dependencies = [
+ "winnow",
+]
+
+[[package]]
+name = "toml_writer"
+version = "1.1.2+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d56353a2a665ad0f41a421187180aab746c8c325620617ad883a99a1cbe66d2"
+
+[[package]]
+name = "trybuild"
+version = "1.0.118"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "06649c6f63d86604ba0c8950d5a1829fc9a17afd70fc6629f481d75b6a624c78"
+dependencies = [
+ "dissimilar",
+ "glob",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "target-triple",
+ "termcolor",
+ "toml",
+]
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "winapi-util"
+version = "0.1.11"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
+dependencies = [
+ "windows-sys",
+]
+
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
+[[package]]
+name = "windows-sys"
+version = "0.61.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
+dependencies = [
+ "windows-link",
+]
+
+[[package]]
+name = "winnow"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81"
+
+[[package]]
+name = "zmij"
+version = "1.0.23"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"
### external/vendor/anyhow/Cargo.toml
@@ -3,41 +3,127 @@
# 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
+# to registry (e.g., crates.io) dependencies.
#
-# If you believe there's an error in this file please file an
-# issue against the rust-lang/cargo repository. If you're
-# editing this file be aware that the upstream Cargo.toml
-# will likely look very different (and much more reasonable)
+# 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 = "2018"
+edition = "2021"
+rust-version = "1.68"
name = "anyhow"
-version = "1.0.31"
+version = "1.0.104"
authors = ["David Tolnay <dtolnay@gmail.com>"]
+build = "build.rs"
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "Flexible concrete Error type built on std::error::Error"
documentation = "https://docs.rs/anyhow"
readme = "README.md"
-categories = ["rust-patterns"]
+keywords = [
+ "error",
+ "error-handling",
+]
+categories = [
+ "rust-patterns",
+ "no-std",
+]
license = "MIT OR Apache-2.0"
repository = "https://github.com/dtolnay/anyhow"
+
[package.metadata.docs.rs]
-rustdoc-args = ["--cfg", "doc_cfg"]
targets = ["x86_64-unknown-linux-gnu"]
+rustdoc-args = [
+ "--generate-link-to-definition",
+ "--generate-macro-expansion",
+ "--extern-html-root-url=core=https://doc.rust-lang.org",
+ "--extern-html-root-url=alloc=https://doc.rust-lang.org",
+ "--extern-html-root-url=std=https://doc.rust-lang.org",
+]
+
+[features]
+backtrace = []
+default = ["std"]
+std = []
+
+[lib]
+name = "anyhow"
+path = "src/lib.rs"
+
+[[test]]
+name = "compiletest"
+path = "tests/compiletest.rs"
+
+[[test]]
+name = "test_autotrait"
+path = "tests/test_autotrait.rs"
+
+[[test]]
+name = "test_backtrace"
+path = "tests/test_backtrace.rs"
+
+[[test]]
+name = "test_boxed"
+path = "tests/test_boxed.rs"
+
+[[test]]
+name = "test_chain"
+path = "tests/test_chain.rs"
+
+[[test]]
+name = "test_context"
+path = "tests/test_context.rs"
+
+[[test]]
+name = "test_convert"
+path = "tests/test_convert.rs"
+
+[[test]]
+name = "test_downcast"
+path = "tests/test_downcast.rs"
+
+[[test]]
+name = "test_ensure"
+path = "tests/test_ensure.rs"
+
+[[test]]
+name = "test_ffi"
+path = "tests/test_ffi.rs"
+
+[[test]]
+name = "test_fmt"
+path = "tests/test_fmt.rs"
+
+[[test]]
+name = "test_macros"
+path = "tests/test_macros.rs"
+
+[[test]]
+name = "test_repr"
+path = "tests/test_repr.rs"
+
+[[test]]
+name = "test_source"
+path = "tests/test_source.rs"
+
[dev-dependencies.futures]
version = "0.3"
default-features = false
[dev-dependencies.rustversion]
-version = "1.0"
+version = "1.0.6"
+
+[dev-dependencies.syn]
+version = "3"
+features = ["full"]
[dev-dependencies.thiserror]
-version = "1.0"
+version = "2"
[dev-dependencies.trybuild]
-version = "1.0.19"
+version = "1.0.108"
features = ["diff"]
-
-[features]
-default = ["std"]
-std = []
### external/vendor/anyhow/Cargo.toml.orig
@@ -1,25 +1,36 @@
[package]
name = "anyhow"
-version = "1.0.31" # remember to update html_root_url
+version = "1.0.104"
authors = ["David Tolnay <dtolnay@gmail.com>"]
-edition = "2018"
-license = "MIT OR Apache-2.0"
+categories = ["rust-patterns", "no-std"]
description = "Flexible concrete Error type built on std::error::Error"
-repository = "https://github.com/dtolnay/anyhow"
documentation = "https://docs.rs/anyhow"
-readme = "README.md"
-categories = ["rust-patterns"]
+edition = "2021"
+keywords = ["error", "error-handling"]
+license = "MIT OR Apache-2.0"
+repository = "https://github.com/dtolnay/anyhow"
+rust-version = "1.68"
[features]
default = ["std"]
std = []
+# THIS HAS NO EFFECT. This feature remains to preserve compatibility with the
+# old `backtrace` optional dependency that this crate used to have.
+backtrace = []
[dev-dependencies]
futures = { version = "0.3", default-features = false }
-rustversion = "1.0"
-thiserror = "1.0"
-trybuild = { version = "1.0.19", features = ["diff"] }
+rustversion = "1.0.6"
+syn = { version = "3", features = ["full"] }
+thiserror = "2"
+trybuild = { version = "1.0.108", features = ["diff"] }
[package.metadata.docs.rs]
targets = ["x86_64-unknown-linux-gnu"]
-rustdoc-args = ["--cfg", "doc_cfg"]
+rustdoc-args = [
+ "--generate-link-to-definition",
+ "--generate-macro-expansion",
+ "--extern-html-root-url=core=https://doc.rust-lang.org",
+ "--extern-html-root-url=alloc=https://doc.rust-lang.org",
+ "--extern-html-root-url=std=https://doc.rust-lang.org",
+]
### external/vendor/anyhow/LICENSE-APACHE
@@ -174,28 +174,3 @@ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
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.
### external/vendor/anyhow/README.md
@@ -1,10 +1,10 @@
-Anyhow ¯\\\_(ツ)\_/¯
-=========================
+Anyhow ¯\\\_(°ペ)\_/¯
+==========================
[<img alt="github" src="https://img.shields.io/badge/github-dtolnay/anyhow-8da0cb?style=for-the-badge&labelColor=555555&logo=github" height="20">](https://github.com/dtolnay/anyhow)
[<img alt="crates.io" src="https://img.shields.io/crates/v/anyhow.svg?style=for-the-badge&color=fc8d62&logo=rust" height="20">](https://crates.io/crates/anyhow)
-[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-anyhow-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K" height="20">](https://docs.rs/anyhow)
-[<img alt="build status" src="https://img.shields.io/github/workflow/status/dtolnay/anyhow/CI/master?style=for-the-badge" height="20">](https://github.com/dtolnay/anyhow/actions?query=branch%3Amaster)
+[<img alt="docs.rs" src="https://img.shields.io/badge/docs.rs-anyhow-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs" height="20">](https://docs.rs/anyhow)
+[<img alt="build status" src="https://img.shields.io/github/actions/workflow/status/dtolnay/anyhow/ci.yml?branch=master&style=for-the-badge" height="20">](https://github.com/dtolnay/anyhow/actions?query=branch%3Amaster)
This library provides [`anyhow::Error`][Error], a trait object based error type
for easy idiomatic error handling in Rust applications.
@@ -16,8 +16,6 @@ for easy idiomatic error handling in Rust applications.
anyhow = "1.0"
```
-*Compiler support: requires rustc 1.34+*
-
<br>
## Details
@@ -26,7 +24,7 @@ anyhow = "1.0"
return type of any fallible function.
Within the function, use `?` to easily propagate any error that implements the
- `std::error::Error` trait.
+ [`std::error::Error`] trait.
```rust
use anyhow::Result;
@@ -38,6 +36,8 @@ anyhow = "1.0"
}
```
+ [`std::error::Error`]: https://doc.rust-lang.org/std/error/trait.Error.html
+
- Attach context to help the person troubleshooting the error understand where
things went wrong. A low-level error like "No such file or directory" can be
annoying to debug without more context about what higher level step the
@@ -75,21 +75,18 @@ anyhow = "1.0"
}
```
-- If using the nightly channel, a backtrace is captured and printed with the
- error if the underlying error type does not already provide its own. In order
- to see backtraces, they must be enabled through the environment variables
- described in [`std::backtrace`]:
+- If using Rust ≥ 1.65, a backtrace is captured and printed with the error if
+ the underlying error type does not already provide its own. In order to see
+ backtraces, they must be enabled through the environment variables described
+ in [`std::backtrace`]:
- If you want panics and errors to both have backtraces, set
`RUST_BACKTRACE=1`;
- If you want only errors to have backtraces, set `RUST_LIB_BACKTRACE=1`;
- If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
`RUST_LIB_BACKTRACE=0`.
- The tracking issue for this feature is [rust-lang/rust#53487].
-
[`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables
- [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487
- Anyhow works with any error type that has an impl of `std::error::Error`,
including ones defined in your crate. We do not bundle a `derive(Error)` macro
@@ -118,23 +115,29 @@ anyhow = "1.0"
return Err(anyhow!("Missing attribute: {}", missing));
```
+ A `bail!` macro is provided as a shorthand for the same early return.
+
+ ```rust
+ bail!("Missing attribute: {}", missing);
+ ```
+
<br>
## No-std support
-In no_std mode, the same API is almost all available and works the same way. To
-depend on Anyhow in no_std mode, disable our default enabled "std" feature in
+In no_std mode, almost all of the same API is available and works the same way.
+To depend on Anyhow in no_std mode, disable our default enabled "std" feature in
Cargo.toml. A global allocator is required.
```toml
[dependencies]
anyhow = { version = "1.0", default-features = false }
```
-Since the `?`-based error conversions would normally rely on the
-`std::error::Error` trait which is only available through std, no_std mode will
-require an explicit `.map_err(Error::msg)` when working with a non-Anyhow error
-type inside a function that returns Anyhow's error type.
+With versions of Rust older than 1.81, no_std mode may require an additional
+`.map_err(Error::msg)` when working with a non-Anyhow error type inside a
+function that returns Anyhow's error type, as the trait that `?`-based error
+conversions are defined by is only available in std in those old versions.
<br>
### external/vendor/anyhow/build.rs
@@ -1,63 +1,194 @@
+#![allow(clippy::uninlined_format_args)]
+
use std::env;
+use std::ffi::OsString;
use std::fs;
+use std::io::ErrorKind;
+use std::iter;
use std::path::Path;
-use std::process::{Command, ExitStatus, Stdio};
-
-// This code exercises the surface area that we expect of the std Backtrace
-// type. If the current toolchain is able to compile it, we go ahead and use
-// backtrace in anyhow.
-const PROBE: &str = r#"
- #![feature(backtrace)]
- #![allow(dead_code)]
+use std::process::{self, Command, Stdio};
+use std::str;
- use std::backtrace::{Backtrace, BacktraceStatus};
- use std::error::Error;
- use std::fmt::{self, Display};
+fn main() {
+ if cfg!(feature = "std") {
+ println!("cargo:rerun-if-changed=src/nightly.rs");
- #[derive(Debug)]
- struct E;
+ let error_generic_member_access;
+ let consider_rustc_bootstrap;
+ if compile_probe(false) {
+ // This is a nightly or dev compiler, so it supports unstable
+ // features regardless of RUSTC_BOOTSTRAP. No need to rerun build
+ // script if RUSTC_BOOTSTRAP is changed.
+ error_generic_member_access = true;
+ consider_rustc_bootstrap = false;
+ } else if let Some(rustc_bootstrap) = env::var_os("RUSTC_BOOTSTRAP") {
+ if compile_probe(true) {
+ // This is a stable or beta compiler for which the user has set
+ // RUSTC_BOOTSTRAP to turn on unstable features. Rerun build
+ // script if they change it.
+ error_generic_member_access = true;
+ consider_rustc_bootstrap = true;
+ } else if rustc_bootstrap == "1" {
+ // This compiler does not support the generic member access API
+ // in the form that anyhow expects. No need to pay attention to
+ // RUSTC_BOOTSTRAP.
+ error_generic_member_access = false;
+ consider_rustc_bootstrap = false;
+ } else {
+ // This is a stable or beta compiler for which RUSTC_BOOTSTRAP
+ // is set to restrict the use of unstable features by this
+ // crate.
+ error_generic_member_access = false;
+ consider_rustc_bootstrap = true;
+ }
+ } else {
+ // Without RUSTC_BOOTSTRAP, this compiler does not support the
+ // generic member access API in the form that anyhow expects, but
+ // try again if the user turns on unstable features.
+ error_generic_member_access = false;
+ consider_rustc_bootstrap = true;
+ }
- impl Display for E {
- fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
- unimplemented!()
+ if error_generic_member_access {
+ println!("cargo:rustc-cfg=error_generic_member_access");
}
- }
- impl Error for E {
- fn backtrace(&self) -> Option<&Backtrace> {
- let backtrace = Backtrace::capture();
- match backtrace.status() {
- BacktraceStatus::Captured | BacktraceStatus::Disabled | _ => {}
- }
- unimplemented!()
+ if consider_rustc_bootstrap {
+ println!("cargo:rerun-if-env-changed=RUSTC_BOOTSTRAP");
}
}
-"#;
-fn main() {
- if !cfg!(feature = "std") {
+ let Some(rustc) = rustc_minor_version() else {
return;
+ };
+
+ if rustc >= 80 {
+ println!("cargo:rustc-check-cfg=cfg(anyhow_build_probe)");
+ println!("cargo:rustc-check-cfg=cfg(anyhow_nightly_testing)");
+ println!("cargo:rustc-check-cfg=cfg(anyhow_no_clippy_format_args)");
+ println!("cargo:rustc-check-cfg=cfg(anyhow_no_core_error)");
+ println!("cargo:rustc-check-cfg=cfg(error_generic_member_access)");
}
- match compile_probe() {
- Some(status) if status.success() => println!("cargo:rustc-cfg=backtrace"),
- _ => {}
+
+ if rustc < 81 {
+ // core::error::Error
+ // https://blog.rust-lang.org/2024/09/05/Rust-1.81.0.html#coreerrorerror
+ println!("cargo:rustc-cfg=anyhow_no_core_error");
+ }
+
+ if rustc < 85 {
+ // #[clippy::format_args]
+ // https://doc.rust-lang.org/1.85.1/clippy/attribs.html#clippyformat_args
+ println!("cargo:rustc-cfg=anyhow_no_clippy_format_args");
}
}
-fn compile_probe() -> Option<ExitStatus> {
- let rustc = env::var_os("RUSTC")?;
- let out_dir = env::var_os("OUT_DIR")?;
- let probefile = Path::new(&out_dir).join("probe.rs");
- fs::write(&probefile, PROBE).ok()?;
- Command::new(rustc)
- .stderr(Stdio::null())
+fn compile_probe(rustc_bootstrap: bool) -> bool {
+ if env::var_os("RUSTC_STAGE").is_some() {
+ // We are running inside rustc bootstrap. This is a highly non-standard
+ // environment with issues such as:
+ //
+ // https://github.com/rust-lang/cargo/issues/11138
+ // https://github.com/rust-lang/rust/issues/114839
+ //
+ // Let's just not use nightly features here.
+ return false;
+ }
+
+ let rustc = cargo_env_var("RUSTC");
+ let out_dir = cargo_env_var("OUT_DIR");
+ let out_subdir = Path::new(&out_dir).join("probe");
+ let probefile = Path::new("src").join("nightly.rs");
+
+ if let Err(err) = fs::create_dir(&out_subdir) {
+ if err.kind() != ErrorKind::AlreadyExists {
+ eprintln!("Failed to create {}: {}", out_subdir.display(), err);
+ process::exit(1);
+ }
+ }
+
+ let rustc_wrapper = env::var_os("RUSTC_WRAPPER").filter(|wrapper| !wrapper.is_empty());
+ let rustc_workspace_wrapper =
+ env::var_os("RUSTC_WORKSPACE_WRAPPER").filter(|wrapper| !wrapper.is_empty());
+ let mut rustc = rustc_wrapper
+ .into_iter()
+ .chain(rustc_workspace_wrapper)
+ .chain(iter::once(rustc));
+ let mut cmd = Command::new(rustc.next().unwrap());
+ cmd.args(rustc);
+
+ if !rustc_bootstrap {
+ cmd.env_remove("RUSTC_BOOTSTRAP");
+ }
+
+ cmd.stderr(Stdio::null())
+ .arg("--cfg=anyhow_build_probe")
.arg("--edition=2018")
- .arg("--crate-name=anyhow_build")
+ .arg("--crate-name=anyhow")
.arg("--crate-type=lib")
- .arg("--emit=metadata")
+ .arg("--cap-lints=allow")
+ .arg("--emit=dep-info,metadata")
.arg("--out-dir")
- .arg(out_dir)
- .arg(probefile)
- .status()
- .ok()
+ .arg(&out_subdir)
+ .arg(probefile);
+
+ if let Some(target) = env::var_os("TARGET") {
+ cmd.arg("--target").arg(target);
+ }
+
+ // If Cargo wants to set RUSTFLAGS, use that.
+ if let Ok(rustflags) = env::var("CARGO_ENCODED_RUSTFLAGS") {
+ if !rustflags.is_empty() {
+ for arg in rustflags.split('\x1f') {
+ cmd.arg(arg);
+ }
+ }
+ }
+
+ let success = match cmd.status() {
+ Ok(status) => status.success(),
+ Err(_) => false,
+ };
+
+ // Clean up to avoid leaving nondeterministic absolute paths in the dep-info
+ // file in OUT_DIR, which causes nonreproducible builds in build systems
+ // that treat the entire OUT_DIR as an artifact.
+ if let Err(err) = fs::remove_dir_all(&out_subdir) {
+ // libc::ENOTEMPTY
+ // Some filesystems (NFSv3) have timing issues under load where '.nfs*'
+ // dummy files can continue to get created for a short period after the
+ // probe command completes, breaking remove_dir_all.
+ // To be replaced with ErrorKind::DirectoryNotEmpty (Rust 1.83+).
+ const ENOTEMPTY: i32 = 39;
+
+ if !(err.kind() == ErrorKind::NotFound
+ || (cfg!(target_os = "linux") && err.raw_os_error() == Some(ENOTEMPTY)))
+ {
+ eprintln!("Failed to clean up {}: {}", out_subdir.display(), err);
+ process::exit(1);
+ }
+ }
+
+ success
+}
+
+fn rustc_minor_version() -> Option<u32> {
+ let rustc = cargo_env_var("RUSTC");
+ let output = Command::new(rustc).arg("--version").output().ok()?;
+ let version = str::from_utf8(&output.stdout).ok()?;
+ let mut pieces = version.split('.');
+ if pieces.next() != Some("rustc 1") {
+ return None;
+ }
+ pieces.next()?.parse().ok()
+}
+
+fn cargo_env_var(key: &str) -> OsString {
+ env::var_os(key).unwrap_or_else(|| {
+ eprintln!(
+ "Environment variable ${} is not set during execution of build script",
+ key,
+ );
+ process::exit(1);
+ })
}
### external/vendor/anyhow/rust-toolchain.toml
@@ -0,0 +1,2 @@
+[toolchain]
+components = ["rust-src"]
### external/vendor/anyhow/src/backtrace.rs
@@ -1,36 +1,48 @@
-#[cfg(backtrace)]
+#[cfg(feature = "std")]
pub(crate) use std::backtrace::Backtrace;
-#[cfg(not(backtrace))]
+#[cfg(not(feature = "std"))]
pub(crate) enum Backtrace {}
-#[cfg(backtrace)]
+#[cfg(feature = "std")]
macro_rules! backtrace {
() => {
- Some(Backtrace::capture())
+ Some(std::backtrace::Backtrace::capture())
};
}
-#[cfg(not(backtrace))]
+#[cfg(not(feature = "std"))]
macro_rules! backtrace {
() => {
None
};
}
-#[cfg(backtrace)]
+#[cfg(error_generic_member_access)]
macro_rules! backtrace_if_absent {
($err:expr) => {
- match $err.backtrace() {
+ match $crate::nightly::request_ref_backtrace($err as &dyn core::error::Error) {
Some(_) => None,
- None => Some(Backtrace::capture()),
+ None => backtrace!(),
}
};
}
-#[cfg(all(feature = "std", not(backtrace)))]
+#[cfg(all(not(error_generic_member_access), feature = "std"))]
+macro_rules! backtrace_if_absent {
+ ($err:expr) => {
+ backtrace!()
+ };
+}
+
+#[cfg(all(not(anyhow_no_core_error), not(feature = "std")))]
macro_rules! backtrace_if_absent {
($err:expr) => {
None
};
}
+
+fn _assert_send_sync() {
+ fn assert<T: Send + Sync>() {}
+ assert::<Backtrace>();
+}
### external/vendor/anyhow/src/chain.rs
@@ -1,13 +1,13 @@
use self::ChainState::*;
use crate::StdError;
-#[cfg(feature = "std")]
-use std::vec;
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+use alloc::vec::{self, Vec};
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
pub(crate) use crate::Chain;
-#[cfg(not(feature = "std"))]
+#[cfg(all(not(feature = "std"), anyhow_no_core_error))]
pub(crate) struct Chain<'a> {
state: ChainState<'a>,
}
@@ -17,13 +17,14 @@ pub(crate) enum ChainState<'a> {
Linked {
next: Option<&'a (dyn StdError + 'static)>,
},
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
Buffered {
rest: vec::IntoIter<&'a (dyn StdError + 'static)>,
},
}
impl<'a> Chain<'a> {
+ #[cold]
pub fn new(head: &'a (dyn StdError + 'static)) -> Self {
Chain {
state: ChainState::Linked { next: Some(head) },
@@ -41,7 +42,7 @@ impl<'a> Iterator for Chain<'a> {
*next = error.source();
Some(error)
}
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
Buffered { rest } => rest.next(),
}
}
@@ -52,7 +53,7 @@ impl<'a> Iterator for Chain<'a> {
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl DoubleEndedIterator for Chain<'_> {
fn next_back(&mut self) -> Option<Self::Item> {
match &mut self.state {
@@ -83,13 +84,13 @@ impl ExactSizeIterator for Chain<'_> {
}
len
}
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
Buffered { rest } => rest.len(),
}
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl Default for Chain<'_> {
fn default() -> Self {
Chain {
### external/vendor/anyhow/src/context.rs
@@ -3,8 +3,8 @@ use crate::{Context, Error, StdError};
use core::convert::Infallible;
use core::fmt::{self, Debug, Display, Write};
-#[cfg(backtrace)]
-use std::backtrace::Backtrace;
+#[cfg(error_generic_member_access)]
+use crate::nightly::{self, Request};
mod ext {
use super::*;
@@ -15,17 +15,17 @@ mod ext {
C: Display + Send + Sync + 'static;
}
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl<E> StdError for E
where
- E: std::error::Error + Send + Sync + 'static,
+ E: crate::StdError + Send + Sync + 'static,
{
fn ext_context<C>(self, context: C) -> Error
where
C: Display + Send + Sync + 'static,
{
- let backtrace = backtrace_if_absent!(self);
- Error::from_context(context, self, backtrace)
+ let backtrace = backtrace_if_absent!(&self);
+ Error::construct_from_context(context, self, backtrace)
}
}
@@ -47,15 +47,23 @@ where
where
C: Display + Send + Sync + 'static,
{
- self.map_err(|error| error.ext_context(context))
+ // Not using map_err to save 2 useless frames off the captured backtrace
+ // in ext_context.
+ match self {
+ Ok(ok) => Ok(ok),
+ Err(error) => Err(error.ext_context(context)),
+ }
}
fn with_context<C, F>(self, context: F) -> Result<T, Error>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
- self.map_err(|error| error.ext_context(context()))
+ match self {
+ Ok(ok) => Ok(ok),
+ Err(error) => Err(error.ext_context(context())),
+ }
}
}
@@ -84,15 +92,23 @@ impl<T> Context<T, Infallible> for Option<T> {
where
C: Display + Send + Sync + 'static,
{
- self.ok_or_else(|| Error::from_display(context, backtrace!()))
+ // Not using ok_or_else to save 2 useless frames off the captured
+ // backtrace.
+ match self {
+ Some(ok) => Ok(ok),
+ None => Err(Error::construct_from_display(context, backtrace!())),
+ }
}
fn with_context<C, F>(self, context: F) -> Result<T, Error>
where
C: Display + Send + Sync + 'static,
F: FnOnce() -> C,
{
- self.ok_or_else(|| Error::from_display(context(), backtrace!()))
+ match self {
+ Some(ok) => Ok(ok),
+ None => Err(Error::construct_from_display(context(), backtrace!())),
+ }
}
}
@@ -123,27 +139,27 @@ where
C: Display,
E: StdError + 'static,
{
- #[cfg(backtrace)]
- fn backtrace(&self) -> Option<&Backtrace> {
- self.error.backtrace()
- }
-
fn source(&self) -> Option<&(dyn StdError + 'static)> {
Some(&self.error)
}
+
+ #[cfg(error_generic_member_access)]
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ nightly::provide(&self.error, request);
+ }
}
impl<C> StdError for ContextError<C, Error>
where
C: Display,
{
- #[cfg(backtrace)]
- fn backtrace(&self) -> Option<&Backtrace> {
- Some(self.error.backtrace())
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
+ Some(unsafe { crate::ErrorImpl::error(self.error.inner.by_ref()) })
}
- fn source(&self) -> Option<&(dyn StdError + 'static)> {
- Some(self.error.inner.error())
+ #[cfg(error_generic_member_access)]
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ Error::provide(&self.error, request);
}
}
### external/vendor/anyhow/src/ensure.rs
@@ -0,0 +1,935 @@
+use crate::Error;
+use alloc::string::String;
+use core::fmt::{self, Debug, Write};
+use core::mem::MaybeUninit;
+use core::ptr;
+use core::slice;
+use core::str;
+
+#[doc(hidden)]
+pub trait BothDebug {
+ fn __dispatch_ensure(self, msg: &'static str) -> Error;
+}
+
+impl<A, B> BothDebug for (A, B)
+where
+ A: Debug,
+ B: Debug,
+{
+ fn __dispatch_ensure(self, msg: &'static str) -> Error {
+ render(msg, &self.0, &self.1)
+ }
+}
+
+#[doc(hidden)]
+pub trait NotBothDebug {
+ fn __dispatch_ensure(self, msg: &'static str) -> Error;
+}
+
+impl<A, B> NotBothDebug for &(A, B) {
+ fn __dispatch_ensure(self, msg: &'static str) -> Error {
+ Error::msg(msg)
+ }
+}
+
+struct Buf {
+ bytes: [MaybeUninit<u8>; 40],
+ written: usize,
+}
+
+impl Buf {
+ fn new() -> Self {
+ Buf {
+ bytes: [MaybeUninit::uninit(); 40],
+ written: 0,
+ }
+ }
+
+ fn as_str(&self) -> &str {
+ unsafe {
+ str::from_utf8_unchecked(slice::from_raw_parts(
+ self.bytes.as_ptr().cast::<u8>(),
+ self.written,
+ ))
+ }
+ }
+}
+
+impl Write for Buf {
+ fn write_str(&mut self, s: &str) -> fmt::Result {
+ if s.bytes().any(|b| b == b' ' || b == b'\n') {
+ return Err(fmt::Error);
+ }
+
+ let remaining = self.bytes.len() - self.written;
+ if s.len() > remaining {
+ return Err(fmt::Error);
+ }
+
+ unsafe {
+ ptr::copy_nonoverlapping(
+ s.as_ptr(),
+ self.bytes.as_mut_ptr().add(self.written).cast::<u8>(),
+ s.len(),
+ );
+ }
+ self.written += s.len();
+ Ok(())
+ }
+}
+
+fn render(msg: &'static str, lhs: &dyn Debug, rhs: &dyn Debug) -> Error {
+ let mut lhs_buf = Buf::new();
+ if fmt::write(&mut lhs_buf, format_args!("{:?}", lhs)).is_ok() {
+ let mut rhs_buf = Buf::new();
+ if fmt::write(&mut rhs_buf, format_args!("{:?}", rhs)).is_ok() {
+ let lhs_str = lhs_buf.as_str();
+ let rhs_str = rhs_buf.as_str();
+ // "{msg} ({lhs} vs {rhs})"
+ let len = msg.len() + 2 + lhs_str.len() + 4 + rhs_str.len() + 1;
+ let mut string = String::with_capacity(len);
+ string.push_str(msg);
+ string.push_str(" (");
+ string.push_str(lhs_str);
+ string.push_str(" vs ");
+ string.push_str(rhs_str);
+ string.push(')');
+ return Error::msg(string);
+ }
+ }
+ Error::msg(msg)
+}
+
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __parse_ensure {
+ (atom () $bail:tt $fuel:tt {($($rhs:tt)+) ($($lhs:tt)+) $op:tt} $dup:tt $(,)?) => {
+ $crate::__fancy_ensure!($($lhs)+, $op, $($rhs)+)
+ };
+
+ // low precedence control flow constructs
+
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt return $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt break $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt continue $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt yield $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (0 $stack:tt ($($bail:tt)*) $fuel:tt $parse:tt $dup:tt move $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ // unary operators
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($deref:tt $($dup:tt)*) * $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $deref) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($not:tt $($dup:tt)*) ! $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $not) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($let:tt $($dup:tt)*) let $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $let) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lifetime:tt $colon:tt $($dup:tt)*) $label:lifetime : $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $lifetime $colon) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) &mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $raw:tt $mut:tt $($dup:tt)*) &raw mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $raw $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $raw:tt $const:tt $($dup:tt)*) &raw const $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and $raw $const) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $mut:tt $($dup:tt)*) &&mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $raw:tt $mut:tt $($dup:tt)*) &&raw mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $raw $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $raw:tt $const:tt $($dup:tt)*) &&raw const $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand $raw $const) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $($dup:tt)*) && $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $andand) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // control flow constructs
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($if:tt $($dup:tt)*) if $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $if) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($match:tt $($dup:tt)*) match $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $match) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($while:tt $($dup:tt)*) while $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $while) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($for:tt $($dup:tt)*) for $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat (cond $stack) $bail ($($fuel)*) {($($buf)* $for) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom (cond $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(cond $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($else:tt $if:tt $($dup:tt)*) else if $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 (cond $stack) $bail ($($fuel)*) {($($buf)* $else $if) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($else:tt $brace:tt $($dup:tt)*) else {$($block:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $else $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (cond $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ // atomic expressions
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($array:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($loop:tt $block:tt $($dup:tt)*) loop {$($body:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $loop $block) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($async:tt $block:tt $($dup:tt)*) async {$($body:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $async $block) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($async:tt $move:tt $block:tt $($dup:tt)*) async move {$($body:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $async $move $block) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($unsafe:tt $block:tt $($dup:tt)*) unsafe {$($body:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $unsafe $block) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($const:tt $block:tt $($dup:tt)*) const {$($body:tt)*} $($rest:tt)*) => {
+ // TODO: this is mostly useless due to https://github.com/rust-lang/rust/issues/86730
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $const $block) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // path expressions
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(epath (atom $stack) $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (0 $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (epath (atom $stack))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: < $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: << $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (epath $stack)))) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt :: <- - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $larrow:tt $($dup:tt)*) :: <- $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (epath $stack) $bail ($($fuel)*) {($($buf)* $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (epath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(epath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! ($($mac:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! [$($mac:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! {$($mac:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (epath (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ (epath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ // trailer expressions
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($call:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($index:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($init:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($question:tt $($dup:tt)*) ? $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $question) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $langle:tt $($dup:tt)*) . $i:ident :: < $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (atom $stack) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $langle:tt $($dup:tt)*) . $i:ident :: << $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (atom $stack)))) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt . $i:ident :: <- - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $ident:tt $colons:tt $larrow:tt $($dup:tt)*) . $i:ident :: <- $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (atom $stack) $bail ($($fuel)*) {($($buf)* $dot $ident $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $field:tt $($dup:tt)*) . $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $dot $field) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt . - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dot:tt $index:tt $($dup:tt)*) . $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(atom $stack $bail ($($fuel)*) {($($buf)* $dot $index) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($as:tt $($dup:tt)*) as $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (atom $stack) $bail ($($fuel)*) {($($buf)* $as) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // types
+
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($content:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($star:tt $const:tt $($dup:tt)*) *const $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $star $const) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($star:tt $mut:tt $($dup:tt)*) *mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $star $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $mut:tt $($dup:tt)*) & $l:lifetime mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) & mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $($dup:tt)*) & $l:lifetime $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $mut:tt $($dup:tt)*) && $l:lifetime mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $mut:tt $($dup:tt)*) && mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $lifetime:tt $($dup:tt)*) && $l:lifetime $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and $lifetime) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) && $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt unsafe extern - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($unsafe:tt $(extern $($abi:literal)?)? fn $($dup:tt)*) unsafe $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $unsafe) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt extern - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($extern:tt $abi:tt fn $($dup:tt)*) extern $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $extern $abi) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($extern:tt fn $($dup:tt)*) extern $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $extern) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($fn:tt $paren:tt $arrow:tt $($dup:tt)*) fn ($($args:tt)*) -> $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $fn $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($fn:tt $paren:tt $($dup:tt)*) fn ($($args:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $fn $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($impl:tt $($dup:tt)*) impl $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $impl) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($dyn:tt $($dup:tt)*) dyn $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $dyn) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($wild:tt $($dup:tt)*) _ $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $wild) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($never:tt $($dup:tt)*) ! $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $never) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($for:tt $langle:tt $($dup:tt)*) for < $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (type $stack) $bail ($($fuel)*) {($($buf)* $for $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // path types
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (type $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (tpath $stack)) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) << $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (tpath $stack)))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt <- - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($larrow:tt $($dup:tt)*) <- $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $larrow) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: < $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $langle:tt $($dup:tt)*) :: << $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (tpath (arglist (tpath $stack)))) $bail ($($fuel)*) {($($buf)* $colons $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt :: <- - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $larrow:tt $($dup:tt)*) :: <- $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic (tpath $stack) $bail ($($fuel)*) {($($buf)* $colons $larrow) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(tpath $stack $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $arrow:tt $($dup:tt)*) ($($args:tt)*) -> $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($args:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $paren:tt $arrow:tt $($dup:tt)*) :: ($($args:tt)*) -> $($rest:tt)*) => {
+ $crate::__parse_ensure!(type $stack $bail ($($fuel)*) {($($buf)* $colons $paren $arrow) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $paren:tt $($dup:tt)*) :: ($($args:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) {($($buf)* $colons $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! ($($mac:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! [$($mac:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bang:tt $args:tt $($dup:tt)*) ! {$($mac:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $bang $args) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (tpath $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!(object $stack $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ // qualified paths
+
+ (qpath (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $colons:tt $ident:tt $($dup:tt)*) >> :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (qpath ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $colons:tt $ident:tt $($dup:tt)*) > :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (qpath $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($as:tt $($dup:tt)*) as $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath $stack) $bail ($($fuel)*) {($($buf)* $as) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // trait objects
+
+ (object (arglist $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($plus:tt $colons:tt $ident:tt $($dup:tt)*) + :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(tpath (arglist $stack) $bail ($($fuel)*) {($($buf)* $plus $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (object (arglist $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($plus:tt $ident:tt $($dup:tt)*) + $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(tpath (arglist $stack) $bail ($($fuel)*) {($($buf)* $plus $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (object (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ (object ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ // angle bracketed generic arguments
+
+ (generic (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) > $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) {($($buf)*) $($parse)*} ($rangle $($rest)*) $rangle $($rest)*)
+ };
+
+ (generic $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (generic $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($block:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lifetime:tt $($dup:tt)*) $l:lifetime $($rest:tt)*) => {
+ $crate::__parse_ensure!(arglist $stack $bail ($($fuel)*) {($($buf)* $lifetime) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($assoc:tt $eq:tt $($dup:tt)*) $ident:ident = $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (arglist $stack) $bail ($($fuel)*) {($($buf)* $assoc $eq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (generic $stack:tt $bail:tt (~$($fuel:tt)*) $parse:tt $dup:tt $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (arglist $stack) $bail ($($fuel)*) $parse $dup $($rest)*)
+ };
+
+ (arglist $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($comma:tt $($dup:tt)*) , $($rest:tt)*) => {
+ $crate::__parse_ensure!(generic $stack $bail ($($fuel)*) {($($buf)* $comma) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (arglist (split ($pop:ident $stack:tt)) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)*) $rangle $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (arglist ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) > $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (arglist ($pop:ident $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!($pop (split $stack) $bail ($($fuel)*) {($($buf)*) $($parse)*} ($rangle $($rest)*) $rangle $($rest)*)
+ };
+
+ // patterns
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($pipe:tt $($dup:tt)*) | $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $pipe) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($eq:tt $($dup:tt)*) = $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $eq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($in:tt $($dup:tt)*) in $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $in) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ref:tt $($dup:tt)*) ref $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $ref) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($mut:tt $($dup:tt)*) mut $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $mut) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($at:tt $($dup:tt)*) @ $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $at) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($neg:tt $($dup:tt)*) - $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $neg) $($parse)*} ($($dup)*) $($dup)*)
+ };
+
+ (pat $stack:tt ($($bail:tt)*) (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt - $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($literal:tt $($dup:tt)*) $lit:literal $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $literal) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($range:tt $($dup:tt)*) .. $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $range) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($range:tt $($dup:tt)*) ..= $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $range) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) & $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($andand:tt $($dup:tt)*) && $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $andand) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($paren:tt $($dup:tt)*) ($($content:tt)*) $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $paren) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bracket:tt $($dup:tt)*) [$($content:tt)*] $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $bracket) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($brace:tt $($dup:tt)*) {$($content:tt)*} $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $brace) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($wild:tt $($dup:tt)*) _ $($rest:tt)*) => {
+ $crate::__parse_ensure!(pat $stack $bail ($($fuel)*) {($($buf)* $wild) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($colons:tt $ident:tt $($dup:tt)*) :: $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(epath (pat $stack) $bail ($($fuel)*) {($($buf)* $colons $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ident:tt $($dup:tt)*) $i:ident $($rest:tt)*) => {
+ $crate::__parse_ensure!(epath (pat $stack) $bail ($($fuel)*) {($($buf)* $ident) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (pat $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($langle:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(type (qpath (epath (pat $stack))) $bail ($($fuel)*) {($($buf)* $langle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // comparison binary operators
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($eq:tt $($dup:tt)*) == $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $eq} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($eq:tt $($dup:tt)*) == $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $eq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($le:tt $($dup:tt)*) <= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $le} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($le:tt $($dup:tt)*) <= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $le) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($lt:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $lt} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($lt:tt $($dup:tt)*) < $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $lt) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ne:tt $($dup:tt)*) != $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $ne} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($ne:tt $($dup:tt)*) != $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $ne) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($ge:tt $($dup:tt)*) >= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $ge} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($ge:tt $($dup:tt)*) >= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $ge) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom (split ()) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} $dup:tt >> $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)* > ) > } ($($rest)*) $($rest)*)
+ };
+
+ (atom () $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($gt:tt $($dup:tt)*) > $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 () $bail ($($fuel)*) {() $($parse)* ($($buf)*) $gt} ($($rest)*) $($rest)*)
+ };
+
+ (atom (split $stack:tt) $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($rangle:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $rangle) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)+) $($parse:tt)*} ($gt:tt $($dup:tt)*) > $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $gt) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // high precedence binary operators
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($add:tt $($dup:tt)*) + $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $add) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($sub:tt $($dup:tt)*) - $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $sub) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($mul:tt $($dup:tt)*) * $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $mul) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($div:tt $($dup:tt)*) / $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $div) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($rem:tt $($dup:tt)*) % $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $rem) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitxor:tt $($dup:tt)*) ^ $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitxor) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitand:tt $($dup:tt)*) & $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitand) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitor:tt $($dup:tt)*) | $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $bitor) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shl:tt $($dup:tt)*) << $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $shl) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom $stack:tt $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shr:tt $($dup:tt)*) >> $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 $stack $bail ($($fuel)*) {($($buf)* $shr) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // low precedence binary operators
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($and:tt $($dup:tt)*) && $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $and) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($or:tt $($dup:tt)*) || $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $or) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($assign:tt $($dup:tt)*) = $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $assign) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($addeq:tt $($dup:tt)*) += $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $addeq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($subeq:tt $($dup:tt)*) -= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $subeq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($muleq:tt $($dup:tt)*) *= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $muleq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($diveq:tt $($dup:tt)*) /= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $diveq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($remeq:tt $($dup:tt)*) %= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $remeq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitxoreq:tt $($dup:tt)*) ^= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitxoreq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitandeq:tt $($dup:tt)*) &= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitandeq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($bitoreq:tt $($dup:tt)*) |= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $bitoreq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shleq:tt $($dup:tt)*) <<= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $shleq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ (atom ($($stack:tt)+) $bail:tt (~$($fuel:tt)*) {($($buf:tt)*) $($parse:tt)*} ($shreq:tt $($dup:tt)*) >>= $($rest:tt)*) => {
+ $crate::__parse_ensure!(0 ($($stack)*) $bail ($($fuel)*) {($($buf)* $shreq) $($parse)*} ($($rest)*) $($rest)*)
+ };
+
+ // unrecognized expression
+
+ ($state:tt $stack:tt ($($bail:tt)*) $($rest:tt)*) => {
+ $crate::__fallback_ensure!($($bail)*)
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __fancy_ensure {
+ ($lhs:expr, $op:tt, $rhs:expr) => {
+ match (&$lhs, &$rhs) {
+ (lhs, rhs) => {
+ if !(lhs $op rhs) {
+ #[allow(unused_imports)]
+ use $crate::__private::{BothDebug, NotBothDebug};
+ return Err((lhs, rhs).__dispatch_ensure(
+ $crate::__private::concat!(
+ "Condition failed: `",
+ $crate::__private::stringify!($lhs),
+ " ",
+ $crate::__private::stringify!($op),
+ " ",
+ $crate::__private::stringify!($rhs),
+ "`",
+ ),
+ ));
+ }
+ }
+ }
+ };
+}
+
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __fallback_ensure {
+ ($cond:expr $(,)?) => {
+ if $crate::__private::not($cond) {
+ return $crate::__private::Err($crate::Error::msg(
+ $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`")
+ ));
+ }
+ };
+ ($cond:expr, $msg:literal $(,)?) => {
+ if $crate::__private::not($cond) {
+ return $crate::__private::Err($crate::__anyhow!($msg));
+ }
+ };
+ ($cond:expr, $err:expr $(,)?) => {
+ if $crate::__private::not($cond) {
+ return $crate::__private::Err($crate::__anyhow!($err));
+ }
+ };
+ ($cond:expr, $fmt:expr, $($arg:tt)*) => {
+ if $crate::__private::not($cond) {
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*));
+ }
+ };
+}
### external/vendor/anyhow/src/error.rs
@@ -1,14 +1,20 @@
-use crate::alloc::Box;
use crate::backtrace::Backtrace;
use crate::chain::Chain;
+#[cfg(error_generic_member_access)]
+use crate::nightly::{self, Request};
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+use crate::ptr::Mut;
+use crate::ptr::{Own, Ref};
use crate::{Error, StdError};
+use alloc::boxed::Box;
use core::any::TypeId;
use core::fmt::{self, Debug, Display};
-use core::mem::{self, ManuallyDrop};
-use core::ptr::{self, NonNull};
-
-#[cfg(feature = "std")]
+use core::mem::ManuallyDrop;
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
use core::ops::{Deref, DerefMut};
+use core::panic::{RefUnwindSafe, UnwindSafe};
+use core::ptr;
+use core::ptr::NonNull;
impl Error {
/// Create a new error object from any error type.
@@ -18,14 +24,15 @@ impl Error {
///
/// If the error type does not provide a backtrace, a backtrace will be
/// created here to ensure that a backtrace exists.
- #[cfg(feature = "std")]
- #[cfg_attr(doc_cfg, doc(cfg(feature = "std")))]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
+ #[must_use]
pub fn new<E>(error: E) -> Self
where
E: StdError + Send + Sync + 'static,
{
- let backtrace = backtrace_if_absent!(error);
- Error::from_std(error, backtrace)
+ let backtrace = backtrace_if_absent!(&error);
+ Error::construct_from_std(error, backtrace)
}
/// Create a new error object from a printable error message.
@@ -65,33 +72,99 @@ impl Error {
/// .await
/// }
/// ```
+ #[cold]
+ #[must_use]
pub fn msg<M>(message: M) -> Self
where
M: Display + Debug + Send + Sync + 'static,
{
- Error::from_adhoc(message, backtrace!())
+ Error::construct_from_adhoc(message, backtrace!())
}
- #[cfg(feature = "std")]
- pub(crate) fn from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
+ /// Construct an error object from a type-erased standard library error.
+ ///
+ /// This is mostly useful for interop with other error libraries.
+ ///
+ /// # Example
+ ///
+ /// Here is a skeleton of a library that provides its own error abstraction.
+ /// The pair of `From` impls provide bidirectional support for `?`
+ /// conversion between `Report` and `anyhow::Error`.
+ ///
+ /// ```
+ /// use std::error::Error as StdError;
+ ///
+ /// pub struct Report {/* ... */}
+ ///
+ /// impl<E> From<E> for Report
+ /// where
+ /// E: Into<anyhow::Error>,
+ /// Result<(), E>: anyhow::Context<(), E>,
+ /// {
+ /// fn from(error: E) -> Self {
+ /// let anyhow_error: anyhow::Error = error.into();
+ /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = anyhow_error.into();
+ /// Report::from_boxed(boxed_error)
+ /// }
+ /// }
+ ///
+ /// impl From<Report> for anyhow::Error {
+ /// fn from(report: Report) -> Self {
+ /// let boxed_error: Box<dyn StdError + Send + Sync + 'static> = report.into_boxed();
+ /// anyhow::Error::from_boxed(boxed_error)
+ /// }
+ /// }
+ ///
+ /// impl Report {
+ /// fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
+ /// todo!()
+ /// }
+ /// fn into_boxed(self) -> Box<dyn StdError + Send + Sync + 'static> {
+ /// todo!()
+ /// }
+ /// }
+ ///
+ /// // Example usage: can use `?` in both directions.
+ /// fn a() -> anyhow::Result<()> {
+ /// b()?;
+ /// Ok(())
+ /// }
+ /// fn b() -> Result<(), Report> {
+ /// a()?;
+ /// Ok(())
+ /// }
+ /// ```
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
+ #[must_use]
+ pub fn from_boxed(boxed_error: Box<dyn StdError + Send + Sync + 'static>) -> Self {
+ let backtrace = backtrace_if_absent!(&*boxed_error);
+ Error::construct_from_boxed(boxed_error, backtrace)
+ }
+
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
+ pub(crate) fn construct_from_std<E>(error: E, backtrace: Option<Backtrace>) -> Self
where
E: StdError + Send + Sync + 'static,
{
let vtable = &ErrorVTable {
object_drop: object_drop::<E>,
object_ref: object_ref::<E>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<E>,
object_boxed: object_boxed::<E>,
+ object_reallocate_boxed: object_reallocate_boxed::<E>,
object_downcast: object_downcast::<E>,
object_drop_rest: object_drop_front::<E>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: no_backtrace,
};
// Safety: passing vtable that operates on the right type E.
unsafe { Error::construct(error, vtable, backtrace) }
}
- pub(crate) fn from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
+ #[cold]
+ pub(crate) fn construct_from_adhoc<M>(message: M, backtrace: Option<Backtrace>) -> Self
where
M: Display + Debug + Send + Sync + 'static,
{
@@ -100,19 +173,23 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<MessageError<M>>,
object_ref: object_ref::<MessageError<M>>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<MessageError<M>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
object_boxed: object_boxed::<MessageError<M>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: object_reallocate_boxed::<MessageError<M>>,
object_downcast: object_downcast::<M>,
object_drop_rest: object_drop_front::<M>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: no_backtrace,
};
// Safety: MessageError is repr(transparent) so it is okay for the
// vtable to allow casting the MessageError<M> to M.
unsafe { Error::construct(error, vtable, backtrace) }
}
- pub(crate) fn from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
+ #[cold]
+ pub(crate) fn construct_from_display<M>(message: M, backtrace: Option<Backtrace>) -> Self
where
M: Display + Send + Sync + 'static,
{
@@ -121,20 +198,28 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<DisplayError<M>>,
object_ref: object_ref::<DisplayError<M>>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<DisplayError<M>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
object_boxed: object_boxed::<DisplayError<M>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: object_reallocate_boxed::<DisplayError<M>>,
object_downcast: object_downcast::<M>,
object_drop_rest: object_drop_front::<M>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: no_backtrace,
};
// Safety: DisplayError is repr(transparent) so it is okay for the
// vtable to allow casting the DisplayError<M> to M.
unsafe { Error::construct(error, vtable, backtrace) }
}
- #[cfg(feature = "std")]
- pub(crate) fn from_context<C, E>(context: C, error: E, backtrace: Option<Backtrace>) -> Self
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
+ pub(crate) fn construct_from_context<C, E>(
+ context: C,
+ error: E,
+ backtrace: Option<Backtrace>,
+ ) -> Self
where
C: Display + Send + Sync + 'static,
E: StdError + Send + Sync + 'static,
@@ -144,19 +229,23 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<ContextError<C, E>>,
object_ref: object_ref::<ContextError<C, E>>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<ContextError<C, E>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
object_boxed: object_boxed::<ContextError<C, E>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, E>>,
object_downcast: context_downcast::<C, E>,
object_drop_rest: context_drop_rest::<C, E>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: no_backtrace,
};
// Safety: passing vtable that operates on the right type.
unsafe { Error::construct(error, vtable, backtrace) }
}
- #[cfg(feature = "std")]
- pub(crate) fn from_boxed(
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
+ pub(crate) fn construct_from_boxed(
error: Box<dyn StdError + Send + Sync>,
backtrace: Option<Backtrace>,
) -> Self {
@@ -165,11 +254,14 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<BoxedError>,
object_ref: object_ref::<BoxedError>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<BoxedError>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
object_boxed: object_boxed::<BoxedError>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: object_reallocate_boxed::<BoxedError>,
object_downcast: object_downcast::<Box<dyn StdError + Send + Sync>>,
object_drop_rest: object_drop_front::<Box<dyn StdError + Send + Sync>>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: no_backtrace,
};
// Safety: BoxedError is repr(transparent) so it is okay for the vtable
@@ -182,6 +274,7 @@ impl Error {
//
// Unsafe because the given vtable must have sensible behavior on the error
// value of type E.
+ #[cold]
unsafe fn construct<E>(
error: E,
vtable: &'static ErrorVTable,
@@ -190,19 +283,18 @@ impl Error {
where
E: StdError + Send + Sync + 'static,
{
- let inner = Box::new(ErrorImpl {
+ let inner: Box<ErrorImpl<E>> = Box::new(ErrorImpl {
vtable,
backtrace,
_object: error,
});
// Erase the concrete type of E from the compile-time type system. This
- // is equivalent to the safe unsize coersion from Box<ErrorImpl<E>> to
+ // is equivalent to the safe unsize coercion from Box<ErrorImpl<E>> to
// Box<ErrorImpl<dyn StdError + Send + Sync + 'static>> except that the
// result is a thin pointer. The necessary behavior for manipulating the
// underlying ErrorImpl<E> is preserved in the vtable provided by the
// caller rather than a builtin fat pointer vtable.
- let erased = mem::transmute::<Box<ErrorImpl<E>>, Box<ErrorImpl<()>>>(inner);
- let inner = ManuallyDrop::new(erased);
+ let inner = Own::new(inner).cast::<ErrorImpl>();
Error { inner }
}
@@ -260,6 +352,8 @@ impl Error {
/// })
/// }
/// ```
+ #[cold]
+ #[must_use]
pub fn context<C>(self, context: C) -> Self
where
C: Display + Send + Sync + 'static,
@@ -272,11 +366,14 @@ impl Error {
let vtable = &ErrorVTable {
object_drop: object_drop::<ContextError<C, Error>>,
object_ref: object_ref::<ContextError<C, Error>>,
- #[cfg(feature = "std")]
- object_mut: object_mut::<ContextError<C, Error>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
object_boxed: object_boxed::<ContextError<C, Error>>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: object_reallocate_boxed::<ContextError<C, Error>>,
object_downcast: context_chain_downcast::<C>,
object_drop_rest: context_chain_drop_rest::<C>,
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: context_backtrace::<C>,
};
// As the cause is anyhow::Error, we already have a backtrace for it.
@@ -288,9 +385,6 @@ impl Error {
/// Get the backtrace for this Error.
///
- /// Backtraces are only available on the nightly channel. Tracking issue:
- /// [rust-lang/rust#53487][tracking].
- ///
/// In order for the backtrace to be meaningful, one of the two environment
/// variables `RUST_LIB_BACKTRACE=1` or `RUST_BACKTRACE=1` must be defined
/// and `RUST_LIB_BACKTRACE` must not be `0`. Backtraces are somewhat
@@ -304,10 +398,21 @@ impl Error {
/// - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
/// `RUST_LIB_BACKTRACE=0`.
///
- /// [tracking]: https://github.com/rust-lang/rust/issues/53487
- #[cfg(backtrace)]
+ /// # Stability
+ ///
+ /// Standard library backtraces are only available when using Rust ≥
+ /// 1.65. On older compilers, this function is only available if the crate's
+ /// "backtrace" feature is enabled, and will use the `backtrace` crate as
+ /// the underlying backtrace implementation. The return type of this
+ /// function on old compilers is `&(impl Debug + Display)`.
+ ///
+ /// ```toml
+ /// [dependencies]
+ /// anyhow = { version = "1.0", features = ["backtrace"] }
+ /// ```
+ #[cfg(feature = "std")]
pub fn backtrace(&self) -> &Backtrace {
- self.inner.backtrace()
+ unsafe { ErrorImpl::backtrace(self.inner.by_ref()) }
}
/// An iterator of the chain of source errors contained by this Error.
@@ -331,24 +436,21 @@ impl Error {
/// None
/// }
/// ```
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[cold]
pub fn chain(&self) -> Chain {
- self.inner.chain()
+ unsafe { ErrorImpl::chain(self.inner.by_ref()) }
}
/// The lowest level cause of this error — this error's cause's
/// cause's cause etc.
///
/// The root cause is the last error in the iterator produced by
/// [`chain()`][Error::chain].
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[allow(clippy::double_ended_iterator_last)]
pub fn root_cause(&self) -> &(dyn StdError + 'static) {
- let mut chain = self.chain();
- let mut root_cause = chain.next().unwrap();
- for cause in chain {
- root_cause = cause;
- }
- root_cause
+ self.chain().last().unwrap()
}
/// Returns true if `E` is the type held by this error object.
@@ -358,7 +460,7 @@ impl Error {
/// context has been attached. For details about the interaction between
/// context and downcasting, [see here].
///
- /// [see here]: trait.Context.html#effect-on-downcasting
+ /// [see here]: crate::Context#effect-on-downcasting
pub fn is<E>(&self) -> bool
where
E: Display + Debug + Send + Sync + 'static,
@@ -367,16 +469,17 @@ impl Error {
}
/// Attempt to downcast the error object to a concrete type.
- pub fn downcast<E>(self) -> Result<E, Self>
+ pub fn downcast<E>(mut self) -> Result<E, Self>
where
E: Display + Debug + Send + Sync + 'static,
{
let target = TypeId::of::<E>();
+ let inner = self.inner.by_mut();
unsafe {
// Use vtable to find NonNull<()> which points to a value of type E
// somewhere inside the data structure.
- let addr = match (self.inner.vtable.object_downcast)(&self.inner, target) {
- Some(addr) => addr,
+ let addr = match (vtable(inner.ptr).object_downcast)(inner.by_ref(), target) {
+ Some(addr) => addr.by_mut().extend(),
None => return Err(self),
};
@@ -385,15 +488,10 @@ impl Error {
let outer = ManuallyDrop::new(self);
// Read E from where the vtable found it.
- let error = ptr::read(addr.cast::<E>().as_ptr());
-
- // Read Box<ErrorImpl<()>> from self. Can't move it out because
- // Error has a Drop impl which we want to not run.
- let inner = ptr::read(&outer.inner);
- let erased = ManuallyDrop::into_inner(inner);
+ let error = addr.cast::<E>().read();
// Drop rest of the data structure outside of E.
- (erased.vtable.object_drop_rest)(erased, target);
+ (vtable(outer.inner.ptr).object_drop_rest)(outer.inner, target);
Ok(error)
}
@@ -443,8 +541,8 @@ impl Error {
unsafe {
// Use vtable to find NonNull<()> which points to a value of type E
// somewhere inside the data structure.
- let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
- Some(&*addr.cast::<E>().as_ptr())
+ let addr = (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?;
+ Some(addr.cast::<E>().deref())
}
}
@@ -457,235 +555,371 @@ impl Error {
unsafe {
// Use vtable to find NonNull<()> which points to a value of type E
// somewhere inside the data structure.
- let addr = (self.inner.vtable.object_downcast)(&self.inner, target)?;
- Some(&mut *addr.cast::<E>().as_ptr())
+ let addr =
+ (vtable(self.inner.ptr).object_downcast)(self.inner.by_ref(), target)?.by_mut();
+ Some(addr.cast::<E>().deref_mut())
+ }
+ }
+
+ /// Convert to a standard library error trait object.
+ ///
+ /// This is implemented as a cheap pointer cast that does not allocate or
+ /// deallocate memory. Like [`anyhow::Error::from_boxed`], it's useful for
+ /// interop with other error libraries.
+ ///
+ /// The same conversion is also available as
+ /// <code style="display:inline;white-space:normal;">impl From<anyhow::Error>
+ /// for Box<dyn Error + Send + Sync + 'static></code>.
+ ///
+ /// If a backtrace was collected during construction of the `anyhow::Error`,
+ /// that backtrace remains accessible using the standard library `Error`
+ /// trait's provider API, but as a consequence, the resulting boxed error
+ /// can no longer be downcast to its original underlying type.
+ ///
+ /// ```
+ #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify! {")]
+ /// #![feature(error_generic_member_access)]
+ ///
+ /// use anyhow::anyhow;
+ /// use std::backtrace::Backtrace;
+ /// use thiserror::Error;
+ ///
+ /// #[derive(Error, Debug)]
+ /// #[error("...")]
+ /// struct MyError;
+ ///
+ /// let anyhow_error = anyhow!(MyError);
+ /// println!("{}", anyhow_error.backtrace()); // has Backtrace
+ /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast
+ ///
+ /// let boxed_dyn_error = anyhow_error.into_boxed_dyn_error();
+ /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_some()); // has Backtrace
+ /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_none()); // can no longer downcast
+ #[cfg_attr(not(error_generic_member_access), doc = "# };")]
+ /// ```
+ ///
+ /// [`anyhow::Error::from_boxed`]: Self::from_boxed
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[must_use]
+ pub fn into_boxed_dyn_error(self) -> Box<dyn StdError + Send + Sync + 'static> {
+ let outer = ManuallyDrop::new(self);
+ unsafe {
+ // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
+ // the right original type E.
+ (vtable(outer.inner.ptr).object_boxed)(outer.inner)
+ }
+ }
+
+ /// Convert to a standard library error trait object.
+ ///
+ /// Unlike `self.into_boxed_dyn_error()`, this method relocates the
+ /// underlying error into a new allocation in order to make it downcastable
+ /// to `&E` or `Box<E>` for its original underlying error type. Any
+ /// backtrace collected during construction of the `anyhow::Error` is
+ /// discarded.
+ ///
+ /// ```
+ #[cfg_attr(not(error_generic_member_access), doc = "# _ = stringify!{")]
+ /// #![feature(error_generic_member_access)]
+ ///
+ /// use anyhow::anyhow;
+ /// use std::backtrace::Backtrace;
+ /// use thiserror::Error;
+ ///
+ /// #[derive(Error, Debug)]
+ /// #[error("...")]
+ /// struct MyError;
+ ///
+ /// let anyhow_error = anyhow!(MyError);
+ /// println!("{}", anyhow_error.backtrace()); // has Backtrace
+ /// assert!(anyhow_error.downcast_ref::<MyError>().is_some()); // can downcast
+ ///
+ /// let boxed_dyn_error = anyhow_error.reallocate_into_boxed_dyn_error_without_backtrace();
+ /// assert!(std::error::request_ref::<Backtrace>(&*boxed_dyn_error).is_none()); // Backtrace lost
+ /// assert!(boxed_dyn_error.downcast_ref::<MyError>().is_some()); // can downcast to &MyError
+ /// assert!(boxed_dyn_error.downcast::<MyError>().is_ok()); // can downcast to Box<MyError>
+ #[cfg_attr(not(error_generic_member_access), doc = "# };")]
+ /// ```
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[must_use]
+ pub fn reallocate_into_boxed_dyn_error_without_backtrace(
+ self,
+ ) -> Box<dyn StdError + Send + Sync + 'static> {
+ let outer = ManuallyDrop::new(self);
+ unsafe {
+ // Use vtable to attach E's native StdError vtable for the right
+ // original type E.
+ (vtable(outer.inner.ptr).object_reallocate_boxed)(outer.inner)
}
}
+
+ #[cfg(error_generic_member_access)]
+ pub(crate) fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ unsafe { ErrorImpl::provide(self.inner.by_ref(), request) }
+ }
+
+ // Called by thiserror when you have `#[source] anyhow::Error`. This provide
+ // implementation includes the anyhow::Error's Backtrace if any, unlike
+ // deref'ing to dyn Error where the provide implementation would include
+ // only the original error's Backtrace from before it got wrapped into an
+ // anyhow::Error.
+ #[cfg(error_generic_member_access)]
+ #[doc(hidden)]
+ pub fn thiserror_provide<'a>(&'a self, request: &mut Request<'a>) {
+ Self::provide(self, request);
+ }
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl<E> From<E> for Error
where
E: StdError + Send + Sync + 'static,
{
+ #[cold]
fn from(error: E) -> Self {
- let backtrace = backtrace_if_absent!(error);
- Error::from_std(error, backtrace)
+ let backtrace = backtrace_if_absent!(&error);
+ Error::construct_from_std(error, backtrace)
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl Deref for Error {
type Target = dyn StdError + Send + Sync + 'static;
fn deref(&self) -> &Self::Target {
- self.inner.error()
+ unsafe { ErrorImpl::error(self.inner.by_ref()) }
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl DerefMut for Error {
fn deref_mut(&mut self) -> &mut Self::Target {
- self.inner.error_mut()
+ unsafe { ErrorImpl::error_mut(self.inner.by_mut()) }
}
}
impl Display for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- self.inner.display(formatter)
+ unsafe { ErrorImpl::display(self.inner.by_ref(), formatter) }
}
}
impl Debug for Error {
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- self.inner.debug(formatter)
+ unsafe { ErrorImpl::debug(self.inner.by_ref(), formatter) }
}
}
impl Drop for Error {
fn drop(&mut self) {
unsafe {
- // Read Box<ErrorImpl<()>> from self.
- let inner = ptr::read(&self.inner);
- let erased = ManuallyDrop::into_inner(inner);
-
// Invoke the vtable's drop behavior.
- (erased.vtable.object_drop)(erased);
+ (vtable(self.inner.ptr).object_drop)(self.inner);
}
}
}
struct ErrorVTable {
- object_drop: unsafe fn(Box<ErrorImpl<()>>),
- object_ref: unsafe fn(&ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static),
- #[cfg(feature = "std")]
- object_mut: unsafe fn(&mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static),
- object_boxed: unsafe fn(Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>,
- object_downcast: unsafe fn(&ErrorImpl<()>, TypeId) -> Option<NonNull<()>>,
- object_drop_rest: unsafe fn(Box<ErrorImpl<()>>, TypeId),
+ object_drop: unsafe fn(Own<ErrorImpl>),
+ object_ref: unsafe fn(Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ object_reallocate_boxed: unsafe fn(Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>,
+ object_downcast: unsafe fn(Ref<ErrorImpl>, TypeId) -> Option<Ref<()>>,
+ object_drop_rest: unsafe fn(Own<ErrorImpl>, TypeId),
+ #[cfg(all(not(error_generic_member_access), feature = "std"))]
+ object_backtrace: unsafe fn(Ref<ErrorImpl>) -> Option<&Backtrace>,
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-unsafe fn object_drop<E>(e: Box<ErrorImpl<()>>) {
+unsafe fn object_drop<E>(e: Own<ErrorImpl>) {
// Cast back to ErrorImpl<E> so that the allocator receives the correct
// Layout to deallocate the Box's memory.
- let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e);
- drop(unerased);
+ let unerased_own = e.cast::<ErrorImpl<E>>();
+ drop(unsafe { unerased_own.boxed() });
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-unsafe fn object_drop_front<E>(e: Box<ErrorImpl<()>>, target: TypeId) {
+unsafe fn object_drop_front<E>(e: Own<ErrorImpl>, target: TypeId) {
// Drop the fields of ErrorImpl other than E as well as the Box allocation,
// without dropping E itself. This is used by downcast after doing a
// ptr::read to take ownership of the E.
let _ = target;
- let unerased = mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<ManuallyDrop<E>>>>(e);
- drop(unerased);
+ let unerased_own = e.cast::<ErrorImpl<ManuallyDrop<E>>>();
+ drop(unsafe { unerased_own.boxed() });
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-unsafe fn object_ref<E>(e: &ErrorImpl<()>) -> &(dyn StdError + Send + Sync + 'static)
+unsafe fn object_ref<E>(e: Ref<ErrorImpl>) -> Ref<dyn StdError + Send + Sync + 'static>
where
E: StdError + Send + Sync + 'static,
{
// Attach E's native StdError vtable onto a pointer to self._object.
- &(*(e as *const ErrorImpl<()> as *const ErrorImpl<E>))._object
+ let unerased_ref = e.cast::<ErrorImpl<E>>();
+ Ref::from_raw(unsafe {
+ NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())
+ })
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-#[cfg(feature = "std")]
-unsafe fn object_mut<E>(e: &mut ErrorImpl<()>) -> &mut (dyn StdError + Send + Sync + 'static)
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+unsafe fn object_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
where
E: StdError + Send + Sync + 'static,
{
- // Attach E's native StdError vtable onto a pointer to self._object.
- &mut (*(e as *mut ErrorImpl<()> as *mut ErrorImpl<E>))._object
+ // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.
+ let unerased_own = e.cast::<ErrorImpl<E>>();
+ unsafe { unerased_own.boxed() }
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-unsafe fn object_boxed<E>(e: Box<ErrorImpl<()>>) -> Box<dyn StdError + Send + Sync + 'static>
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+unsafe fn object_reallocate_boxed<E>(e: Own<ErrorImpl>) -> Box<dyn StdError + Send + Sync + 'static>
where
E: StdError + Send + Sync + 'static,
{
- // Attach ErrorImpl<E>'s native StdError vtable. The StdError impl is below.
- mem::transmute::<Box<ErrorImpl<()>>, Box<ErrorImpl<E>>>(e)
+ // Attach E's native StdError vtable.
+ let unerased_own = e.cast::<ErrorImpl<E>>();
+ Box::new(unsafe { unerased_own.boxed() }._object)
}
// Safety: requires layout of *e to match ErrorImpl<E>.
-unsafe fn object_downcast<E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
+unsafe fn object_downcast<E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
where
E: 'static,
{
if TypeId::of::<E>() == target {
// Caller is looking for an E pointer and e is ErrorImpl<E>, take a
// pointer to its E field.
- let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<E>;
- let addr = &(*unerased)._object as *const E as *mut ();
- Some(NonNull::new_unchecked(addr))
+ let unerased_ref = e.cast::<ErrorImpl<E>>();
+ Some(
+ Ref::from_raw(unsafe {
+ NonNull::new_unchecked(ptr::addr_of!((*unerased_ref.as_ptr())._object).cast_mut())
+ })
+ .cast::<()>(),
+ )
} else {
None
}
}
+#[cfg(all(not(error_generic_member_access), feature = "std"))]
+fn no_backtrace(e: Ref<ErrorImpl>) -> Option<&Backtrace> {
+ let _ = e;
+ None
+}
+
// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
-#[cfg(feature = "std")]
-unsafe fn context_downcast<C, E>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+unsafe fn context_downcast<C, E>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
where
C: 'static,
E: 'static,
{
if TypeId::of::<C>() == target {
- let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;
- let addr = &(*unerased)._object.context as *const C as *mut ();
- Some(NonNull::new_unchecked(addr))
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
+ let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.context) };
+ Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())
} else if TypeId::of::<E>() == target {
- let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, E>>;
- let addr = &(*unerased)._object.error as *const E as *mut ();
- Some(NonNull::new_unchecked(addr))
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, E>>>();
+ let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.error) };
+ Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())
} else {
None
}
}
// Safety: requires layout of *e to match ErrorImpl<ContextError<C, E>>.
-#[cfg(feature = "std")]
-unsafe fn context_drop_rest<C, E>(e: Box<ErrorImpl<()>>, target: TypeId)
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+unsafe fn context_drop_rest<C, E>(e: Own<ErrorImpl>, target: TypeId)
where
C: 'static,
E: 'static,
{
// Called after downcasting by value to either the C or the E and doing a
// ptr::read to take ownership of that value.
if TypeId::of::<C>() == target {
- let unerased = mem::transmute::<
- Box<ErrorImpl<()>>,
- Box<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>,
- >(e);
- drop(unerased);
+ let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, E>>>();
+ drop(unsafe { unerased_own.boxed() });
} else {
- let unerased = mem::transmute::<
- Box<ErrorImpl<()>>,
- Box<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>,
- >(e);
- drop(unerased);
+ let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<E>>>>();
+ drop(unsafe { unerased_own.boxed() });
}
}
// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
-unsafe fn context_chain_downcast<C>(e: &ErrorImpl<()>, target: TypeId) -> Option<NonNull<()>>
+unsafe fn context_chain_downcast<C>(e: Ref<ErrorImpl>, target: TypeId) -> Option<Ref<()>>
where
C: 'static,
{
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
if TypeId::of::<C>() == target {
- let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
- let addr = &(*unerased)._object.context as *const C as *mut ();
- Some(NonNull::new_unchecked(addr))
+ let inner = unsafe { ptr::addr_of!((*unerased_ref.as_ptr())._object.context) };
+ Some(Ref::from_raw(unsafe { NonNull::new_unchecked(inner.cast_mut()) }).cast::<()>())
} else {
// Recurse down the context chain per the inner error's vtable.
- let unerased = e as *const ErrorImpl<()> as *const ErrorImpl<ContextError<C, Error>>;
- let source = &(*unerased)._object.error;
- (source.inner.vtable.object_downcast)(&source.inner, target)
+ let unerased = unsafe { unerased_ref.deref() };
+ let source = &unerased._object.error;
+ unsafe { (vtable(source.inner.ptr).object_downcast)(source.inner.by_ref(), target) }
}
}
// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
-unsafe fn context_chain_drop_rest<C>(e: Box<ErrorImpl<()>>, target: TypeId)
+unsafe fn context_chain_drop_rest<C>(e: Own<ErrorImpl>, target: TypeId)
where
C: 'static,
{
// Called after downcasting by value to either the C or one of the causes
// and doing a ptr::read to take ownership of that value.
if TypeId::of::<C>() == target {
- let unerased = mem::transmute::<
- Box<ErrorImpl<()>>,
- Box<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>,
- >(e);
+ let unerased_own = e.cast::<ErrorImpl<ContextError<ManuallyDrop<C>, Error>>>();
// Drop the entire rest of the data structure rooted in the next Error.
- drop(unerased);
+ drop(unsafe { unerased_own.boxed() });
} else {
- let unerased = mem::transmute::<
- Box<ErrorImpl<()>>,
- Box<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>,
- >(e);
- // Read out a ManuallyDrop<Box<ErrorImpl<()>>> from the next error.
- let inner = ptr::read(&unerased._object.error.inner);
+ let unerased_own = e.cast::<ErrorImpl<ContextError<C, ManuallyDrop<Error>>>>();
+ let unerased = unsafe { unerased_own.boxed() };
+ // Read the Own<ErrorImpl> from the next error.
+ let inner = unerased._object.error.inner;
drop(unerased);
- let erased = ManuallyDrop::into_inner(inner);
+ let vtable = unsafe { vtable(inner.ptr) };
// Recursively drop the next error using the same target typeid.
- (erased.vtable.object_drop_rest)(erased, target);
+ unsafe { (vtable.object_drop_rest)(inner, target) };
}
}
+// Safety: requires layout of *e to match ErrorImpl<ContextError<C, Error>>.
+#[cfg(all(not(error_generic_member_access), feature = "std"))]
+#[allow(clippy::unnecessary_wraps)]
+unsafe fn context_backtrace<C>(e: Ref<ErrorImpl>) -> Option<&Backtrace>
+where
+ C: 'static,
+{
+ let unerased_ref = e.cast::<ErrorImpl<ContextError<C, Error>>>();
+ let unerased = unsafe { unerased_ref.deref() };
+ let backtrace = unsafe { ErrorImpl::backtrace(unerased._object.error.inner.by_ref()) };
+ Some(backtrace)
+}
+
+// NOTE: If working with `ErrorImpl<()>`, references should be avoided in favor
+// of raw pointers and `NonNull`.
// repr C to ensure that E remains in the final position.
#[repr(C)]
-pub(crate) struct ErrorImpl<E> {
+pub(crate) struct ErrorImpl<E = ()> {
vtable: &'static ErrorVTable,
backtrace: Option<Backtrace>,
// NOTE: Don't use directly. Use only through vtable. Erased type may have
// different alignment.
_object: E,
}
+// Reads the vtable out of `p`. This is the same as `p.as_ref().vtable`, but
+// avoids converting `p` into a reference.
+unsafe fn vtable(p: NonNull<ErrorImpl>) -> &'static ErrorVTable {
+ // NOTE: This assumes that `ErrorVTable` is the first field of ErrorImpl.
+ unsafe { *(p.as_ptr() as *const &'static ErrorVTable) }
+}
+
// repr C to ensure that ContextError<C, E> has the same layout as
// ContextError<ManuallyDrop<C>, E> and ContextError<C, ManuallyDrop<E>>.
#[repr(C)]
@@ -695,55 +929,74 @@ pub(crate) struct ContextError<C, E> {
}
impl<E> ErrorImpl<E> {
- fn erase(&self) -> &ErrorImpl<()> {
+ fn erase(&self) -> Ref<ErrorImpl> {
// Erase the concrete type of E but preserve the vtable in self.vtable
// for manipulating the resulting thin pointer. This is analogous to an
- // unsize coersion.
- unsafe { &*(self as *const ErrorImpl<E> as *const ErrorImpl<()>) }
+ // unsize coercion.
+ Ref::new(self).cast::<ErrorImpl>()
}
}
-impl ErrorImpl<()> {
- pub(crate) fn error(&self) -> &(dyn StdError + Send + Sync + 'static) {
+impl ErrorImpl {
+ pub(crate) unsafe fn error(this: Ref<Self>) -> &(dyn StdError + Send + Sync + 'static) {
// Use vtable to attach E's native StdError vtable for the right
// original type E.
- unsafe { &*(self.vtable.object_ref)(self) }
+ unsafe { (vtable(this.ptr).object_ref)(this).deref() }
}
- #[cfg(feature = "std")]
- pub(crate) fn error_mut(&mut self) -> &mut (dyn StdError + Send + Sync + 'static) {
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ pub(crate) unsafe fn error_mut(this: Mut<Self>) -> &mut (dyn StdError + Send + Sync + 'static) {
// Use vtable to attach E's native StdError vtable for the right
// original type E.
- unsafe { &mut *(self.vtable.object_mut)(self) }
+ unsafe {
+ (vtable(this.ptr).object_ref)(this.by_ref())
+ .by_mut()
+ .deref_mut()
+ }
}
- #[cfg(backtrace)]
- pub(crate) fn backtrace(&self) -> &Backtrace {
+ #[cfg(feature = "std")]
+ pub(crate) unsafe fn backtrace(this: Ref<Self>) -> &Backtrace {
// This unwrap can only panic if the underlying error's backtrace method
// is nondeterministic, which would only happen in maliciously
// constructed code.
- self.backtrace
+ unsafe { this.deref() }
+ .backtrace
.as_ref()
- .or_else(|| self.error().backtrace())
+ .or_else(|| {
+ #[cfg(error_generic_member_access)]
+ return nightly::request_ref_backtrace(unsafe { Self::error(this) });
+ #[cfg(not(error_generic_member_access))]
+ return unsafe { (vtable(this.ptr).object_backtrace)(this) };
+ })
.expect("backtrace capture failed")
}
- pub(crate) fn chain(&self) -> Chain {
- Chain::new(self.error())
+ #[cfg(error_generic_member_access)]
+ unsafe fn provide<'a>(this: Ref<'a, Self>, request: &mut Request<'a>) {
+ if let Some(backtrace) = unsafe { &this.deref().backtrace } {
+ nightly::provide_ref_backtrace(request, backtrace);
+ }
+ nightly::provide(unsafe { Self::error(this) }, request);
+ }
+
+ #[cold]
+ pub(crate) unsafe fn chain(this: Ref<Self>) -> Chain {
+ Chain::new(unsafe { Self::error(this) })
}
}
impl<E> StdError for ErrorImpl<E>
where
E: StdError,
{
- #[cfg(backtrace)]
- fn backtrace(&self) -> Option<&Backtrace> {
- Some(self.erase().backtrace())
+ fn source(&self) -> Option<&(dyn StdError + 'static)> {
+ unsafe { ErrorImpl::error(self.erase()).source() }
}
- fn source(&self) -> Option<&(dyn StdError + 'static)> {
- self.erase().error().source()
+ #[cfg(error_generic_member_access)]
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ unsafe { ErrorImpl::provide(self.erase(), request) }
}
}
@@ -752,7 +1005,7 @@ where
E: Debug,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- self.erase().debug(formatter)
+ unsafe { ErrorImpl::debug(self.erase(), formatter) }
}
}
@@ -761,42 +1014,47 @@ where
E: Display,
{
fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
- Display::fmt(&self.erase().error(), formatter)
+ unsafe { Display::fmt(ErrorImpl::error(self.erase()), formatter) }
}
}
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl From<Error> for Box<dyn StdError + Send + Sync + 'static> {
+ #[cold]
fn from(error: Error) -> Self {
- let outer = ManuallyDrop::new(error);
- unsafe {
- // Read Box<ErrorImpl<()>> from error. Can't move it out because
- // Error has a Drop impl which we want to not run.
- let inner = ptr::read(&outer.inner);
- let erased = ManuallyDrop::into_inner(inner);
+ error.into_boxed_dyn_error()
+ }
+}
- // Use vtable to attach ErrorImpl<E>'s native StdError vtable for
- // the right original type E.
- (erased.vtable.object_boxed)(erased)
- }
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+impl From<Error> for Box<dyn StdError + Send + 'static> {
+ #[cold]
+ fn from(error: Error) -> Self {
+ error.into_boxed_dyn_error()
}
}
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl From<Error> for Box<dyn StdError + 'static> {
+ #[cold]
fn from(error: Error) -> Self {
- Box::<dyn StdError + Send + Sync>::from(error)
+ error.into_boxed_dyn_error()
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl AsRef<dyn StdError + Send + Sync> for Error {
fn as_ref(&self) -> &(dyn StdError + Send + Sync + 'static) {
&**self
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl AsRef<dyn StdError> for Error {
fn as_ref(&self) -> &(dyn StdError + 'static) {
&**self
}
}
+
+impl UnwindSafe for Error {}
+impl RefUnwindSafe for Error {}
### external/vendor/anyhow/src/fmt.rs
@@ -1,22 +1,24 @@
use crate::chain::Chain;
use crate::error::ErrorImpl;
+use crate::ptr::Ref;
use core::fmt::{self, Debug, Write};
-impl ErrorImpl<()> {
- pub(crate) fn display(&self, f: &mut fmt::Formatter) -> fmt::Result {
- write!(f, "{}", self.error())?;
+impl ErrorImpl {
+ pub(crate) unsafe fn display(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {
+ write!(f, "{}", unsafe { Self::error(this) })?;
if f.alternate() {
- for cause in self.chain().skip(1) {
+ let chain = unsafe { Self::chain(this) };
+ for cause in chain.skip(1) {
write!(f, ": {}", cause)?;
}
}
Ok(())
}
- pub(crate) fn debug(&self, f: &mut fmt::Formatter) -> fmt::Result {
- let error = self.error();
+ pub(crate) unsafe fn debug(this: Ref<Self>, f: &mut fmt::Formatter) -> fmt::Result {
+ let error = unsafe { Self::error(this) };
if f.alternate() {
return Debug::fmt(error, f);
@@ -38,11 +40,12 @@ impl ErrorImpl<()> {
}
}
- #[cfg(backtrace)]
+ #[cfg(feature = "std")]
{
+ use alloc::string::ToString;
use std::backtrace::BacktraceStatus;
- let backtrace = self.backtrace();
+ let backtrace = unsafe { Self::backtrace(this) };
if let BacktraceStatus::Captured = backtrace.status() {
let mut backtrace = backtrace.to_string();
write!(f, "\n\n")?;
@@ -100,6 +103,7 @@ where
#[cfg(test)]
mod tests {
use super::*;
+ use alloc::string::String;
#[test]
fn one_digit() {
### external/vendor/anyhow/src/kind.rs
@@ -40,21 +40,21 @@
// The anyhow! macro will set up the call in this form:
//
// #[allow(unused_imports)]
-// use $crate::private::{AdhocKind, TraitKind};
+// use $crate::__private::{AdhocKind, TraitKind};
// let error = $msg;
// (&error).anyhow_kind().new(error)
use crate::Error;
use core::fmt::{Debug, Display};
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
use crate::StdError;
-
-#[cfg(backtrace)]
-use std::backtrace::Backtrace;
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+use alloc::boxed::Box;
pub struct Adhoc;
+#[doc(hidden)]
pub trait AdhocKind: Sized {
#[inline]
fn anyhow_kind(&self) -> Adhoc {
@@ -65,16 +65,18 @@ pub trait AdhocKind: Sized {
impl<T> AdhocKind for &T where T: ?Sized + Display + Debug + Send + Sync + 'static {}
impl Adhoc {
+ #[cold]
pub fn new<M>(self, message: M) -> Error
where
M: Display + Debug + Send + Sync + 'static,
{
- Error::from_adhoc(message, backtrace!())
+ Error::construct_from_adhoc(message, backtrace!())
}
}
pub struct Trait;
+#[doc(hidden)]
pub trait TraitKind: Sized {
#[inline]
fn anyhow_kind(&self) -> Trait {
@@ -85,6 +87,7 @@ pub trait TraitKind: Sized {
impl<E> TraitKind for E where E: Into<Error> {}
impl Trait {
+ #[cold]
pub fn new<E>(self, error: E) -> Error
where
E: Into<Error>,
@@ -93,24 +96,26 @@ impl Trait {
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
pub struct Boxed;
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+#[doc(hidden)]
pub trait BoxedKind: Sized {
#[inline]
fn anyhow_kind(&self) -> Boxed {
Boxed
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl BoxedKind for Box<dyn StdError + Send + Sync> {}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl Boxed {
+ #[cold]
pub fn new(self, error: Box<dyn StdError + Send + Sync>) -> Error {
- let backtrace = backtrace_if_absent!(error);
- Error::from_boxed(error, backtrace)
+ let backtrace = backtrace_if_absent!(&*error);
+ Error::construct_from_boxed(error, backtrace)
}
}
### external/vendor/anyhow/src/lib.rs
@@ -2,7 +2,7 @@
//!
//! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github
//! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust
-//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logoColor=white&logo=data:image/svg+xml;base64,PHN2ZyByb2xlPSJpbWciIHhtbG5zPSJodHRwOi8vd3d3LnczLm9yZy8yMDAwL3N2ZyIgdmlld0JveD0iMCAwIDUxMiA1MTIiPjxwYXRoIGZpbGw9IiNmNWY1ZjUiIGQ9Ik00ODguNiAyNTAuMkwzOTIgMjE0VjEwNS41YzAtMTUtOS4zLTI4LjQtMjMuNC0zMy43bC0xMDAtMzcuNWMtOC4xLTMuMS0xNy4xLTMuMS0yNS4zIDBsLTEwMCAzNy41Yy0xNC4xIDUuMy0yMy40IDE4LjctMjMuNCAzMy43VjIxNGwtOTYuNiAzNi4yQzkuMyAyNTUuNSAwIDI2OC45IDAgMjgzLjlWMzk0YzAgMTMuNiA3LjcgMjYuMSAxOS45IDMyLjJsMTAwIDUwYzEwLjEgNS4xIDIyLjEgNS4xIDMyLjIgMGwxMDMuOS01MiAxMDMuOSA1MmMxMC4xIDUuMSAyMi4xIDUuMSAzMi4yIDBsMTAwLTUwYzEyLjItNi4xIDE5LjktMTguNiAxOS45LTMyLjJWMjgzLjljMC0xNS05LjMtMjguNC0yMy40LTMzLjd6TTM1OCAyMTQuOGwtODUgMzEuOXYtNjguMmw4NS0zN3Y3My4zek0xNTQgMTA0LjFsMTAyLTM4LjIgMTAyIDM4LjJ2LjZsLTEwMiA0MS40LTEwMi00MS40di0uNnptODQgMjkxLjFsLTg1IDQyLjV2LTc5LjFsODUtMzguOHY3NS40em0wLTExMmwtMTAyIDQxLjQtMTAyLTQxLjR2LS42bDEwMi0zOC4yIDEwMiAzOC4ydi42em0yNDAgMTEybC04NSA0Mi41di03OS4xbDg1LTM4Ljh2NzUuNHptMC0xMTJsLTEwMiA0MS40LTEwMi00MS40di0uNmwxMDItMzguMiAxMDIgMzguMnYuNnoiPjwvcGF0aD48L3N2Zz4K
+//! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs
//!
//! <br>
//!
@@ -17,7 +17,7 @@
//! the return type of any fallible function.
//!
//! Within the function, use `?` to easily propagate any error that implements
-//! the `std::error::Error` trait.
+//! the [`std::error::Error`] trait.
//!
//! ```
//! # pub trait Deserialize {}
@@ -128,7 +128,7 @@
//! # ;
//! ```
//!
-//! - If using the nightly channel, a backtrace is captured and printed with the
+//! - If using Rust ≥ 1.65, a backtrace is captured and printed with the
//! error if the underlying error type does not already provide its own. In
//! order to see backtraces, they must be enabled through the environment
//! variables described in [`std::backtrace`]:
@@ -139,10 +139,7 @@
//! - If you want only panics to have backtraces, set `RUST_BACKTRACE=1` and
//! `RUST_LIB_BACKTRACE=0`.
//!
-//! The tracking issue for this feature is [rust-lang/rust#53487].
-//!
-//! [`std::backtrace`]: https://doc.rust-lang.org/std/backtrace/index.html#environment-variables
-//! [rust-lang/rust#53487]: https://github.com/rust-lang/rust/issues/53487
+//! [`std::backtrace`]: std::backtrace#environment-variables
//!
//! - Anyhow works with any error type that has an impl of `std::error::Error`,
//! including ones defined in your crate. We do not bundle a `derive(Error)`
@@ -179,73 +176,113 @@
//! # }
//! ```
//!
+//! A `bail!` macro is provided as a shorthand for the same early return.
+//!
+//! ```
+//! # use anyhow::{bail, Result};
+//! #
+//! # fn demo() -> Result<()> {
+//! # let missing = "...";
+//! bail!("Missing attribute: {}", missing);
+//! # Ok(())
+//! # }
+//! ```
+//!
//! <br>
//!
//! # No-std support
//!
-//! In no_std mode, the same API is almost all available and works the same way.
-//! To depend on Anyhow in no_std mode, disable our default enabled "std"
+//! In no_std mode, almost all of the same API is available and works the same
+//! way. To depend on Anyhow in no_std mode, disable our default enabled "std"
//! feature in Cargo.toml. A global allocator is required.
//!
//! ```toml
//! [dependencies]
//! anyhow = { version = "1.0", default-features = false }
//! ```
//!
-//! Since the `?`-based error conversions would normally rely on the
-//! `std::error::Error` trait which is only available through std, no_std mode
-//! will require an explicit `.map_err(Error::msg)` when working with a
-//! non-Anyhow error type inside a function that returns Anyhow's error type.
+//! With versions of Rust older than 1.81, no_std mode may require an additional
+//! `.map_err(Error::msg)` when working with a non-Anyhow error type inside a
+//! function that returns Anyhow's error type, as the trait that `?`-based error
+//! conversions are defined by is only available in std in those old versions.
-#![doc(html_root_url = "https://docs.rs/anyhow/1.0.31")]
-#![cfg_attr(backtrace, feature(backtrace))]
-#![cfg_attr(doc_cfg, feature(doc_cfg))]
-#![cfg_attr(not(feature = "std"), no_std)]
+#![doc(html_root_url = "https://docs.rs/anyhow/1.0.104")]
+#![cfg_attr(error_generic_member_access, feature(error_generic_member_access))]
+#![no_std]
+#![deny(dead_code, unsafe_op_in_unsafe_fn, unused_imports, unused_mut)]
#![allow(
+ clippy::doc_markdown,
+ clippy::elidable_lifetime_names,
+ clippy::enum_glob_use,
+ clippy::explicit_auto_deref,
+ clippy::extra_unused_type_parameters,
+ clippy::incompatible_msrv,
+ clippy::let_underscore_untyped,
+ clippy::missing_errors_doc,
+ clippy::missing_panics_doc,
+ clippy::module_name_repetitions,
+ clippy::must_use_candidate,
clippy::needless_doctest_main,
+ clippy::needless_lifetimes,
clippy::new_ret_no_self,
+ clippy::redundant_else,
+ clippy::return_self_not_must_use,
+ clippy::struct_field_names,
+ clippy::uninlined_format_args,
+ clippy::unused_self,
+ clippy::used_underscore_binding,
+ clippy::wildcard_imports,
clippy::wrong_self_convention
)]
+#![allow(unknown_lints, mismatched_lifetime_syntaxes)]
-mod alloc {
- #[cfg(not(feature = "std"))]
- extern crate alloc;
+#[cfg(all(
+ anyhow_nightly_testing,
+ feature = "std",
+ not(error_generic_member_access)
+))]
+compile_error!("Build script probe failed to compile.");
- #[cfg(not(feature = "std"))]
- pub use alloc::boxed::Box;
+extern crate alloc;
- #[cfg(feature = "std")]
- pub use std::boxed::Box;
-}
+#[cfg(feature = "std")]
+extern crate std;
#[macro_use]
mod backtrace;
mod chain;
mod context;
+mod ensure;
mod error;
mod fmt;
mod kind;
mod macros;
+#[cfg(error_generic_member_access)]
+mod nightly;
+mod ptr;
mod wrapper;
-use crate::alloc::Box;
use crate::error::ErrorImpl;
+use crate::ptr::Own;
use core::fmt::Display;
-use core::mem::ManuallyDrop;
-#[cfg(not(feature = "std"))]
+#[cfg(all(not(feature = "std"), anyhow_no_core_error))]
use core::fmt::Debug;
#[cfg(feature = "std")]
use std::error::Error as StdError;
-#[cfg(not(feature = "std"))]
+#[cfg(not(any(feature = "std", anyhow_no_core_error)))]
+use core::error::Error as StdError;
+
+#[cfg(all(not(feature = "std"), anyhow_no_core_error))]
trait StdError: Debug + Display {
fn source(&self) -> Option<&(dyn StdError + 'static)> {
None
}
}
+#[doc(no_inline)]
pub use anyhow as format_err;
/// The `Error` type, a wrapper around a dynamic error type.
@@ -349,8 +386,9 @@ pub use anyhow as format_err;
/// # Ok(())
/// }
/// ```
+#[repr(transparent)]
pub struct Error {
- inner: ManuallyDrop<Box<ErrorImpl<()>>>,
+ inner: Own<ErrorImpl>,
}
/// Iterator of a chain of source errors.
@@ -372,7 +410,7 @@ pub struct Error {
/// None
/// }
/// ```
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
#[derive(Clone)]
pub struct Chain<'a> {
state: crate::chain::ChainState<'a>,
@@ -477,6 +515,11 @@ pub type Result<T, E = Error> = core::result::Result<T, E>;
/// No such file or directory (os error 2)
/// ```
///
+/// Refer to the [Display representations] documentation for other forms in
+/// which this context chain can be rendered.
+///
+/// [Display representations]: Error#display-representations
+///
/// <br>
///
/// # Effect on downcasting
@@ -584,29 +627,102 @@ pub trait Context<T, E>: context::private::Sealed {
F: FnOnce() -> C;
}
+/// Equivalent to `Ok::<_, anyhow::Error>(value)`.
+///
+/// This simplifies creation of an `anyhow::Result` in places where type
+/// inference cannot deduce the `E` type of the result — without needing
+/// to write `Ok::<_, anyhow::Error>(value)`.
+///
+/// One might think that `anyhow::Result::Ok(value)` would work in such cases
+/// but it does not.
+///
+/// ```console
+/// error[E0282]: type annotations needed for `std::result::Result<i32, E>`
+/// --> src/main.rs:11:13
+/// |
+/// 11 | let _ = anyhow::Result::Ok(1);
+/// | - ^^^^^^^^^^^^^^^^^^ cannot infer type for type parameter `E` declared on the enum `Result`
+/// | |
+/// | consider giving this pattern the explicit type `std::result::Result<i32, E>`, where the type parameter `E` is specified
+/// ```
+#[allow(non_snake_case)]
+#[inline]
+pub fn Ok<T>(value: T) -> Result<T> {
+ Result::Ok(value)
+}
+
// Not public API. Referenced by macro-generated code.
#[doc(hidden)]
-pub mod private {
+pub mod __private {
+ use self::not::Bool;
use crate::Error;
- use core::fmt::{Debug, Display};
-
- #[cfg(backtrace)]
- use std::backtrace::Backtrace;
+ use alloc::fmt;
+ use core::fmt::Arguments;
+ #[doc(hidden)]
+ pub use crate::ensure::{BothDebug, NotBothDebug};
+ #[doc(hidden)]
+ pub use alloc::format;
+ #[doc(hidden)]
pub use core::result::Result::Err;
+ #[doc(hidden)]
+ pub use core::{concat, format_args, stringify};
#[doc(hidden)]
pub mod kind {
+ #[doc(hidden)]
pub use crate::kind::{AdhocKind, TraitKind};
- #[cfg(feature = "std")]
+ #[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+ #[doc(hidden)]
pub use crate::kind::BoxedKind;
}
- pub fn new_adhoc<M>(message: M) -> Error
- where
- M: Display + Debug + Send + Sync + 'static,
- {
- Error::from_adhoc(message, backtrace!())
+ #[doc(hidden)]
+ #[inline]
+ #[cold]
+ pub fn format_err(args: Arguments) -> Error {
+ if let Some(message) = args.as_str() {
+ // anyhow!("literal"), can downcast to &'static str
+ Error::msg(message)
+ } else {
+ // anyhow!("interpolate {var}"), can downcast to String
+ Error::msg(fmt::format(args))
+ }
+ }
+
+ #[doc(hidden)]
+ #[inline]
+ #[cold]
+ #[must_use]
+ pub fn must_use(error: Error) -> Error {
+ error
+ }
+
+ #[doc(hidden)]
+ #[inline]
+ pub fn not(cond: impl Bool) -> bool {
+ cond.not()
+ }
+
+ mod not {
+ #[doc(hidden)]
+ pub trait Bool {
+ fn not(self) -> bool;
+ }
+
+ impl Bool for bool {
+ #[inline]
+ fn not(self) -> bool {
+ !self
+ }
+ }
+
+ impl Bool for &bool {
+ #[inline]
+ fn not(self) -> bool {
+ !*self
+ }
+ }
}
}
### external/vendor/anyhow/src/macros.rs
@@ -1,6 +1,12 @@
/// Return early with an error.
///
-/// This macro is equivalent to `return Err(From::from($err))`.
+/// This macro is equivalent to
+/// <code>return Err([anyhow!($args\...)][anyhow!])</code>.
+///
+/// The surrounding function's or closure's return value is required to be
+/// <code>Result<_, [anyhow::Error][crate::Error]></code>.
+///
+/// [anyhow!]: crate::anyhow
///
/// # Example
///
@@ -48,86 +54,134 @@
/// # }
/// ```
#[macro_export]
+#[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
macro_rules! bail {
($msg:literal $(,)?) => {
- return $crate::private::Err($crate::anyhow!($msg));
+ return $crate::__private::Err($crate::__anyhow!($msg))
};
($err:expr $(,)?) => {
- return $crate::private::Err($crate::anyhow!($err));
+ return $crate::__private::Err($crate::__anyhow!($err))
};
($fmt:expr, $($arg:tt)*) => {
- return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*))
};
}
-/// Return early with an error if a condition is not satisfied.
-///
-/// This macro is equivalent to `if !$cond { return Err(From::from($err)); }`.
-///
-/// Analogously to `assert!`, `ensure!` takes a condition and exits the function
-/// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
-/// rather than panicking.
-///
-/// # Example
-///
-/// ```
-/// # use anyhow::{ensure, Result};
-/// #
-/// # fn main() -> Result<()> {
-/// # let user = 0;
-/// #
-/// ensure!(user == 0, "only user 0 is allowed");
-/// # Ok(())
-/// # }
-/// ```
-///
-/// ```
-/// # use anyhow::{ensure, Result};
-/// # use thiserror::Error;
-/// #
-/// # const MAX_DEPTH: usize = 1;
-/// #
-/// #[derive(Error, Debug)]
-/// enum ScienceError {
-/// #[error("recursion limit exceeded")]
-/// RecursionLimitExceeded,
-/// # #[error("...")]
-/// # More = (stringify! {
-/// ...
-/// # }, 1).1,
-/// }
-///
-/// # fn main() -> Result<()> {
-/// # let depth = 0;
-/// #
-/// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
-/// # Ok(())
-/// # }
-/// ```
-#[macro_export]
-macro_rules! ensure {
- ($cond:expr, $msg:literal $(,)?) => {
- if !$cond {
- return $crate::private::Err($crate::anyhow!($msg));
- }
- };
- ($cond:expr, $err:expr $(,)?) => {
- if !$cond {
- return $crate::private::Err($crate::anyhow!($err));
- }
- };
- ($cond:expr, $fmt:expr, $($arg:tt)*) => {
- if !$cond {
- return $crate::private::Err($crate::anyhow!($fmt, $($arg)*));
- }
+macro_rules! __ensure {
+ ($ensure:item) => {
+ /// Return early with an error if a condition is not satisfied.
+ ///
+ /// This macro is equivalent to
+ /// <code>if !$cond { return Err([anyhow!($args\...)][anyhow!]); }</code>.
+ ///
+ /// The surrounding function's or closure's return value is required to be
+ /// <code>Result<_, [anyhow::Error][crate::Error]></code>.
+ ///
+ /// Analogously to `assert!`, `ensure!` takes a condition and exits the function
+ /// if the condition fails. Unlike `assert!`, `ensure!` returns an `Error`
+ /// rather than panicking.
+ ///
+ /// [anyhow!]: crate::anyhow
+ ///
+ /// # Example
+ ///
+ /// ```
+ /// # use anyhow::{ensure, Result};
+ /// #
+ /// # fn main() -> Result<()> {
+ /// # let user = 0;
+ /// #
+ /// ensure!(user == 0, "only user 0 is allowed");
+ /// # Ok(())
+ /// # }
+ /// ```
+ ///
+ /// ```
+ /// # use anyhow::{ensure, Result};
+ /// # use thiserror::Error;
+ /// #
+ /// # const MAX_DEPTH: usize = 1;
+ /// #
+ /// #[derive(Error, Debug)]
+ /// enum ScienceError {
+ /// #[error("recursion limit exceeded")]
+ /// RecursionLimitExceeded,
+ /// # #[error("...")]
+ /// # More = (stringify! {
+ /// ...
+ /// # }, 1).1,
+ /// }
+ ///
+ /// # fn main() -> Result<()> {
+ /// # let depth = 0;
+ /// #
+ /// ensure!(depth <= MAX_DEPTH, ScienceError::RecursionLimitExceeded);
+ /// # Ok(())
+ /// # }
+ /// ```
+ $ensure
};
}
-/// Construct an ad-hoc error from a string.
+#[cfg(doc)]
+__ensure![
+ #[macro_export]
+ macro_rules! ensure {
+ ($cond:expr $(,)?) => {
+ if !$cond {
+ return $crate::__private::Err($crate::Error::msg(
+ $crate::__private::concat!("Condition failed: `", $crate::__private::stringify!($cond), "`")
+ ));
+ }
+ };
+ ($cond:expr, $msg:literal $(,)?) => {
+ if !$cond {
+ return $crate::__private::Err($crate::__anyhow!($msg));
+ }
+ };
+ ($cond:expr, $err:expr $(,)?) => {
+ if !$cond {
+ return $crate::__private::Err($crate::__anyhow!($err));
+ }
+ };
+ ($cond:expr, $fmt:expr, $($arg:tt)*) => {
+ if !$cond {
+ return $crate::__private::Err($crate::__anyhow!($fmt, $($arg)*));
+ }
+ };
+ }
+];
+
+#[cfg(not(doc))]
+__ensure![
+ #[macro_export]
+ #[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
+ macro_rules! ensure {
+ ($($tt:tt)*) => {
+ $crate::__parse_ensure!(
+ /* state */ 0
+ /* stack */ ()
+ /* bail */ ($($tt)*)
+ /* fuel */ (~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~ ~~~~~~~~~~)
+ /* parse */ {()}
+ /* dup */ ($($tt)*)
+ /* rest */ $($tt)*
+ )
+ };
+ }
+];
+
+/// Construct an ad-hoc error from a string or existing non-`anyhow` error
+/// value.
///
-/// This evaluates to an `Error`. It can take either just a string, or a format
-/// string with arguments. It also can take any custom type which implements
-/// `Debug` and `Display`.
+/// This evaluates to an [`Error`][crate::Error]. It can take either just a
+/// string, or a format string with arguments. It also can take any custom type
+/// which implements `Debug` and `Display`.
+///
+/// If called with a single argument whose type implements `std::error::Error`
+/// (in addition to `Debug` and `Display`, which are always required), then that
+/// Error impl's `source` is preserved as the `source` of the resulting
+/// `anyhow::Error`.
///
/// # Example
///
@@ -146,18 +200,46 @@ macro_rules! ensure {
/// }
/// ```
#[macro_export]
+#[cfg_attr(not(anyhow_no_clippy_format_args), clippy::format_args)]
macro_rules! anyhow {
($msg:literal $(,)?) => {
- // Handle $:literal as a special case to make cargo-expanded code more
- // concise in the common case.
- $crate::private::new_adhoc($msg)
+ $crate::__private::must_use({
+ let error = $crate::__private::format_err($crate::__private::format_args!($msg));
+ error
+ })
+ };
+ ($err:expr $(,)?) => {
+ $crate::__private::must_use({
+ use $crate::__private::kind::*;
+ let error = match $err {
+ error => (&error).anyhow_kind().new(error),
+ };
+ error
+ })
};
+ ($fmt:expr, $($arg:tt)*) => {
+ $crate::Error::msg($crate::__private::format!($fmt, $($arg)*))
+ };
+}
+
+// Not public API. This is used in the implementation of some of the other
+// macros, in which the must_use call is not needed because the value is known
+// to be used.
+#[doc(hidden)]
+#[macro_export]
+macro_rules! __anyhow {
+ ($msg:literal $(,)?) => ({
+ let error = $crate::__private::format_err($crate::__private::format_args!($msg));
+ error
+ });
($err:expr $(,)?) => ({
- use $crate::private::kind::*;
- let error = $err;
- (&error).anyhow_kind().new(error)
+ use $crate::__private::kind::*;
+ let error = match $err {
+ error => (&error).anyhow_kind().new(error),
+ };
+ error
});
($fmt:expr, $($arg:tt)*) => {
- $crate::private::new_adhoc(format!($fmt, $($arg)*))
+ $crate::Error::msg($crate::__private::format!($fmt, $($arg)*))
};
}
### external/vendor/anyhow/src/nightly.rs
@@ -0,0 +1,58 @@
+// This code exercises the surface area that we expect of the Error generic
+// member access API. If the current toolchain is able to compile it, then
+// anyhow is able to provide backtrace support.
+
+#![cfg_attr(anyhow_build_probe, feature(error_generic_member_access))]
+
+use core::error::{self, Error};
+use std::backtrace::Backtrace;
+
+pub use core::error::Request;
+
+#[cfg(anyhow_build_probe)]
+const _: () = {
+ use core::fmt::{self, Debug, Display};
+
+ struct MyError(Backtrace);
+
+ impl Debug for MyError {
+ fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
+ unimplemented!()
+ }
+ }
+
+ impl Display for MyError {
+ fn fmt(&self, _formatter: &mut fmt::Formatter) -> fmt::Result {
+ unimplemented!()
+ }
+ }
+
+ impl Error for MyError {
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ provide_ref_backtrace(request, &self.0);
+ }
+ }
+};
+
+// Include in sccache cache key.
+#[cfg(anyhow_build_probe)]
+const _: Option<&str> = option_env!("RUSTC_BOOTSTRAP");
+
+pub fn request_ref_backtrace(err: &dyn Error) -> Option<&Backtrace> {
+ request_ref::<Backtrace>(err)
+}
+
+fn request_ref<'a, T>(err: &'a (impl Error + ?Sized)) -> Option<&'a T>
+where
+ T: 'static + ?Sized,
+{
+ error::request_ref::<T>(err)
+}
+
+pub fn provide_ref_backtrace<'a>(request: &mut Request<'a>, backtrace: &'a Backtrace) {
+ Request::provide_ref(request, backtrace);
+}
+
+pub fn provide<'a>(err: &'a (impl Error + ?Sized), request: &mut Request<'a>) {
+ Error::provide(err, request);
+}
### external/vendor/anyhow/src/ptr.rs
@@ -0,0 +1,187 @@
+use alloc::boxed::Box;
+use core::marker::PhantomData;
+use core::ptr::NonNull;
+
+#[repr(transparent)]
+pub struct Own<T>
+where
+ T: ?Sized,
+{
+ pub ptr: NonNull<T>,
+}
+
+unsafe impl<T> Send for Own<T> where T: ?Sized {}
+
+unsafe impl<T> Sync for Own<T> where T: ?Sized {}
+
+impl<T> Copy for Own<T> where T: ?Sized {}
+
+impl<T> Clone for Own<T>
+where
+ T: ?Sized,
+{
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<T> Own<T>
+where
+ T: ?Sized,
+{
+ pub fn new(ptr: Box<T>) -> Self {
+ Own {
+ ptr: unsafe { NonNull::new_unchecked(Box::into_raw(ptr)) },
+ }
+ }
+
+ pub fn cast<U: CastTo>(self) -> Own<U::Target> {
+ Own {
+ ptr: self.ptr.cast(),
+ }
+ }
+
+ pub unsafe fn boxed(self) -> Box<T> {
+ unsafe { Box::from_raw(self.ptr.as_ptr()) }
+ }
+
+ pub fn by_ref(&self) -> Ref<T> {
+ Ref {
+ ptr: self.ptr,
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn by_mut(&mut self) -> Mut<T> {
+ Mut {
+ ptr: self.ptr,
+ lifetime: PhantomData,
+ }
+ }
+}
+
+#[repr(transparent)]
+pub struct Ref<'a, T>
+where
+ T: ?Sized,
+{
+ pub ptr: NonNull<T>,
+ lifetime: PhantomData<&'a T>,
+}
+
+impl<'a, T> Copy for Ref<'a, T> where T: ?Sized {}
+
+impl<'a, T> Clone for Ref<'a, T>
+where
+ T: ?Sized,
+{
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<'a, T> Ref<'a, T>
+where
+ T: ?Sized,
+{
+ pub fn new(ptr: &'a T) -> Self {
+ Ref {
+ ptr: NonNull::from(ptr),
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn from_raw(ptr: NonNull<T>) -> Self {
+ Ref {
+ ptr,
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn cast<U: CastTo>(self) -> Ref<'a, U::Target> {
+ Ref {
+ ptr: self.ptr.cast(),
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn by_mut(self) -> Mut<'a, T> {
+ Mut {
+ ptr: self.ptr,
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn as_ptr(self) -> *const T {
+ self.ptr.as_ptr().cast_const()
+ }
+
+ pub unsafe fn deref(self) -> &'a T {
+ unsafe { &*self.ptr.as_ptr() }
+ }
+}
+
+#[repr(transparent)]
+pub struct Mut<'a, T>
+where
+ T: ?Sized,
+{
+ pub ptr: NonNull<T>,
+ lifetime: PhantomData<&'a mut T>,
+}
+
+impl<'a, T> Copy for Mut<'a, T> where T: ?Sized {}
+
+impl<'a, T> Clone for Mut<'a, T>
+where
+ T: ?Sized,
+{
+ fn clone(&self) -> Self {
+ *self
+ }
+}
+
+impl<'a, T> Mut<'a, T>
+where
+ T: ?Sized,
+{
+ pub fn cast<U: CastTo>(self) -> Mut<'a, U::Target> {
+ Mut {
+ ptr: self.ptr.cast(),
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn by_ref(self) -> Ref<'a, T> {
+ Ref {
+ ptr: self.ptr,
+ lifetime: PhantomData,
+ }
+ }
+
+ pub fn extend<'b>(self) -> Mut<'b, T> {
+ Mut {
+ ptr: self.ptr,
+ lifetime: PhantomData,
+ }
+ }
+
+ pub unsafe fn deref_mut(self) -> &'a mut T {
+ unsafe { &mut *self.ptr.as_ptr() }
+ }
+}
+
+impl<'a, T> Mut<'a, T> {
+ pub unsafe fn read(self) -> T {
+ unsafe { self.ptr.as_ptr().read() }
+ }
+}
+
+// Force turbofish on all calls of `.cast::<U>()`.
+pub trait CastTo {
+ type Target;
+}
+
+impl<T> CastTo for T {
+ type Target = T;
+}
### external/vendor/anyhow/src/wrapper.rs
@@ -1,6 +1,12 @@
use crate::StdError;
use core::fmt::{self, Debug, Display};
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
+use alloc::boxed::Box;
+
+#[cfg(error_generic_member_access)]
+use crate::nightly::{self, Request};
+
#[repr(transparent)]
pub struct MessageError<M>(pub M);
@@ -47,32 +53,32 @@ where
impl<M> StdError for DisplayError<M> where M: Display + 'static {}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
#[repr(transparent)]
pub struct BoxedError(pub Box<dyn StdError + Send + Sync>);
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl Debug for BoxedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Debug::fmt(&self.0, f)
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl Display for BoxedError {
fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
Display::fmt(&self.0, f)
}
}
-#[cfg(feature = "std")]
+#[cfg(any(feature = "std", not(anyhow_no_core_error)))]
impl StdError for BoxedError {
- #[cfg(backtrace)]
- fn backtrace(&self) -> Option<&crate::backtrace::Backtrace> {
- self.0.backtrace()
- }
-
fn source(&self) -> Option<&(dyn StdError + 'static)> {
self.0.source()
}
+
+ #[cfg(error_generic_member_access)]
+ fn provide<'a>(&'a self, request: &mut Request<'a>) {
+ nightly::provide(&*self.0, request);
+ }
}
### external/vendor/anyhow/tests/compiletest.rs
@@ -1,4 +1,5 @@
-#[rustversion::attr(not(nightly), ignore)]
+#[rustversion::attr(not(nightly), ignore = "requires nightly")]
+#[cfg_attr(miri, ignore = "incompatible with miri")]
#[test]
fn ui() {
let t = trybuild::TestCases::new();
### external/vendor/anyhow/tests/drop/mod.rs
@@ -1,7 +1,8 @@
+#![allow(clippy::module_name_repetitions)]
+
use std::error::Error as StdError;
use std::fmt::{self, Display};
-use std::sync::atomic::AtomicBool;
-use std::sync::atomic::Ordering::SeqCst;
+use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::Arc;
#[derive(Debug)]
@@ -17,7 +18,7 @@ impl Flag {
}
pub fn get(&self) -> bool {
- self.atomic.load(SeqCst)
+ self.atomic.load(Ordering::Relaxed)
}
}
@@ -46,7 +47,7 @@ impl Display for DetectDrop {
impl Drop for DetectDrop {
fn drop(&mut self) {
- let already_dropped = self.has_dropped.atomic.swap(true, SeqCst);
+ let already_dropped = self.has_dropped.atomic.swap(true, Ordering::Relaxed);
assert!(!already_dropped);
}
}
### external/vendor/anyhow/tests/test_autotrait.rs
@@ -1,4 +1,7 @@
+#![allow(clippy::extra_unused_type_parameters)]
+
use anyhow::Error;
+use std::panic::{RefUnwindSafe, UnwindSafe};
#[test]
fn test_send() {
@@ -11,3 +14,21 @@ fn test_sync() {
fn assert_sync<T: Sync>() {}
assert_sync::<Error>();
}
+
+#[test]
+fn test_unwind_safe() {
+ fn assert_unwind_safe<T: UnwindSafe>() {}
+ assert_unwind_safe::<Error>();
+}
+
+#[test]
+fn test_ref_unwind_safe() {
+ fn assert_ref_unwind_safe<T: RefUnwindSafe>() {}
+ assert_ref_unwind_safe::<Error>();
+}
+
+#[test]
+fn test_unpin() {
+ fn assert_unpin<T: Unpin>() {}
+ assert_unpin::<Error>();
+}
### external/vendor/anyhow/tests/test_backtrace.rs
@@ -1,5 +1,7 @@
+#![allow(clippy::let_underscore_untyped)]
+
#[rustversion::not(nightly)]
-#[ignore]
+#[ignore = "requires nightly"]
#[test]
fn test_backtrace() {}
### external/vendor/anyhow/tests/test_boxed.rs
@@ -1,3 +1,8 @@
+#![allow(
+ // Clippy bug: https://github.com/rust-lang/rust-clippy/issues/7422
+ clippy::nonstandard_macro_braces,
+)]
+
use anyhow::anyhow;
use std::error::Error as StdError;
use std::io;
### external/vendor/anyhow/tests/test_chain.rs
@@ -1,7 +1,7 @@
-use anyhow::{anyhow, Error};
+use anyhow::{anyhow, Chain, Error};
fn error() -> Error {
- anyhow!(0).context(1).context(2).context(3)
+ anyhow!({ 0 }).context(1).context(2).context(3)
}
#[test]
@@ -33,13 +33,37 @@ fn test_len() {
let e = error();
let mut chain = e.chain();
assert_eq!(4, chain.len());
+ assert_eq!((4, Some(4)), chain.size_hint());
assert_eq!("3", chain.next().unwrap().to_string());
assert_eq!(3, chain.len());
+ assert_eq!((3, Some(3)), chain.size_hint());
assert_eq!("0", chain.next_back().unwrap().to_string());
assert_eq!(2, chain.len());
+ assert_eq!((2, Some(2)), chain.size_hint());
assert_eq!("2", chain.next().unwrap().to_string());
assert_eq!(1, chain.len());
+ assert_eq!((1, Some(1)), chain.size_hint());
assert_eq!("1", chain.next_back().unwrap().to_string());
assert_eq!(0, chain.len());
+ assert_eq!((0, Some(0)), chain.size_hint());
assert!(chain.next().is_none());
}
+
+#[test]
+fn test_default() {
+ let mut c = Chain::default();
+ assert!(c.next().is_none());
+}
+
+#[test]
+#[allow(clippy::redundant_clone)]
+fn test_clone() {
+ let e = error();
+ let mut chain = e.chain().clone();
+ assert_eq!("3", chain.next().unwrap().to_string());
+ assert_eq!("2", chain.next().unwrap().to_string());
+ assert_eq!("1", chain.next().unwrap().to_string());
+ assert_eq!("0", chain.next().unwrap().to_string());
+ assert!(chain.next().is_none());
+ assert!(chain.next_back().is_none());
+}
### external/vendor/anyhow/tests/test_context.rs
@@ -1,3 +1,8 @@
+#![allow(
+ // Clippy bug: https://github.com/rust-lang/rust-clippy/issues/7422
+ clippy::nonstandard_macro_braces,
+)]
+
mod drop;
use crate::drop::{DetectDrop, Flag};
@@ -19,6 +24,7 @@ macro_rules! context_type {
#[derive(Debug)]
struct $name {
message: &'static str,
+ #[allow(dead_code)]
drop: DetectDrop,
}
@@ -157,3 +163,33 @@ fn test_unsuccessful_downcast() {
drop(err);
assert!(dropped.all());
}
+
+#[test]
+fn test_downcast_mut() {
+ let (mut err, dropped) = make_chain();
+
+ err.downcast_mut::<HighLevel>().unwrap().message = "high context";
+ err.downcast_mut::<MidLevel>().unwrap().message = "mid context";
+ err.downcast_mut::<LowLevel>().unwrap().message = "low error";
+
+ assert_eq!(
+ err.downcast_ref::<HighLevel>().unwrap().message,
+ "high context",
+ );
+ assert_eq!(
+ err.downcast_ref::<MidLevel>().unwrap().message,
+ "mid context",
+ );
+ assert_eq!(err.downcast_ref::<LowLevel>().unwrap().message, "low error");
+
+ assert!(dropped.none());
+ drop(err);
+ assert!(dropped.all());
+}
+
+#[test]
+fn test_root_cause() {
+ let (err, _) = make_chain();
+
+ assert_eq!(err.root_cause().to_string(), "no such file or directory");
+}
### external/vendor/anyhow/tests/test_convert.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::unnecessary_wraps)]
+
mod drop;
use self::drop::{DetectDrop, Flag};
@@ -6,6 +8,26 @@ use std::error::Error as StdError;
#[test]
fn test_convert() {
+ let has_dropped = Flag::new();
+ let error = Error::new(DetectDrop::new(&has_dropped));
+ let box_dyn = Box::<dyn StdError>::from(error);
+ assert_eq!("oh no!", box_dyn.to_string());
+ drop(box_dyn);
+ assert!(has_dropped.get());
+}
+
+#[test]
+fn test_convert_send() {
+ let has_dropped = Flag::new();
+ let error = Error::new(DetectDrop::new(&has_dropped));
+ let box_dyn = Box::<dyn StdError + Send>::from(error);
+ assert_eq!("oh no!", box_dyn.to_string());
+ drop(box_dyn);
+ assert!(has_dropped.get());
+}
+
+#[test]
+fn test_convert_send_sync() {
let has_dropped = Flag::new();
let error = Error::new(DetectDrop::new(&has_dropped));
let box_dyn = Box::<dyn StdError + Send + Sync>::from(error);
### external/vendor/anyhow/tests/test_downcast.rs
@@ -1,3 +1,5 @@
+#![allow(clippy::assertions_on_result_states, clippy::wildcard_imports)]
+
mod common;
mod drop;
@@ -66,6 +68,12 @@ fn test_downcast_mut() {
.unwrap()
.to_string(),
);
+
+ let mut bailed = bail_fmt().unwrap_err();
+ *bailed.downcast_mut::<String>().unwrap() = "clobber".to_string();
+ assert_eq!(bailed.downcast_ref::<String>().unwrap(), "clobber");
+ assert_eq!(bailed.downcast_mut::<String>().unwrap(), "clobber");
+ assert_eq!(bailed.downcast::<String>().unwrap(), "clobber");
}
#[test]
@@ -76,6 +84,15 @@ fn test_drop() {
assert!(has_dropped.get());
}
+#[test]
+fn test_as_ref() {
+ let error = bail_error().unwrap_err();
+ let ref_dyn: &dyn StdError = error.as_ref();
+ assert_eq!("oh no!", ref_dyn.to_string());
+ let ref_dyn_send_sync: &(dyn StdError + Send + Sync) = error.as_ref();
+ assert_eq!("oh no!", ref_dyn_send_sync.to_string());
+}
+
#[test]
fn test_large_alignment() {
#[repr(align(64))]
### external/vendor/anyhow/tests/test_ensure.rs
@@ -0,0 +1,756 @@
+#![allow(
+ clippy::bool_to_int_with_if,
+ clippy::char_lit_as_u8,
+ clippy::deref_addrof,
+ clippy::diverging_sub_expression,
+ clippy::erasing_op,
+ clippy::extra_unused_type_parameters,
+ clippy::if_same_then_else,
+ clippy::ifs_same_cond,
+ clippy::ignored_unit_patterns,
+ clippy::items_after_statements,
+ clippy::let_and_return,
+ clippy::let_underscore_untyped,
+ clippy::literal_string_with_formatting_args,
+ clippy::match_bool,
+ clippy::needless_else,
+ clippy::never_loop,
+ clippy::overly_complex_bool_expr,
+ clippy::ptr_cast_constness,
+ clippy::redundant_closure_call,
+ clippy::redundant_pattern_matching,
+ clippy::too_many_lines,
+ clippy::uninlined_format_args,
+ clippy::unit_arg,
+ clippy::unnecessary_cast,
+ clippy::while_immutable_condition,
+ clippy::zero_ptr,
+ irrefutable_let_patterns
+)]
+
+use self::Enum::Generic;
+use anyhow::{anyhow, ensure, Chain, Error, Result};
+use std::fmt::{self, Debug};
+use std::iter;
+use std::marker::{PhantomData, PhantomData as P};
+use std::mem;
+use std::ops::Add;
+use std::ptr;
+
+struct S;
+
+impl<T> Add<T> for S {
+ type Output = bool;
+ fn add(self, rhs: T) -> Self::Output {
+ let _ = rhs;
+ false
+ }
+}
+
+trait Trait: Sized {
+ const V: usize = 0;
+ fn t(self, i: i32) -> i32 {
+ i
+ }
+}
+
+impl<T> Trait for T {}
+
+enum Enum<T: ?Sized> {
+ #[allow(dead_code)]
+ Thing(PhantomData<T>),
+ Generic,
+}
+
+impl<T: ?Sized> PartialEq for Enum<T> {
+ fn eq(&self, rhs: &Self) -> bool {
+ mem::discriminant(self) == mem::discriminant(rhs)
+ }
+}
+
+impl<T: ?Sized> Debug for Enum<T> {
+ fn fmt(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
+ formatter.write_str("Generic")
+ }
+}
+
+#[track_caller]
+fn assert_err<T: Debug>(result: impl FnOnce() -> Result<T>, expected: &'static str) {
+ let actual = result().unwrap_err().to_string();
+
+ // In general different rustc versions will format the interpolated lhs and
+ // rhs $:expr fragment with insignificant differences in whitespace or
+ // punctuation, so we check the message in full against nightly and do just
+ // a cursory test on older toolchains.
+ if rustversion::cfg!(nightly) && !cfg!(miri) {
+ assert_eq!(actual, expected);
+ } else {
+ assert_eq!(actual.contains(" vs "), expected.contains(" vs "));
+ }
+}
+
+#[test]
+fn test_recursion() {
+ // Must not blow the default #[recursion_limit], which is 128.
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false |
+ false | false | false | false | false | false | false | false | false
+ ));
+
+ test().unwrap_err();
+}
+
+#[test]
+fn test_low_precedence_control_flow() {
+ #[allow(unreachable_code)]
+ let test = || {
+ let val = loop {
+ // Break has lower precedence than the comparison operators so the
+ // expression here is `S + (break (1 == 1))`. It would be bad if the
+ // ensure macro partitioned this input into `(S + break 1) == (1)`
+ // because that means a different thing than what was written.
+ ensure!(S + break 1 == 1);
+ };
+ Ok(val)
+ };
+
+ assert!(test().unwrap());
+}
+
+#[test]
+fn test_low_precedence_binary_operator() {
+ // Must not partition as `false == (true && false)`.
+ let test = || Ok(ensure!(false == true && false));
+ assert_err(test, "Condition failed: `false == true && false`");
+
+ // But outside the root level, it is fine.
+ let test = || Ok(ensure!(while false == true && false {} < ()));
+ assert_err(
+ test,
+ "Condition failed: `while false == true && false {} < ()` (() vs ())",
+ );
+
+ let a = 15;
+ let b = 3;
+ let test = || Ok(ensure!(a <= b || a - b <= 10));
+ assert_err(test, "Condition failed: `a <= b || a - b <= 10`");
+}
+
+#[test]
+fn test_high_precedence_binary_operator() {
+ let a = 15;
+ let b = 3;
+ let test = || Ok(ensure!(a - b <= 10));
+ assert_err(test, "Condition failed: `a - b <= 10` (12 vs 10)");
+}
+
+#[test]
+fn test_closure() {
+ // Must not partition as `(S + move) || (1 == 1)` by treating move as an
+ // identifier, nor as `(S + move || 1) == (1)` by misinterpreting the
+ // closure precedence.
+ let test = || Ok(ensure!(S + move || 1 == 1));
+ assert_err(test, "Condition failed: `S + move || 1 == 1`");
+
+ let test = || Ok(ensure!(S + || 1 == 1));
+ assert_err(test, "Condition failed: `S + || 1 == 1`");
+
+ // Must not partition as `S + ((move | ()) | 1) == 1` by treating those
+ // pipes as bitwise-or.
+ let test = || Ok(ensure!(S + move |()| 1 == 1));
+ assert_err(test, "Condition failed: `S + move |()| 1 == 1`");
+
+ let test = || Ok(ensure!(S + |()| 1 == 1));
+ assert_err(test, "Condition failed: `S + |()| 1 == 1`");
+}
+
+#[test]
+fn test_unary() {
+ let mut x = &1;
+ let test = || Ok(ensure!(*x == 2));
+ assert_err(test, "Condition failed: `*x == 2` (1 vs 2)");
+
+ let test = || Ok(ensure!(!x == 1));
+ assert_err(test, "Condition failed: `!x == 1` (-2 vs 1)");
+
+ let test = || Ok(ensure!(-x == 1));
+ assert_err(test, "Condition failed: `-x == 1` (-1 vs 1)");
+
+ let test = || Ok(ensure!(&x == &&2));
+ assert_err(test, "Condition failed: `&x == &&2` (1 vs 2)");
+
+ let test = || Ok(ensure!(&mut x == *&&mut &2));
+ assert_err(test, "Condition failed: `&mut x == *&&mut &2` (1 vs 2)");
+}
+
+#[rustversion::since(1.82)]
+#[test]
+fn test_raw_addr() {
+ let mut x = 1;
+ let test = || Ok(ensure!(S + &raw const x != S + &raw mut x));
+ assert_err(
+ test,
+ "Condition failed: `S + &raw const x != S + &raw mut x` (false vs false)",
+ );
+}
+
+#[test]
+fn test_if() {
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if false {}.t(1) == 2));
+ assert_err(test, "Condition failed: `if false {}.t(1) == 2` (1 vs 2)");
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if false {} else {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `if false {} else {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if false {} else if false {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `if false {} else if false {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if let 1 = 2 {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `if let 1 = 2 {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if let 1 | 2 = 2 {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `if let 1 | 2 = 2 {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(if let | 1 | 2 = 2 {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `if let | 1 | 2 = 2 {}.t(1) == 2` (1 vs 2)",
+ );
+}
+
+#[test]
+fn test_loop() {
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(1 + loop { break 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `1 + loop { break 1 } == 1` (2 vs 1)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(1 + 'a: loop { break 'a 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `1 + 'a: loop { break 'a 1 } == 1` (2 vs 1)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(while false {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `while false {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(while let None = Some(1) {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `while let None = Some(1) {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(for _x in iter::once(0) {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `for _x in iter::once(0) {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(for | _x in iter::once(0) {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `for | _x in iter::once(0) {}.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(for true | false in iter::empty() {}.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `for true | false in iter::empty() {}.t(1) == 2` (1 vs 2)",
+ );
+}
+
+#[test]
+fn test_match() {
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(match 1 == 1 { true => 1, false => 0 } == 2));
+ assert_err(
+ test,
+ "Condition failed: `match 1 == 1 { true => 1, false => 0 } == 2` (1 vs 2)",
+ );
+}
+
+#[test]
+fn test_atom() {
+ let test = || Ok(ensure!([false, false].len() > 3));
+ assert_err(
+ test,
+ "Condition failed: `[false, false].len() > 3` (2 vs 3)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!({ let x = 1; x } >= 3));
+ assert_err(test, "Condition failed: `{ let x = 1; x } >= 3` (1 vs 3)");
+
+ let test = || Ok(ensure!(S + async { 1 } == true));
+ assert_err(
+ test,
+ "Condition failed: `S + async { 1 } == true` (false vs true)",
+ );
+
+ let test = || Ok(ensure!(S + async move { 1 } == true));
+ assert_err(
+ test,
+ "Condition failed: `S + async move { 1 } == true` (false vs true)",
+ );
+
+ let x = &1;
+ let test = || Ok(ensure!(S + unsafe { ptr::read(x) } == true));
+ assert_err(
+ test,
+ "Condition failed: `S + unsafe { ptr::read(x) } == true` (false vs true)",
+ );
+}
+
+#[test]
+fn test_path() {
+ let test = || Ok(ensure!(crate::S.t(1) == 2));
+ assert_err(test, "Condition failed: `crate::S.t(1) == 2` (1 vs 2)");
+
+ let test = || Ok(ensure!(::anyhow::Error::root_cause.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `::anyhow::Error::root_cause.t(1) == 2` (1 vs 2)",
+ );
+
+ let test = || Ok(ensure!(Error::msg::<&str>.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `Error::msg::<&str>.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(Error::msg::<&str,>.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `Error::msg::<&str,>.t(1) == 2` (1 vs 2)",
+ );
+
+ let test = || Ok(ensure!(Error::msg::<<str as ToOwned>::Owned>.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `Error::msg::<<str as ToOwned>::Owned>.t(1) == 2` (1 vs 2)",
+ );
+
+ let test = || Ok(ensure!(Chain::<'static>::new.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `Chain::<'static>::new.t(1) == 2` (1 vs 2)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(Chain::<'static,>::new.t(1) == 2));
+ assert_err(
+ test,
+ "Condition failed: `Chain::<'static,>::new.t(1) == 2` (1 vs 2)",
+ );
+
+ fn f<const I: isize>() {}
+ let test = || Ok(ensure!(f::<1>() != ()));
+ assert_err(test, "Condition failed: `f::<1>() != ()` (() vs ())");
+ let test = || Ok(ensure!(f::<-1>() != ()));
+ assert_err(test, "Condition failed: `f::<-1>() != ()` (() vs ())");
+
+ fn g<T, const I: isize>() {}
+ let test = || Ok(ensure!(g::<u8, 1>() != ()));
+ assert_err(test, "Condition failed: `g::<u8, 1>() != ()` (() vs ())");
+ let test = || Ok(ensure!(g::<u8, -1>() != ()));
+ assert_err(test, "Condition failed: `g::<u8, -1>() != ()` (() vs ())");
+
+ #[derive(PartialOrd, PartialEq, Debug)]
+ enum E<'a, T> {
+ #[allow(dead_code)]
+ T(&'a T),
+ U,
+ }
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(E::U::<>>E::U::<u8>));
+ assert_err(test, "Condition failed: `E::U::<> > E::U::<u8>` (U vs U)");
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(E::U::<u8>>E::U));
+ assert_err(test, "Condition failed: `E::U::<u8> > E::U` (U vs U)");
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(E::U::<u8,>>E::U));
+ assert_err(test, "Condition failed: `E::U::<u8,> > E::U` (U vs U)");
+
+ let test = || Ok(ensure!(Generic::<dyn Debug + Sync> != Generic));
+ assert_err(
+ test,
+ "Condition failed: `Generic::<dyn Debug + Sync> != Generic` (Generic vs Generic)",
+ );
+
+ let test = || Ok(ensure!(Generic::<dyn Fn() + Sync> != Generic));
+ assert_err(
+ test,
+ "Condition failed: `Generic::<dyn Fn() + Sync> != Generic` (Generic vs Generic)",
+ );
+
+ #[rustfmt::skip]
+ let test = || {
+ Ok(ensure!(
+ Generic::<dyn Fn::() + ::std::marker::Sync> != Generic
+ ))
+ };
+ assert_err(
+ test,
+ "Condition failed: `Generic::<dyn Fn::() + ::std::marker::Sync> != Generic` (Generic vs Generic)",
+ );
+}
+
+#[test]
+fn test_macro() {
+ let test = || Ok(ensure!(anyhow!("...").to_string().len() <= 1));
+ assert_err(
+ test,
+ "Condition failed: `anyhow!(\"...\").to_string().len() <= 1` (3 vs 1)",
+ );
+
+ let test = || Ok(ensure!(vec![1].len() < 1));
+ assert_err(test, "Condition failed: `vec![1].len() < 1` (1 vs 1)");
+
+ let test = || Ok(ensure!(stringify! {} != ""));
+ assert_err(
+ test,
+ "Condition failed: `stringify! {} != \"\"` (\"\" vs \"\")",
+ );
+}
+
+#[test]
+fn test_trailer() {
+ let test = || Ok(ensure!((|| 1)() == 2));
+ assert_err(test, "Condition failed: `(|| 1)() == 2` (1 vs 2)");
+
+ let test = || Ok(ensure!(b"hmm"[1] == b'c'));
+ assert_err(test, "Condition failed: `b\"hmm\"[1] == b'c'` (109 vs 99)");
+
+ let test = || Ok(ensure!(PhantomData::<u8> {} != PhantomData));
+ assert_err(
+ test,
+ "Condition failed: `PhantomData::<u8> {} != PhantomData` (PhantomData<u8> vs PhantomData<u8>)",
+ );
+
+ let result = Ok::<_, Error>(1);
+ let test = || Ok(ensure!(result? == 2));
+ assert_err(test, "Condition failed: `result? == 2` (1 vs 2)");
+
+ let test = || Ok(ensure!((2, 3).1 == 2));
+ assert_err(test, "Condition failed: `(2, 3).1 == 2` (3 vs 2)");
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!((2, (3, 4)). 1.1 == 2));
+ assert_err(test, "Condition failed: `(2, (3, 4)).1.1 == 2` (4 vs 2)");
+
+ let err = anyhow!("");
+ let test = || Ok(ensure!(err.is::<&str>() == false));
+ assert_err(
+ test,
+ "Condition failed: `err.is::<&str>() == false` (true vs false)",
+ );
+
+ let test = || Ok(ensure!(err.is::<<str as ToOwned>::Owned>() == true));
+ assert_err(
+ test,
+ "Condition failed: `err.is::<<str as ToOwned>::Owned>() == true` (false vs true)",
+ );
+}
+
+#[test]
+fn test_whitespace() {
+ #[derive(Debug)]
+ pub struct Point {
+ #[allow(dead_code)]
+ pub x: i32,
+ #[allow(dead_code)]
+ pub y: i32,
+ }
+
+ let point = Point { x: 0, y: 0 };
+ let test = || Ok(ensure!("" == format!("{:#?}", point)));
+ assert_err(
+ test,
+ "Condition failed: `\"\" == format!(\"{:#?}\", point)`",
+ );
+}
+
+#[test]
+fn test_too_long() {
+ let test = || Ok(ensure!("" == "x".repeat(10)));
+ assert_err(
+ test,
+ "Condition failed: `\"\" == \"x\".repeat(10)` (\"\" vs \"xxxxxxxxxx\")",
+ );
+
+ let test = || Ok(ensure!("" == "x".repeat(80)));
+ assert_err(test, "Condition failed: `\"\" == \"x\".repeat(80)`");
+}
+
+#[test]
+fn test_as() {
+ let test = || Ok(ensure!('\0' as u8 > 1));
+ assert_err(test, "Condition failed: `'\\0' as u8 > 1` (0 vs 1)");
+
+ let test = || Ok(ensure!('\0' as ::std::primitive::u8 > 1));
+ assert_err(
+ test,
+ "Condition failed: `'\\0' as ::std::primitive::u8 > 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(&[0] as &[i32] == [1]));
+ assert_err(
+ test,
+ "Condition failed: `&[0] as &[i32] == [1]` ([0] vs [1])",
+ );
+
+ let test = || Ok(ensure!(0 as *const () as *mut _ == 1 as *mut ()));
+ assert_err(
+ test,
+ "Condition failed: `0 as *const () as *mut _ == 1 as *mut ()` (0x0 vs 0x1)",
+ );
+
+ let s = "";
+ let test = || Ok(ensure!(s as &str != s));
+ assert_err(test, "Condition failed: `s as &str != s` (\"\" vs \"\")");
+
+ let test = || Ok(ensure!(&s as &&str != &s));
+ assert_err(test, "Condition failed: `&s as &&str != &s` (\"\" vs \"\")");
+
+ let test = || Ok(ensure!(s as &'static str != s));
+ assert_err(
+ test,
+ "Condition failed: `s as &'static str != s` (\"\" vs \"\")",
+ );
+
+ let test = || Ok(ensure!(&s as &&'static str != &s));
+ assert_err(
+ test,
+ "Condition failed: `&s as &&'static str != &s` (\"\" vs \"\")",
+ );
+
+ let m: &mut str = Default::default();
+ let test = || Ok(ensure!(m as &mut str != s));
+ assert_err(
+ test,
+ "Condition failed: `m as &mut str != s` (\"\" vs \"\")",
+ );
+
+ let test = || Ok(ensure!(&m as &&mut str != &s));
+ assert_err(
+ test,
+ "Condition failed: `&m as &&mut str != &s` (\"\" vs \"\")",
+ );
+
+ let test = || Ok(ensure!(&m as &&'static mut str != &s));
+ assert_err(
+ test,
+ "Condition failed: `&m as &&'static mut str != &s` (\"\" vs \"\")",
+ );
+
+ let f = || {};
+ let test = || Ok(ensure!(f as fn() as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as fn() as usize * 0 != 0` (0 vs 0)",
+ );
+
+ let test = || Ok(ensure!(f as fn() -> () as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as fn() -> () as usize * 0 != 0` (0 vs 0)",
+ );
+
+ let test = || Ok(ensure!(f as for<'a> fn() as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as for<'a> fn() as usize * 0 != 0` (0 vs 0)",
+ );
+
+ let test = || Ok(ensure!(f as unsafe fn() as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as unsafe fn() as usize * 0 != 0` (0 vs 0)",
+ );
+
+ #[rustfmt::skip]
+ let test = || Ok(ensure!(f as extern "Rust" fn() as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as extern \"Rust\" fn() as usize * 0 != 0` (0 vs 0)",
+ );
+
+ extern "C" fn extern_fn() {}
+ #[rustfmt::skip]
+ #[allow(missing_abi)]
+ let test = || Ok(ensure!(extern_fn as extern fn() as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `extern_fn as extern fn() as usize * 0 != 0` (0 vs 0)",
+ );
+
+ let f = || -> ! { panic!() };
+ let test = || Ok(ensure!(f as fn() -> ! as usize * 0 != 0));
+ assert_err(
+ test,
+ "Condition failed: `f as fn() -> ! as usize * 0 != 0` (0 vs 0)",
+ );
+
+ trait EqDebug<T>: PartialEq<T> + Debug {
+ type Assoc;
+ }
+
+ impl<S, T> EqDebug<T> for S
+ where
+ S: PartialEq<T> + Debug,
+ {
+ type Assoc = bool;
+ }
+
+ let test = || Ok(ensure!(&0 as &dyn EqDebug<i32, Assoc = bool> != &0));
+ assert_err(
+ test,
+ "Condition failed: `&0 as &dyn EqDebug<i32, Assoc = bool> != &0` (0 vs 0)",
+ );
+
+ let test = || {
+ Ok(ensure!(
+ PhantomData as PhantomData<<i32 as ToOwned>::Owned> != PhantomData
+ ))
+ };
+ assert_err(
+ test,
+ "Condition failed: `PhantomData as PhantomData<<i32 as ToOwned>::Owned> != PhantomData` (PhantomData<i32> vs PhantomData<i32>)",
+ );
+
+ macro_rules! int {
+ (...) => {
+ u8
+ };
+ }
+
+ let test = || Ok(ensure!(0 as int!(...) != 0));
+ assert_err(test, "Condition failed: `0 as int!(...) != 0` (0 vs 0)");
+
+ let test = || Ok(ensure!(0 as int![...] != 0));
+ assert_err(test, "Condition failed: `0 as int![...] != 0` (0 vs 0)");
+
+ let test = || Ok(ensure!(0 as int! {...} != 0));
+ assert_err(test, "Condition failed: `0 as int! {...} != 0` (0 vs 0)");
+}
+
+#[test]
+fn test_pat() {
+ let test = || Ok(ensure!(if let ref mut _x @ 0 = 0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let ref mut _x @ 0 = 0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let -1..=1 = 0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let -1..=1 = 0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let &0 = &0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let &0 = &0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let &&0 = &&0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let &&0 = &&0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let &mut 0 = &mut 0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let &mut 0 = &mut 0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let &&mut 0 = &&mut 0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let &&mut 0 = &&mut 0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let (0, 1) = (0, 1) { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let (0, 1) = (0, 1) { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let [0] = b"\0" { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let [0] = b\"\\0\" { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let p = PhantomData::<u8>;
+ let test = || Ok(ensure!(if let P::<u8> {} = p { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let P::<u8> {} = p { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(if let ::std::marker::PhantomData = p {} != ()));
+ assert_err(
+ test,
+ "Condition failed: `if let ::std::marker::PhantomData = p {} != ()` (() vs ())",
+ );
+
+ let test = || Ok(ensure!(if let <S as Trait>::V = 0 { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let <S as Trait>::V = 0 { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+
+ let test = || Ok(ensure!(for _ in iter::once(()) {} != ()));
+ assert_err(
+ test,
+ "Condition failed: `for _ in iter::once(()) {} != ()` (() vs ())",
+ );
+
+ let test = || Ok(ensure!(if let stringify!(x) = "x" { 0 } else { 1 } == 1));
+ assert_err(
+ test,
+ "Condition failed: `if let stringify!(x) = \"x\" { 0 } else { 1 } == 1` (0 vs 1)",
+ );
+}
### external/vendor/anyhow/tests/test_ffi.rs
@@ -0,0 +1,19 @@
+#![deny(improper_ctypes, improper_ctypes_definitions)]
+#![allow(clippy::uninlined_format_args)]
+
+use anyhow::anyhow;
+
+#[no_mangle]
+pub extern "C" fn anyhow1(err: anyhow::Error) {
+ println!("{:?}", err);
+}
+
+#[no_mangle]
+pub extern "C" fn anyhow2(err: &mut Option<anyhow::Error>) {
+ *err = Some(anyhow!("ffi error"));
+}
+
+#[no_mangle]
+pub extern "C" fn anyhow3() -> Option<anyhow::Error> {
+ Some(anyhow!("ffi error"))
+}
### external/vendor/anyhow/tests/test_fmt.rs
@@ -79,7 +79,6 @@ fn test_altdisplay() {
}
#[test]
-#[cfg_attr(not(backtrace), ignore)]
fn test_debug() {
assert_eq!(EXPECTED_DEBUG_F, format!("{:?}", f().unwrap_err()));
assert_eq!(EXPECTED_DEBUG_G, format!("{:?}", g().unwrap_err()));
### external/vendor/anyhow/tests/test_macros.rs
@@ -1,7 +1,21 @@
+#![allow(
+ clippy::assertions_on_result_states,
+ clippy::eq_op,
+ clippy::incompatible_msrv, // https://github.com/rust-lang/rust-clippy/issues/12257
+ clippy::items_after_statements,
+ clippy::match_single_binding,
+ clippy::needless_pass_by_value,
+ clippy::shadow_unrelated,
+ clippy::uninlined_format_args,
+ clippy::wildcard_imports
+)]
+
mod common;
use self::common::*;
-use anyhow::ensure;
+use anyhow::{anyhow, ensure, Result};
+use std::cell::Cell;
+use std::future;
#[test]
fn test_messages() {
@@ -30,4 +44,54 @@ fn test_ensure() {
Ok(())
};
assert!(f().is_err());
+
+ let f = || {
+ ensure!(v + v == 1);
+ Ok(())
+ };
+ assert_eq!(
+ f().unwrap_err().to_string(),
+ "Condition failed: `v + v == 1` (2 vs 1)",
+ );
+}
+
+#[test]
+fn test_ensure_nonbool() -> Result<()> {
+ struct Struct {
+ condition: bool,
+ }
+
+ let s = Struct { condition: true };
+ match &s {
+ Struct { condition } => ensure!(condition), // &bool
+ }
+
+ Ok(())
+}
+
+#[test]
+fn test_temporaries() {
+ fn require_send_sync(_: impl Send + Sync) {}
+
+ require_send_sync(async {
+ // If anyhow hasn't dropped any temporary format_args it creates by the
+ // time it's done evaluating, those will stick around until the
+ // semicolon, which is on the other side of the await point, making the
+ // enclosing future non-Send.
+ future::ready(anyhow!("...")).await;
+ });
+
+ fn message(cell: Cell<&str>) -> &str {
+ cell.get()
+ }
+
+ require_send_sync(async {
+ future::ready(anyhow!(message(Cell::new("...")))).await;
+ });
+}
+
+#[test]
+fn test_brace_escape() {
+ let err = anyhow!("unterminated ${{..}} expression");
+ assert_eq!("unterminated ${..} expression", err.to_string());
}
### external/vendor/anyhow/tests/test_repr.rs
@@ -1,8 +1,9 @@
+#![allow(clippy::extra_unused_type_parameters)]
+
mod drop;
use self::drop::{DetectDrop, Flag};
use anyhow::Error;
-use std::marker::Unpin;
use std::mem;
#[test]
### external/vendor/anyhow/tests/ui/chained-comparison.rs
@@ -0,0 +1,8 @@
+use anyhow::{ensure, Result};
+
+fn main() -> Result<()> {
+ // `ensure!` must not partition this into `(false) == (false == true)`
+ // because Rust doesn't ordinarily allow this form of expression.
+ ensure!(false == false == true);
+ Ok(())
+}
### external/vendor/anyhow/tests/ui/chained-comparison.stderr
@@ -0,0 +1,10 @@
+error: comparison operators cannot be chained
+ --> tests/ui/chained-comparison.rs:6:19
+ |
+6 | ensure!(false == false == true);
+ | ^^ ^^
+ |
+help: split the comparison into two
+ |
+6 | ensure!(false == false && false == true);
+ | ++++++++
### external/vendor/anyhow/tests/ui/empty-ensure.rs
@@ -0,0 +1,6 @@
+use anyhow::{ensure, Result};
+
+fn main() -> Result<()> {
+ ensure!();
+ Ok(())
+}
### external/vendor/anyhow/tests/ui/empty-ensure.stderr
@@ -0,0 +1,12 @@
+error: unexpected end of macro invocation
+ --> tests/ui/empty-ensure.rs:4:5
+ |
+4 | ensure!();
+ | ^^^^^^^^^ missing tokens in macro arguments
+ |
+note: while trying to match meta-variable `$cond:expr`
+ --> src/ensure.rs
+ |
+ | ($cond:expr $(,)?) => {
+ | ^^^^^^^^^^
+ = note: this error originates in the macro `$crate::__parse_ensure` which comes from the expansion of the macro `ensure` (in Nightly builds, run with -Z macro-backtrace for more info)
### external/vendor/anyhow/tests/ui/ensure-nonbool.rs
@@ -0,0 +1,40 @@
+use anyhow::{ensure, Result};
+use std::ops::{Deref, Not};
+
+struct Bool(bool);
+
+struct DerefBool(bool);
+
+struct NotBool(bool);
+
+impl Deref for DerefBool {
+ type Target = bool;
+ fn deref(&self) -> &Self::Target {
+ &self.0
+ }
+}
+
+impl Not for NotBool {
+ type Output = bool;
+ fn not(self) -> Self::Output {
+ !self.0
+ }
+}
+
+fn main() -> Result<()> {
+ ensure!("...");
+
+ let mut s = Bool(true);
+ match &mut s {
+ Bool(cond) => ensure!(cond),
+ }
+
+ let db = DerefBool(true);
+ ensure!(db);
+ ensure!(&db);
+
+ let nb = NotBool(true);
+ ensure!(nb);
+
+ Ok(())
+}
### external/vendor/anyhow/tests/ui/ensure-nonbool.stderr
@@ -0,0 +1,113 @@
+error[E0277]: the trait bound `&str: anyhow::__private::not::Bool` is not satisfied
+ --> tests/ui/ensure-nonbool.rs:25:13
+ |
+25 | ensure!("...");
+ | --------^^^^^-
+ | | |
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&str`
+ | required by a bound introduced by this call
+ |
+help: the following other types implement trait `anyhow::__private::not::Bool`
+ --> src/lib.rs
+ |
+ | impl Bool for bool {
+ | ^^^^^^^^^^^^^^^^^^ `bool`
+...
+ | impl Bool for &bool {
+ | ^^^^^^^^^^^^^^^^^^^ `&bool`
+note: required by a bound in `anyhow::__private::not`
+ --> src/lib.rs
+ |
+ | pub fn not(cond: impl Bool) -> bool {
+ | ^^^^ required by this bound in `not`
+
+error[E0277]: the trait bound `&mut bool: anyhow::__private::not::Bool` is not satisfied
+ --> tests/ui/ensure-nonbool.rs:29:31
+ |
+29 | Bool(cond) => ensure!(cond),
+ | --------^^^^-
+ | | |
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&mut bool`
+ | required by a bound introduced by this call
+ |
+ = note: `anyhow::__private::not::Bool` is implemented for `&bool`, but not for `&mut bool`
+note: required by a bound in `anyhow::__private::not`
+ --> src/lib.rs
+ |
+ | pub fn not(cond: impl Bool) -> bool {
+ | ^^^^ required by this bound in `not`
+help: consider dereferencing here
+ |
+29 | Bool(cond) => ensure!(*cond),
+ | +
+
+error[E0277]: the trait bound `DerefBool: anyhow::__private::not::Bool` is not satisfied
+ --> tests/ui/ensure-nonbool.rs:33:13
+ |
+33 | ensure!(db);
+ | --------^^-
+ | | |
+ | | unsatisfied trait bound
+ | required by a bound introduced by this call
+ |
+help: the trait `anyhow::__private::not::Bool` is not implemented for `DerefBool`
+ --> tests/ui/ensure-nonbool.rs:6:1
+ |
+ 6 | struct DerefBool(bool);
+ | ^^^^^^^^^^^^^^^^
+note: required by a bound in `anyhow::__private::not`
+ --> src/lib.rs
+ |
+ | pub fn not(cond: impl Bool) -> bool {
+ | ^^^^ required by this bound in `not`
+help: consider dereferencing here
+ |
+33 | ensure!(*db);
+ | +
+
+error[E0277]: the trait bound `&DerefBool: anyhow::__private::not::Bool` is not satisfied
+ --> tests/ui/ensure-nonbool.rs:34:13
+ |
+34 | ensure!(&db);
+ | --------^^^-
+ | | |
+ | | the trait `anyhow::__private::not::Bool` is not implemented for `&DerefBool`
+ | required by a bound introduced by this call
+ |
+note: required by a bound in `anyhow::__private::not`
+ --> src/lib.rs
+ |
+ | pub fn not(cond: impl Bool) -> bool {
+ | ^^^^ required by this bound in `not`
+help: consider dereferencing here
+ |
+34 | ensure!(&*db);
+ | +
+
+error[E0277]: the trait bound `NotBool: anyhow::__private::not::Bool` is not satisfied
+ --> tests/ui/ensure-nonbool.rs:37:13
+ |
+37 | ensure!(nb);
+ | --------^^-
+ | | |
+ | | unsatisfied trait bound
+ | required by a bound introduced by this call
+ |
+help: the trait `anyhow::__private::not::Bool` is not implemented for `NotBool`
+ --> tests/ui/ensure-nonbool.rs:8:1
+ |
+ 8 | struct NotBool(bool);
+ | ^^^^^^^^^^^^^^
+help: the following other types implement trait `anyhow::__private::not::Bool`
+ --> src/lib.rs
+ |
+ | impl Bool for bool {
+ | ^^^^^^^^^^^^^^^^^^ `bool`
+...
+ | impl Bool for &bool {
+ | ^^^^^^^^^^^^^^^^^^^ `&bool`
+note: required by a bound in `anyhow::__private::not`
+ --> src/lib.rs
+ |
+ | pub fn not(cond: impl Bool) -> bool {
+ | ^^^^ required by this bound in `not`
### external/vendor/anyhow/tests/ui/must-use.rs
@@ -0,0 +1,11 @@
+#![deny(unused_must_use)]
+
+use anyhow::anyhow;
+
+fn main() -> anyhow::Result<()> {
+ if true {
+ // meant to write bail!
+ anyhow!("it failed");
+ }
+ Ok(())
+}
### external/vendor/anyhow/tests/ui/must-use.stderr
@@ -0,0 +1,15 @@
+error: unused return value of `anyhow::__private::must_use` that must be used
+ --> tests/ui/must-use.rs:8:9
+ |
+8 | anyhow!("it failed");
+ | ^^^^^^^^^^^^^^^^^^^^
+ |
+note: the lint level is defined here
+ --> tests/ui/must-use.rs:1:9
+ |
+1 | #![deny(unused_must_use)]
+ | ^^^^^^^^^^^^^^^
+help: use `let _ = ...` to ignore the resulting value
+ |
+8 | let _ = anyhow!("it failed");
+ | +++++++
### external/vendor/anyhow/tests/ui/no-impl.stderr
@@ -1,21 +1,32 @@
-error[E0599]: no method named `anyhow_kind` found for reference `&Error` in the current scope
- --> $DIR/no-impl.rs:7:13
+error[E0599]: the method `anyhow_kind` exists for reference `&Error`, but its trait bounds were not satisfied
+ --> tests/ui/no-impl.rs:7:13
|
4 | struct Error;
- | -------------
- | |
- | doesn't satisfy `Error: anyhow::kind::TraitKind`
- | doesn't satisfy `Error: std::convert::Into<anyhow::Error>`
- | doesn't satisfy `Error: std::fmt::Display`
+ | ------------ doesn't satisfy `Error: Into<anyhow::Error>`, `Error: anyhow::kind::TraitKind` or `Error: std::fmt::Display`
...
7 | let _ = anyhow!(Error);
- | ^^^^^^^^^^^^^^ method not found in `&Error`
+ | ^^^^^^^^^^^^^^ method cannot be called on `&Error` due to unsatisfied trait bounds
|
- = note: the method `anyhow_kind` exists but the following trait bounds were not satisfied:
- `Error: std::convert::Into<anyhow::Error>`
+ = note: the following trait bounds were not satisfied:
+ `Error: Into<anyhow::Error>`
which is required by `Error: anyhow::kind::TraitKind`
`Error: std::fmt::Display`
which is required by `&Error: anyhow::kind::AdhocKind`
- `&Error: std::convert::Into<anyhow::Error>`
+ `&Error: Into<anyhow::Error>`
which is required by `&Error: anyhow::kind::TraitKind`
- = note: this error originates in a macro (in Nightly builds, run with -Z macro-backtrace for more info)
+note: the traits `Into` and `std::fmt::Display` must be implemented
+ --> $RUST/core/src/fmt/mod.rs
+ |
+ | pub trait Display: PointeeSized {
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ |
+ ::: $RUST/core/src/convert/mod.rs
+ |
+ | pub const trait Into<T>: Sized {
+ | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
+ = help: items from traits can only be used if the trait is implemented and in scope
+ = note: the following traits define an item `anyhow_kind`, perhaps you need to implement one of them:
+ candidate #1: `anyhow::kind::AdhocKind`
+ candidate #2: `anyhow::kind::BoxedKind`
+ candidate #3: `anyhow::kind::TraitKind`
+ = note: this error originates in the macro `anyhow` (in Nightly builds, run with -Z macro-backtrace for more info)
### external/vendor/anyhow/tests/ui/temporary-value.rs
@@ -0,0 +1,5 @@
+use anyhow::anyhow;
+
+fn main() {
+ let _ = anyhow!(&String::new());
+}
### external/vendor/anyhow/tests/ui/temporary-value.stderr
@@ -0,0 +1,15 @@
+error[E0716]: temporary value dropped while borrowed
+ --> tests/ui/temporary-value.rs:4:22
+ |
+4 | let _ = anyhow!(&String::new());
+ | ---------^^^^^^^^^^^^^-
+ | | |
+ | | creates a temporary value which is freed while still in use
+ | temporary value is freed at the end of this statement
+ | argument requires that borrow lasts for `'static`
+ |
+note: requirement that the value outlives `'static` introduced here
+ --> src/kind.rs
+ |
+ | M: Display + Debug + Send + Sync + 'static,
+ | ^^^^^^^
### external/vendor/anyhow/tests/ui/wrong-interpolation.rs
@@ -0,0 +1,5 @@
+use anyhow::{bail, Result};
+
+fn main() -> Result<()> {
+ bail!("{} not found");
+}
### external/vendor/anyhow/tests/ui/wrong-interpolation.stderr
@@ -0,0 +1,5 @@
+error: 1 positional argument in format string, but no arguments were given
+ --> tests/ui/wrong-interpolation.rs:4:12
+ |
+4 | bail!("{} not found");
+ | ^^
### external/vendor/deranged/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"e57656063dbb7f1dd11ff93e0f43930bc384c32df3337a6146210a5728856eb5","Cargo.lock":"5a1acb9838be3f9f53694ea2ba2eddeac74925621e7cd6abb37eba3b8371fe6f","Cargo.toml":"ed80c260411d925d1e3704c4d84a4f7af67c50079f732a2790f2ffb4b2b42e24","Cargo.toml.orig":"e19191a6de2accd1870c99f037203430f6403eaac1cc0aa05a20e44f8466d3db","LICENSE-Apache":"edd65bdd88957a205c47d53fa499eed8865a70320f0f03f6391668cb304ea376","LICENSE-MIT":"231c837c45eb53f108fb48929e488965bc4fcc14e9ea21d35f50e6b99d98685b","README.md":"fc4c9482d9e5225630da44e5371d6fa3f37220e2f4da2dac076cf4cd4f9592e7","src/lib.rs":"7190955819f7779d3e73ddfc92791d9ac0ba91a807133140d0c1d8faaf66c729","src/tests.rs":"e6459379daa2fe1ca8a5ef957d74e5027ee4e8d87f1f50eb15e3e450ae53722e","src/unsafe_wrapper.rs":"76e67ff03b31f0b97849f0e6c3131f1cb213fc25a11ed259664f48a6901c623e"},"package":"ececcb659e7ba858fb4f10388c250a7252eb0a27373f1a72b8748afdd248e587"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"582f982e585f046c250af87b92c109e048650dac12d1a672667e677c25b4485b","Cargo.lock":"e48acd936600824f01ac1b1484d88fa84e4d75c28beffbec082f033f6c8ec8b4","Cargo.toml":"8604c48d0f13a96386d4ef94448d295c64a1639a9a6352b3a060bc00da5bc011","Cargo.toml.orig":"8d82d967d014ff3bde0b905004fc94155c55ef76047caf68a7773758d14c1cf1","LICENSE-Apache":"edd65bdd88957a205c47d53fa499eed8865a70320f0f03f6391668cb304ea376","LICENSE-MIT":"231c837c45eb53f108fb48929e488965bc4fcc14e9ea21d35f50e6b99d98685b","README.md":"fc4c9482d9e5225630da44e5371d6fa3f37220e2f4da2dac076cf4cd4f9592e7","src/lib.rs":"9d6107518384ab83aea30dafaa2d89383345198a40ec6b03548ce8810b700e79","src/tests.rs":"b6c8a42f02f122d4a5afee06819b9c5ee867479390f0df6fbd72e1a090f368aa","src/unsafe_wrapper.rs":"76e67ff03b31f0b97849f0e6c3131f1cb213fc25a11ed259664f48a6901c623e"},"package":"9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"}
\ No newline at end of file
### external/vendor/deranged/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "c249467d73779b196b68f56df8a9bf800bc89c8d"
+ "sha1": "aeb03a4be17fe287d5fdd509e9ae134d4b9999fc"
},
"path_in_vcs": "deranged"
}
\ No newline at end of file
### external/vendor/deranged/Cargo.lock
@@ -1,6 +1,12 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.101"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
[[package]]
name = "autocfg"
@@ -20,25 +26,59 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+[[package]]
+name = "chacha20"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "6f8d983286843e49675a4b7a2d174efe136dc93a18d69130dd18198a6c167601"
+dependencies = [
+ "cfg-if",
+ "cpufeatures",
+ "rand_core 0.10.0",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
[[package]]
name = "deranged"
-version = "0.5.5"
+version = "0.5.9"
dependencies = [
"deranged-macros",
"num-traits",
"powerfmt",
"quickcheck",
+ "rand 0.10.0",
"rand 0.8.5",
"rand 0.9.0",
"serde_core",
"serde_json",
+ "serde_test2",
]
[[package]]
name = "deranged-macros"
-version = "0.3.0"
+version = "0.3.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7bca4c1de336861b47b9bae300e835ee36ae82452c511c4335401da138ee18a6"
+
+[[package]]
+name = "equivalent"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "foldhash"
+version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8952b6aa444b5338b25807ef3ccfc4082637d28bd77e2305dc60d6cae04af6c1"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
[[package]]
name = "getrandom"
@@ -63,18 +103,83 @@ dependencies = [
"windows-targets",
]
+[[package]]
+name = "getrandom"
+version = "0.4.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core 0.10.0",
+ "wasip2",
+ "wasip3",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.16.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "id-arena"
+version = "2.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
+
+[[package]]
+name = "indexmap"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_core",
+]
+
[[package]]
name = "itoa"
version = "1.0.10"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b1a46d1a171d865aa5f83f92695765caa047a9b4cbae2cbf37dbd613a793fd4c"
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
[[package]]
name = "libc"
version = "0.2.170"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "875b3680cb2f8f71bdcf9a30f38d48282f5d3c95cbf9b3fa57269bb5d5c06828"
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
[[package]]
name = "num-traits"
version = "0.2.18"
@@ -96,6 +201,16 @@ version = "0.2.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
+
[[package]]
name = "proc-macro2"
version = "1.0.101"
@@ -123,6 +238,12 @@ dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "rand"
version = "0.8.5"
@@ -145,6 +266,17 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "rand"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bc266eb313df6c5c09c1c7b1fbe2510961e5bcd3add930c1e31f7ed9da0feff8"
+dependencies = [
+ "chacha20",
+ "getrandom 0.4.1",
+ "rand_core 0.10.0",
+]
+
[[package]]
name = "rand_chacha"
version = "0.3.1"
@@ -184,12 +316,24 @@ dependencies = [
"zerocopy",
]
+[[package]]
+name = "rand_core"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"
+
[[package]]
name = "ryu"
version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "e86697c916019a8588c99b5fac3cead74ec0b4b819707a682fd4d23fa0ce1ba1"
+[[package]]
+name = "semver"
+version = "1.0.27"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
+
[[package]]
name = "serde"
version = "1.0.226"
@@ -230,6 +374,15 @@ dependencies = [
"serde",
]
+[[package]]
+name = "serde_test2"
+version = "2.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "95a9eac4d4fc2509eef1f6d4f03b7ee3834fe055349ba336ab5388206176cb30"
+dependencies = [
+ "serde_core",
+]
+
[[package]]
name = "syn"
version = "2.0.106"
@@ -247,6 +400,12 @@ version = "1.0.12"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b"
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
[[package]]
name = "wasi"
version = "0.11.0+wasi-snapshot-preview1"
@@ -262,6 +421,58 @@ dependencies = [
"wit-bindgen-rt",
]
+[[package]]
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
+dependencies = [
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
+
[[package]]
name = "windows-targets"
version = "0.52.6"
@@ -326,6 +537,26 @@ version = "0.52.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
+[[package]]
+name = "wit-bindgen"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
+
+[[package]]
+name = "wit-bindgen-core"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
+
[[package]]
name = "wit-bindgen-rt"
version = "0.33.0"
@@ -335,6 +566,74 @@ dependencies = [
"bitflags",
]
+[[package]]
+name = "wit-bindgen-rust"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
+
+[[package]]
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
+
+[[package]]
+name = "wit-component"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
+
+[[package]]
+name = "wit-parser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
+
[[package]]
name = "zerocopy"
version = "0.8.20"
### external/vendor/deranged/Cargo.toml
@@ -10,10 +10,10 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.81.0"
+edition = "2024"
+rust-version = "1.85.0"
name = "deranged"
-version = "0.5.5"
+version = "0.5.9"
authors = ["Jacob Pratt <jacob@jhpratt.dev>"]
build = false
include = [
@@ -35,6 +35,7 @@ keywords = [
]
license = "MIT OR Apache-2.0"
repository = "https://github.com/jhpratt/deranged"
+resolver = "2"
[package.metadata.docs.rs]
all-features = true
@@ -57,7 +58,9 @@ quickcheck = [
rand = [
"rand08",
"rand09",
+ "rand010",
]
+rand010 = ["dep:rand010"]
rand08 = ["dep:rand08"]
rand09 = ["dep:rand09"]
serde = ["dep:serde_core"]
@@ -67,7 +70,7 @@ name = "deranged"
path = "src/lib.rs"
[dependencies.deranged-macros]
-version = "=0.3.0"
+version = "=0.3.1"
optional = true
[dependencies.num-traits]
@@ -85,6 +88,12 @@ version = "1.0.3"
optional = true
default-features = false
+[dependencies.rand010]
+version = "0.10.0"
+optional = true
+default-features = false
+package = "rand"
+
[dependencies.rand08]
version = "0.8.4"
optional = true
@@ -102,6 +111,10 @@ version = "1.0.220"
optional = true
default-features = false
+[dev-dependencies.rand010]
+version = "0.10.0"
+package = "rand"
+
[dev-dependencies.rand08]
version = "0.8.4"
package = "rand"
@@ -113,29 +126,32 @@ package = "rand"
[dev-dependencies.serde_json]
version = "1.0.86"
+[dev-dependencies.serde_test2]
+version = "2.0.0"
+
[lints.clippy]
-alloc-instead-of-core = "deny"
-dbg-macro = "warn"
-decimal-literal-representation = "warn"
-explicit-auto-deref = "warn"
-get-unwrap = "warn"
-manual-let-else = "warn"
-missing-docs-in-private-items = "warn"
-missing-enforced-import-renames = "warn"
-obfuscated-if-else = "warn"
-option-if-let-else = "allow"
-print-stdout = "warn"
-redundant-pub-crate = "allow"
-semicolon-outside-block = "warn"
-std-instead-of-core = "deny"
+alloc_instead_of_core = "deny"
+dbg_macro = "warn"
+decimal_literal_representation = "warn"
+explicit_auto_deref = "warn"
+get_unwrap = "warn"
+manual_let_else = "warn"
+missing_docs_in_private_items = "warn"
+missing_enforced_import_renames = "warn"
+obfuscated_if_else = "warn"
+option_if_let_else = "allow"
+print_stdout = "warn"
+redundant_pub_crate = "allow"
+semicolon_outside_block = "warn"
+std_instead_of_core = "deny"
todo = "warn"
-undocumented-unsafe-blocks = "deny"
+undocumented_unsafe_blocks = "deny"
unimplemented = "warn"
-uninlined-format-args = "warn"
-unnested-or-patterns = "warn"
-unwrap-in-result = "warn"
-unwrap-used = "warn"
-use-debug = "warn"
+uninlined_format_args = "warn"
+unnested_or_patterns = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+use_debug = "warn"
[lints.clippy.all]
level = "warn"
@@ -146,53 +162,58 @@ level = "warn"
priority = -1
[lints.rust]
-ambiguous-glob-reexports = "deny"
-clashing-extern-declarations = "deny"
-const-item-mutation = "deny"
-dangling-pointers-from-temporaries = "deny"
-deref-nullptr = "deny"
-drop-bounds = "deny"
-future-incompatible = "deny"
-hidden-glob-reexports = "deny"
-improper-ctypes = "deny"
-improper-ctypes-definitions = "deny"
-invalid-from-utf8 = "deny"
-invalid-macro-export-arguments = "deny"
-invalid-nan-comparisons = "deny"
-invalid-reference-casting = "deny"
-invalid-value = "deny"
-keyword-idents = "warn"
-let-underscore = "warn"
-macro-use-extern-crate = "warn"
-meta-variable-misuse = "warn"
-missing-abi = "warn"
-missing-copy-implementations = "warn"
-missing-debug-implementations = "warn"
-missing-docs = "warn"
-named-arguments-used-positionally = "deny"
-non-ascii-idents = "deny"
-noop-method-call = "warn"
-opaque-hidden-inferred-bound = "deny"
-overlapping-range-endpoints = "deny"
-single-use-lifetimes = "warn"
-suspicious-double-ref-op = "deny"
-trivial-casts = "warn"
-trivial-numeric-casts = "warn"
-unconditional-recursion = "deny"
-unnameable-test-items = "deny"
-unreachable-pub = "warn"
-unsafe-op-in-unsafe-fn = "deny"
-unstable-syntax-pre-expansion = "deny"
-unused-import-braces = "warn"
-unused-lifetimes = "warn"
-unused-qualifications = "warn"
-variant-size-differences = "warn"
-
-[lints.rust.path-statements]
-level = "allow"
-priority = 1
+ambiguous_glob_reexports = "deny"
+clashing_extern_declarations = "deny"
+const_item_mutation = "deny"
+dangling_pointers_from_temporaries = "deny"
+deref_nullptr = "deny"
+drop_bounds = "deny"
+hidden_glob_reexports = "deny"
+improper_ctypes = "deny"
+improper_ctypes_definitions = "deny"
+invalid_from_utf8 = "deny"
+invalid_macro_export_arguments = "deny"
+invalid_nan_comparisons = "deny"
+invalid_reference_casting = "deny"
+invalid_value = "deny"
+macro_use_extern_crate = "warn"
+meta_variable_misuse = "warn"
+missing_abi = "warn"
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+named_arguments_used_positionally = "deny"
+non_ascii_idents = "deny"
+noop_method_call = "warn"
+opaque_hidden_inferred_bound = "deny"
+overlapping_range_endpoints = "deny"
+single_use_lifetimes = "warn"
+suspicious_double_ref_op = "deny"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unconditional_recursion = "deny"
+unnameable_test_items = "deny"
+unreachable_pub = "warn"
+unsafe_op_in_unsafe_fn = "deny"
+unstable_syntax_pre_expansion = "deny"
+unused_import_braces = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
+variant_size_differences = "warn"
+
+[lints.rust.future_incompatible]
+level = "deny"
+priority = -1
+
+[lints.rust.keyword_idents]
+level = "warn"
+priority = -1
+
+[lints.rust.let_underscore]
+level = "warn"
+priority = -1
-[lints.rust.unstable-name-collisions]
+[lints.rust.unstable_name_collisions]
level = "warn"
priority = 1
@@ -201,5 +222,5 @@ level = "warn"
priority = -1
[lints.rustdoc]
-private-doc-tests = "warn"
-unescaped-backticks = "warn"
+private_doc_tests = "warn"
+unescaped_backticks = "warn"
### external/vendor/deranged/Cargo.toml.orig
@@ -1,9 +1,9 @@
[package]
name = "deranged"
-version = "0.5.5"
+version = "0.5.9"
authors = ["Jacob Pratt <jacob@jhpratt.dev>"]
-edition = "2021"
-rust-version = "1.81.0"
+edition = "2024"
+rust-version = "1.85.0"
repository = "https://github.com/jhpratt/deranged"
keywords = ["integer", "int", "range"]
readme = "../README.md"
@@ -18,9 +18,10 @@ macros = ["dep:deranged-macros"]
num = ["dep:num-traits"]
powerfmt = ["dep:powerfmt"]
quickcheck = ["dep:quickcheck", "alloc"]
-rand = ["rand08", "rand09"]
+rand = ["rand08", "rand09", "rand010"]
rand08 = ["dep:rand08"]
rand09 = ["dep:rand09"]
+rand010 = ["dep:rand010"]
serde = ["dep:serde_core"]
[lints]
@@ -38,9 +39,12 @@ powerfmt = { version = "0.2.0", optional = true, default-features = false }
quickcheck = { version = "1.0.3", default-features = false, optional = true }
rand08 = { package = "rand", version = "0.8.4", optional = true, default-features = false }
rand09 = { package = "rand", version = "0.9.0", optional = true, default-features = false }
+rand010 = { package = "rand", version = "0.10.0", optional = true, default-features = false }
serde_core = { version = "1.0.220", optional = true, default-features = false }
[dev-dependencies]
rand08 = { package = "rand", version = "0.8.4" }
rand09 = { package = "rand", version = "0.9.0" }
+rand010 = { package = "rand", version = "0.10.0" }
serde_json = "1.0.86"
+serde_test2 = "2.0.0"
### external/vendor/deranged/src/lib.rs
@@ -35,7 +35,8 @@ use core::str::FromStr;
/// int!(-5, 5); // RangedI8<-5, 5>
/// int!(-5u, 5); // compile error (-5 cannot be unsigned)
/// ```
-#[cfg(all(docsrs, feature = "macros"))]
+#[cfg(docsrs)]
+#[doc(cfg(feature = "macros"))]
#[macro_export]
macro_rules! int {
($min:literal, $max:literal) => {};
@@ -57,7 +58,8 @@ macro_rules! int {
/// opt_int!(-5, 5); // OptionRangedI8<-5, 5>
/// opt_int!(-5u, 5); // compile error (-5 cannot be unsigned)
/// ```
-#[cfg(all(docsrs, feature = "macros"))]
+#[cfg(docsrs)]
+#[doc(cfg(feature = "macros"))]
#[macro_export]
macro_rules! opt_int {
($min:literal, $max:literal) => {};
@@ -169,18 +171,6 @@ macro_rules! article {
};
}
-/// `Option::unwrap_unchecked`, but usable in `const` contexts.
-macro_rules! unsafe_unwrap_unchecked {
- ($e:expr) => {{
- let opt = $e;
- debug_assert!(opt.is_some());
- match $e {
- Some(value) => value,
- None => core::hint::unreachable_unchecked(),
- }
- }};
-}
-
/// Output the provided code if and only if the list does not include `rand_09`.
#[allow(unused_macro_rules)]
macro_rules! if_not_manual_rand_09 {
@@ -193,19 +183,42 @@ macro_rules! if_not_manual_rand_09 {
};
}
+/// Output the provided code if and only if the list does not include `rand_010`.
+#[allow(unused_macro_rules)]
+macro_rules! if_not_manual_rand_010 {
+ ([rand_010 $($rest:ident)*] $($output:tt)*) => {};
+ ([] $($output:tt)*) => {
+ $($output)*
+ };
+ ([$first:ident $($rest:ident)*] $($output:tt)*) => {
+ if_not_manual_rand_010!([$($rest)*] $($output)*);
+ };
+}
+
/// Implement a ranged integer type.
macro_rules! impl_ranged {
($(
$type:ident {
mod_name: $mod_name:ident
+ alias: $alias:ident
internal: $internal:ident
signed: $is_signed:ident
unsigned: $unsigned_type:ident
optional: $optional_type:ident
+ optional_alias: $optional_alias:ident
from: [$($from:ident($from_internal:ident))+]
$(manual: [$($skips:ident)+])?
}
)*) => {$(
+ #[doc = concat!("Equivalent to `", stringify!($type), "`")]
+ #[expect(non_camel_case_types, reason = "symmetry with primitives")]
+ pub type $alias<const MIN: $internal, const MAX: $internal> = $type<MIN, MAX>;
+
+ #[doc = concat!("Equivalent to `", stringify!($optional_type), "`")]
+ #[expect(non_camel_case_types, reason = "closest visually to `Option<T>`")]
+ pub type $optional_alias<const MIN: $internal, const MAX: $internal>
+ = $optional_type<MIN, MAX>;
+
#[doc = concat!(
article!($is_signed),
" `",
@@ -316,7 +329,7 @@ macro_rules! impl_ranged {
///
#[doc = concat!("The returned value is identical to [`", stringify!($type), "::get`].")]
/// Unlike `get`, no hints are output to the compiler indicating the range that the
- /// value is in. Depending on the scenario, this may with be helpful or harmful too
+ /// value is in. Depending on the scenario, this may with be helpful or harmful to
/// optimization.
#[inline(always)]
pub const fn get_without_hint(self) -> $internal {
@@ -423,6 +436,27 @@ macro_rules! impl_ranged {
$type::<NEW_MIN, NEW_MAX>::new(self.get())
}
+ /// Narrow the range that the value may be in. **Fails to compile** if the new range is
+ /// not a subset of the current range.
+ ///
+ /// # Safety
+ ///
+ /// The value must in the range `NEW_MIN..=NEW_MAX`.
+ #[inline(always)]
+ pub const unsafe fn narrow_unchecked<
+ const NEW_MIN: $internal,
+ const NEW_MAX: $internal,
+ >(self) -> $type<NEW_MIN, NEW_MAX> {
+ const {
+ assert!(MIN <= MAX);
+ assert!(NEW_MIN <= NEW_MAX);
+ assert!(NEW_MIN >= MIN);
+ assert!(NEW_MAX <= MAX);
+ }
+ // Safety: The caller must ensure that the value is in the new range.
+ unsafe { $type::new_unchecked(self.get()) }
+ }
+
/// Converts a string slice in a given base to an integer.
///
/// The string is expected to be an optional `+` or `-` sign followed by digits. Leading
@@ -490,12 +524,12 @@ macro_rules! impl_ranged {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_add(rhs)))
+ Self::new_unchecked(self.get().unchecked_add(rhs))
}
}
- /// Checked integer addition. Computes `self - rhs`, returning `None` if the resulting
- /// value is out of range.
+ /// Checked integer subtraction. Computes `self - rhs`, returning `None` if the
+ /// resulting value is out of range.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub const fn checked_sub(self, rhs: $internal) -> Option<Self> {
@@ -516,12 +550,12 @@ macro_rules! impl_ranged {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_sub(rhs)))
+ Self::new_unchecked(self.get().unchecked_sub(rhs))
}
}
- /// Checked integer addition. Computes `self * rhs`, returning `None` if the resulting
- /// value is out of range.
+ /// Checked integer multiplication. Computes `self * rhs`, returning `None` if the
+ /// resulting value is out of range.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
pub const fn checked_mul(self, rhs: $internal) -> Option<Self> {
@@ -542,11 +576,11 @@ macro_rules! impl_ranged {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_mul(rhs)))
+ Self::new_unchecked(self.get().unchecked_mul(rhs))
}
}
- /// Checked integer addition. Computes `self / rhs`, returning `None` if `rhs == 0` or
+ /// Checked integer division. Computes `self / rhs`, returning `None` if `rhs == 0` or
/// if the resulting value is out of range.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
@@ -560,7 +594,7 @@ macro_rules! impl_ranged {
///
/// # Safety
///
- /// `self` must not be zero and the result of `self / rhs` must be in the range
+ /// `rhs` must not be zero and the result of `self / rhs` must be in the range
/// `MIN..=MAX`.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
@@ -570,7 +604,7 @@ macro_rules! impl_ranged {
// Safety: The caller must ensure that the result is in range and that `rhs` is not
// zero.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_div(rhs)))
+ Self::new_unchecked(self.get().checked_div(rhs).unwrap_unchecked())
}
}
@@ -588,8 +622,8 @@ macro_rules! impl_ranged {
///
/// # Safety
///
- /// `self` must not be zero and the result of `self.div_euclid(rhs)` must be in the
- /// range `MIN..=MAX`.
+ /// `rhs` must not be zero and the result of `self.div_euclid(rhs)` must be in the range
+ /// `MIN..=MAX`.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
#[inline(always)]
@@ -599,7 +633,7 @@ macro_rules! impl_ranged {
// zero.
unsafe {
Self::new_unchecked(
- unsafe_unwrap_unchecked!(self.get().checked_div_euclid(rhs))
+ self.get().checked_div_euclid(rhs).unwrap_unchecked()
)
}
}
@@ -629,22 +663,22 @@ macro_rules! impl_ranged {
Self::new(const_try_opt!(self.get().checked_rem(rhs)))
}
- /// Unchecked remainder. Computes `self % rhs`, assuming that `rhs != 0` and that the
- /// result is in range.
+ /// Unchecked remainder. Computes `self % rhs`, assuming that safety invariants are
+ /// upheld.
///
/// # Safety
///
- /// `self` must not be zero and the result of `self % rhs` must be in the range
- /// `MIN..=MAX`.
+ /// `rhs` must not be zero, the division must not overflow, and the result must be in
+ /// range.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
#[inline(always)]
pub const unsafe fn unchecked_rem(self, rhs: $internal) -> Self {
const { assert!(MIN <= MAX); }
- // Safety: The caller must ensure that the result is in range and that `rhs` is not
- // zero.
+ // Safety: The caller must ensure that the result is in range, `rhs` is not zero,
+ // and the remainder operation does not overflow.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_rem(rhs)))
+ Self::new_unchecked(self.get().checked_rem(rhs).unwrap_unchecked())
}
}
@@ -657,23 +691,23 @@ macro_rules! impl_ranged {
Self::new(const_try_opt!(self.get().checked_rem_euclid(rhs)))
}
- /// Unchecked Euclidean remainder. Computes `self.rem_euclid(rhs)`, assuming that
- /// `rhs != 0` and that the result is in range.
+ /// Unchecked Euclidean remainder. Computes `self.rem_euclid(rhs)`, assuming that safety
+ /// invariants are upheld.
///
/// # Safety
///
- /// `self` must not be zero and the result of `self.rem_euclid(rhs)` must be in the
- /// range `MIN..=MAX`.
+ /// `rhs` must not be zero, the division must not overflow, and the result must be in
+ /// range.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
#[inline(always)]
pub const unsafe fn unchecked_rem_euclid(self, rhs: $internal) -> Self {
const { assert!(MIN <= MAX); }
- // Safety: The caller must ensure that the result is in range and that `rhs` is not
- // zero.
+ // Safety: The caller must ensure that the result is in range, `rhs` is not zero,
+ // and the remainder operation does not overflow.
unsafe {
Self::new_unchecked(
- unsafe_unwrap_unchecked!(self.get().checked_rem_euclid(rhs))
+ self.get().checked_rem_euclid(rhs).unwrap_unchecked()
)
}
}
@@ -698,7 +732,8 @@ macro_rules! impl_ranged {
pub const unsafe fn unchecked_neg(self) -> Self {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
- unsafe { Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_neg())) }
+ // TODO(MSRV 1.93) use `unchecked_neg`
+ unsafe { Self::new_unchecked(self.get().checked_neg().unwrap_unchecked()) }
}
/// Negation. Computes `self.neg()`, **failing to compile** if the result is not
@@ -734,15 +769,18 @@ macro_rules! impl_ranged {
///
/// # Safety
///
- /// The result of `self << rhs` must be in the range `MIN..=MAX`.
+ /// `rhs` must be less than the number of bits in the inner integer type, and the
+ /// result of `self << rhs` must be in the range `MIN..=MAX`.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
#[inline(always)]
pub const unsafe fn unchecked_shl(self, rhs: u32) -> Self {
const { assert!(MIN <= MAX); }
- // Safety: The caller must ensure that the result is in range.
+ // Safety: The caller must ensure that the shift count is valid and the result is
+ // in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_shl(rhs)))
+ // TOD(MSRV 1.93) use `unchecked_shl`
+ Self::new_unchecked(self.get().checked_shl(rhs).unwrap_unchecked())
}
}
@@ -759,15 +797,18 @@ macro_rules! impl_ranged {
///
/// # Safety
///
- /// The result of `self >> rhs` must be in the range `MIN..=MAX`.
+ /// `rhs` must be less than the number of bits in the inner integer type, and the
+ /// result of `self >> rhs` must be in the range `MIN..=MAX`.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[track_caller]
#[inline(always)]
pub const unsafe fn unchecked_shr(self, rhs: u32) -> Self {
const { assert!(MIN <= MAX); }
- // Safety: The caller must ensure that the result is in range.
+ // Safety: The caller must ensure that the shift count is valid and the result is
+ // in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_shr(rhs)))
+ // TODO(MSRV 1.93) use `unchecked_shr`
+ Self::new_unchecked(self.get().checked_shr(rhs).unwrap_unchecked())
}
}
@@ -793,7 +834,7 @@ macro_rules! impl_ranged {
pub const unsafe fn unchecked_abs(self) -> Self {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
- unsafe { Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_abs())) }
+ unsafe { Self::new_unchecked(self.get().checked_abs().unwrap_unchecked()) }
}
/// Absolute value. Computes `self.abs()`, **failing to compile** if the result is not
@@ -833,7 +874,7 @@ macro_rules! impl_ranged {
const { assert!(MIN <= MAX); }
// Safety: The caller must ensure that the result is in range.
unsafe {
- Self::new_unchecked(unsafe_unwrap_unchecked!(self.get().checked_pow(exp)))
+ Self::new_unchecked(self.get().checked_pow(exp).unwrap_unchecked())
}
}
@@ -856,7 +897,7 @@ macro_rules! impl_ranged {
}
if_signed!($is_signed
- /// Saturating integer negation. Computes `self - rhs`, saturating at the numeric
+ /// Saturating integer negation. Computes `-self`, saturating at the numeric
/// bounds.
#[must_use = "this returns the result of the operation, without modifying the original"]
#[inline]
@@ -1038,6 +1079,54 @@ macro_rules! impl_ranged {
) }
}
}
+
+ /// Calculates self + rhs.
+ ///
+ /// Returns a tuple of the addition along with a boolean indicating whether an arithmetic overflow would occur.
+ /// If an overflow would have occurred then the wrapped value is returned.
+ #[must_use = "this returns the result of the operation, without modifying the original"]
+ #[inline]
+ pub const fn overflowing_add(self, rhs: $internal) -> (Self, bool) {
+ const { assert!(MIN <= MAX); }
+
+ // Forward to internal type's impl if same as type.
+ if MIN == $internal::MIN && MAX == $internal::MAX {
+ let (res, overflow) = self.get().overflowing_add(rhs);
+
+ // Safety: std's wrapping methods match ranged arithmetic when the range is the internal datatype's range.
+ return (unsafe { Self::new_unchecked(res) }, overflow)
+ }
+
+ if let Some(res) = self.checked_add(rhs) {
+ (res, false)
+ } else {
+ (self.wrapping_add(rhs), true)
+ }
+ }
+
+ /// Calculates self - rhs.
+ ///
+ /// Returns a tuple of the subtraction along with a boolean indicating whether an arithmetic overflow would occur.
+ /// If an overflow would have occurred then the wrapped value is returned.
+ #[must_use = "this returns the result of the operation, without modifying the original"]
+ #[inline]
+ pub const fn overflowing_sub(self, rhs: $internal) -> (Self, bool) {
+ const { assert!(MIN <= MAX); }
+
+ // Forward to internal type's impl if same as type.
+ if MIN == $internal::MIN && MAX == $internal::MAX {
+ let (res, overflow) = self.get().overflowing_sub(rhs);
+
+ // Safety: std's wrapping methods match ranged arithmetic when the range is the internal datatype's range.
+ return (unsafe { Self::new_unchecked(res) }, overflow)
+ }
+
+ if let Some(res) = self.checked_sub(rhs) {
+ (res, false)
+ } else {
+ (self.wrapping_sub(rhs), true)
+ }
+ }
}
impl<const MIN: $internal, const MAX: $internal> $optional_type<MIN, MAX> {
@@ -1117,7 +1206,7 @@ macro_rules! impl_ranged {
)]
/// Unlike `get_primitive`, no hints are output to the compiler indicating the range
/// that the value is in. Depending on the scenario, this may with be helpful or harmful
- /// too optimization.
+ /// to optimization.
#[inline(always)]
pub const fn get_primitive_without_hint(self) -> Option<$internal> {
const { assert!(MIN <= MAX); }
@@ -1242,7 +1331,7 @@ macro_rules! impl_ranged {
assert!(MIN_A <= MAX_A);
assert!(MIN_B <= MAX_B);
}
- self.inner() == other.inner()
+ self.get().map(|value| value.get()) == other.get().map(|value| value.get())
}
}
@@ -1547,17 +1636,17 @@ macro_rules! impl_ranged {
{
const { assert!(MIN <= MAX); }
let internal = <$internal>::deserialize(deserializer)?;
- Self::new(internal).ok_or_else(||
+ Self::new(internal).ok_or_else(|| {
+ #[cfg(feature = "alloc")]
+ let s = alloc::format!("an integer in the range {}..={}", MIN, MAX);
+ #[cfg(not(feature = "alloc"))]
+ let s = "an integer in the valid range";
+
<D::Error as serde_core::de::Error>::invalid_value(
serde_core::de::Unexpected::Other("integer"),
- #[cfg(feature = "alloc")] {
- &alloc::format!("an integer in the range {}..={}", MIN, MAX).as_ref()
- },
- #[cfg(not(feature = "alloc"))] {
- &"an integer in the valid range"
- }
+ &s.as_ref(),
)
- )
+ })
}
}
@@ -1572,7 +1661,10 @@ macro_rules! impl_ranged {
-> Result<Self, D::Error>
{
const { assert!(MIN <= MAX); }
- Ok(Self::Some($type::<MIN, MAX>::deserialize(deserializer)?))
+ match Option::<$type<MIN, MAX>>::deserialize(deserializer)? {
+ Some(value) => Ok(Self::Some(value)),
+ None => Ok(Self::None),
+ }
}
}
@@ -1603,6 +1695,22 @@ macro_rules! impl_ranged {
}
}
+ if_not_manual_rand_010! {
+ [$($($skips)+)?]
+ #[cfg(feature = "rand010")]
+ impl<
+ const MIN: $internal,
+ const MAX: $internal,
+ > rand010::distr::Distribution<$type<MIN, MAX>> for rand010::distr::StandardUniform {
+ #[inline]
+ fn sample<R: rand010::Rng + ?Sized>(&self, rng: &mut R) -> $type<MIN, MAX> {
+ const { assert!(MIN <= MAX); }
+ use rand010::RngExt as _;
+ $type::new(rng.random_range(MIN..=MAX)).expect("rand failed to generate a valid value")
+ }
+ }
+ }
+
#[cfg(feature = "rand08")]
impl<
const MIN: $internal,
@@ -1633,6 +1741,24 @@ macro_rules! impl_ranged {
}
}
+ #[cfg(feature = "rand010")]
+ impl<
+ const MIN: $internal,
+ const MAX: $internal,
+ > rand010::distr::Distribution<$optional_type<MIN, MAX>>
+ for rand010::distr::StandardUniform {
+ #[inline]
+ fn sample<R: rand010::Rng + ?Sized>(&self, rng: &mut R) -> $optional_type<MIN, MAX> {
+ const { assert!(MIN <= MAX); }
+ use rand010::RngExt as _;
+ if rng.random() {
+ $optional_type::None
+ } else {
+ $optional_type::Some(rng.random::<$type<MIN, MAX>>())
+ }
+ }
+ }
+
#[cfg(feature = "num")]
impl<const MIN: $internal, const MAX: $internal> num_traits::Bounded for $type<MIN, MAX> {
#[inline(always)]
@@ -1650,12 +1776,26 @@ macro_rules! impl_ranged {
#[cfg(feature = "quickcheck")]
impl<const MIN: $internal, const MAX: $internal> quickcheck::Arbitrary for $type<MIN, MAX> {
+ #[allow(trivial_numeric_casts)] // Normalize signed and unsigned values to unsigned bits.
#[inline]
fn arbitrary(g: &mut quickcheck::Gen) -> Self {
const { assert!(MIN <= MAX); }
- // Safety: The `rem_euclid` call and addition ensure that the value is in range.
- unsafe {
- Self::new_unchecked($internal::arbitrary(g).rem_euclid(MAX - MIN + 1) + MIN)
+ if const { MIN == <$internal>::MIN && MAX == <$internal>::MAX } {
+ // Safety: Every value of the inner type is in the full range.
+ unsafe { Self::new_unchecked(<$internal>::arbitrary(g)) }
+ } else {
+ let range = (MAX as $unsigned_type)
+ .wrapping_sub(MIN as $unsigned_type)
+ .wrapping_add(1);
+ let offset = (<$internal>::arbitrary(g) as $unsigned_type)
+ .wrapping_sub(MIN as $unsigned_type)
+ % range;
+ let value = (MIN as $unsigned_type).wrapping_add(offset) as $internal;
+
+ // Safety: The offset is less than the range width, so the value is in range.
+ unsafe {
+ Self::new_unchecked(value)
+ }
}
}
@@ -1691,10 +1831,12 @@ macro_rules! impl_ranged {
impl_ranged! {
RangedU8 {
mod_name: ranged_u8
+ alias: ru8
internal: u8
signed: false
unsigned: u8
optional: OptionRangedU8
+ optional_alias: Option_ru8
from: [
RangedU16(u16)
RangedU32(u32)
@@ -1711,10 +1853,12 @@ impl_ranged! {
}
RangedU16 {
mod_name: ranged_u16
+ alias: ru16
internal: u16
signed: false
unsigned: u16
optional: OptionRangedU16
+ optional_alias: Option_ru16
from: [
RangedU8(u8)
RangedU32(u32)
@@ -1731,10 +1875,12 @@ impl_ranged! {
}
RangedU32 {
mod_name: ranged_u32
+ alias: ru32
internal: u32
signed: false
unsigned: u32
optional: OptionRangedU32
+ optional_alias: Option_ru32
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1751,10 +1897,12 @@ impl_ranged! {
}
RangedU64 {
mod_name: ranged_u64
+ alias: ru64
internal: u64
signed: false
unsigned: u64
optional: OptionRangedU64
+ optional_alias: Option_ru64
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1771,10 +1919,12 @@ impl_ranged! {
}
RangedU128 {
mod_name: ranged_u128
+ alias: ru128
internal: u128
signed: false
unsigned: u128
optional: OptionRangedU128
+ optional_alias: Option_ru128
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1791,10 +1941,12 @@ impl_ranged! {
}
RangedUsize {
mod_name: ranged_usize
+ alias: rusize
internal: usize
signed: false
unsigned: usize
optional: OptionRangedUsize
+ optional_alias: Option_rusize
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1808,14 +1960,16 @@ impl_ranged! {
RangedI128(i128)
RangedIsize(isize)
]
- manual: [rand_09]
+ manual: [rand_09 rand_010]
}
RangedI8 {
mod_name: ranged_i8
+ alias: ri8
internal: i8
signed: true
unsigned: u8
optional: OptionRangedI8
+ optional_alias: Option_ri8
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1832,10 +1986,12 @@ impl_ranged! {
}
RangedI16 {
mod_name: ranged_i16
+ alias: ri16
internal: i16
signed: true
unsigned: u16
optional: OptionRangedI16
+ optional_alias: Option_ri16
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1852,10 +2008,12 @@ impl_ranged! {
}
RangedI32 {
mod_name: ranged_i32
+ alias: ri32
internal: i32
signed: true
unsigned: u32
optional: OptionRangedI32
+ optional_alias: Option_ri32
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1872,10 +2030,12 @@ impl_ranged! {
}
RangedI64 {
mod_name: ranged_i64
+ alias: ri64
internal: i64
signed: true
unsigned: u64
optional: OptionRangedI64
+ optional_alias: Option_ri64
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1892,10 +2052,12 @@ impl_ranged! {
}
RangedI128 {
mod_name: ranged_i128
+ alias: ri128
internal: i128
signed: true
unsigned: u128
optional: OptionRangedI128
+ optional_alias: Option_ri128
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1912,10 +2074,12 @@ impl_ranged! {
}
RangedIsize {
mod_name: ranged_isize
+ alias: risize
internal: isize
signed: true
unsigned: usize
optional: OptionRangedIsize
+ optional_alias: Option_risize
from: [
RangedU8(u8)
RangedU16(u16)
@@ -1929,7 +2093,7 @@ impl_ranged! {
RangedI64(i64)
RangedI128(i128)
]
- manual: [rand_09]
+ manual: [rand_09 rand_010]
}
}
@@ -1986,3 +2150,61 @@ impl<const MIN: isize, const MAX: isize> rand09::distr::Distribution<RangedIsize
RangedIsize::new(value).expect("rand failed to generate a valid value")
}
}
+
+#[cfg(feature = "rand010")]
+impl<const MIN: usize, const MAX: usize> rand010::distr::Distribution<RangedUsize<MIN, MAX>>
+ for rand010::distr::StandardUniform
+{
+ #[inline]
+ fn sample<R: rand010::Rng + ?Sized>(&self, rng: &mut R) -> RangedUsize<MIN, MAX> {
+ const {
+ assert!(MIN <= MAX);
+ }
+
+ use rand010::RngExt as _;
+
+ #[cfg(target_pointer_width = "16")]
+ let value = rng.random_range(MIN as u16..=MAX as u16) as usize;
+ #[cfg(target_pointer_width = "32")]
+ let value = rng.random_range(MIN as u32..=MAX as u32) as usize;
+ #[cfg(target_pointer_width = "64")]
+ let value = rng.random_range(MIN as u64..=MAX as u64) as usize;
+ #[cfg(not(any(
+ target_pointer_width = "16",
+ target_pointer_width = "32",
+ target_pointer_width = "64"
+ )))]
+ compile_error("platform has unusual (and unsupported) pointer width");
+
+ RangedUsize::new(value).expect("rand failed to generate a valid value")
+ }
+}
+
+#[cfg(feature = "rand010")]
+impl<const MIN: isize, const MAX: isize> rand010::distr::Distribution<RangedIsize<MIN, MAX>>
+ for rand010::distr::StandardUniform
+{
+ #[inline]
+ fn sample<R: rand010::Rng + ?Sized>(&self, rng: &mut R) -> RangedIsize<MIN, MAX> {
+ const {
+ assert!(MIN <= MAX);
+ }
+
+ use rand010::RngExt as _;
+
+ #[cfg(target_pointer_width = "16")]
+ let value = rng.random_range(MIN as i16..=MAX as i16) as isize;
+ #[cfg(target_pointer_width = "32")]
+ let value = rng.random_range(MIN as i32..=MAX as i32) as isize;
+ #[cfg(target_pointer_width = "64")]
+ let value = rng.random_range(MIN as i64..=MAX as i64) as isize;
+ #[cfg(not(any(
+ target_pointer_width = "16",
+ target_pointer_width = "32",
+ target_pointer_width = "64"
+ )))]
+ compile_error("platform has unusual (and unsupported) pointer width");
+
+ RangedIsize::new(value).expect("rand failed to generate a valid value")
+ }
+}
### external/vendor/deranged/src/tests.rs
@@ -1,8 +1,8 @@
extern crate std;
use core::hash::Hash;
-use std::format;
use std::prelude::rust_2021::*;
+use std::{format, panic};
use crate::{
IntErrorKind, OptionRangedI128, OptionRangedI16, OptionRangedI32, OptionRangedI64,
@@ -24,6 +24,36 @@ fn test_ranged_conversion() {
// let _ : RangedI8<-4, 4> = RangedI16::<-5, 5>::new_static::<3>().into();
}
+#[test]
+fn optional_cross_range_equality() {
+ let none = OptionRangedU8::<0, 10>::None;
+ let some_max = OptionRangedU8::<5, { u8::MAX }>::Some(RangedU8::<5, { u8::MAX }>::MAX);
+ assert_ne!(none, some_max);
+ assert_eq!(none.partial_cmp(&some_max), Some(core::cmp::Ordering::Less));
+
+ let other_none = OptionRangedU8::<5, 10>::None;
+ assert_eq!(none, other_none);
+ assert_eq!(
+ none.partial_cmp(&other_none),
+ Some(core::cmp::Ordering::Equal)
+ );
+}
+
+#[cfg(feature = "quickcheck")]
+#[test]
+fn quickcheck_full_width_ranges() {
+ let mut generator = quickcheck::Gen::new(100);
+
+ for _ in 0..100 {
+ let _: RangedU8<0, 255> = quickcheck::Arbitrary::arbitrary(&mut generator);
+ let _: RangedI8<{ i8::MIN }, { i8::MAX }> =
+ quickcheck::Arbitrary::arbitrary(&mut generator);
+ let _: RangedU128<0, { u128::MAX }> = quickcheck::Arbitrary::arbitrary(&mut generator);
+ let _: RangedI128<{ i128::MIN }, { i128::MAX }> =
+ quickcheck::Arbitrary::arbitrary(&mut generator);
+ }
+}
+
macro_rules! if_signed {
(signed $($x:tt)*) => { $($x)* };
(unsigned $($x:tt)*) => {};
@@ -496,6 +526,18 @@ macro_rules! tests {
})*
}
+ #[test]
+ fn overflowing_add() {$(
+ assert_eq!($t::<5, 10>::MAX.overflowing_add(0), ($t::<5, 10>::MAX, false));
+ assert_eq!($t::<5, 10>::MAX.overflowing_add(1), ($t::<5, 10>::MIN, true));
+ )*}
+
+ #[test]
+ fn overflowing_sub() {$(
+ assert_eq!($t::<5, 10>::MIN.overflowing_sub(0), ($t::<5, 10>::MIN, false));
+ assert_eq!($t::<5, 10>::MIN.overflowing_sub(1), ($t::<5, 10>::MAX, true));
+ )*}
+
#[test]
fn saturating_sub() {$(
assert_eq!($t::<5, 10>::MIN.saturating_sub(0), $t::<5, 10>::MIN);
@@ -651,6 +693,8 @@ macro_rules! tests {
let val = $opt::<5, 10>::None;
let serialized = serde_json::to_string(&val)?;
assert_eq!(serialized, "null");
+ let deserialized: $opt<5, 10> = serde_json::from_str(&serialized)?;
+ assert_eq!(deserialized, val);
assert!(serde_json::from_str::<$opt<5, 10>>("").is_err());
assert!(serde_json::from_str::<$opt<5, 10>>("4").is_err());
@@ -659,6 +703,21 @@ macro_rules! tests {
Ok(())
}
+ #[cfg(feature = "serde")]
+ #[test]
+ fn serde_option_tokens() {
+ use serde_test2::{assert_tokens, Token};
+
+ assert_tokens(
+ &OptionRangedU8::<5, 10>::Some(RangedU8::<5, 10>::MAX),
+ &[Token::Some, Token::U8(10)],
+ );
+ assert_tokens(
+ &OptionRangedU8::<5, 10>::None,
+ &[Token::None],
+ );
+ }
+
#[cfg(feature = "rand08")]
#[test]
fn rand08() {$(
@@ -687,6 +746,20 @@ macro_rules! tests {
}
)*}
+ #[cfg(feature = "rand010")]
+ #[test]
+ fn rand010() {$(
+ let rand_val: $t<5, 10> = rand010::random();
+ assert!(rand_val >= $t::<5, 10>::MIN);
+ assert!(rand_val <= $t::<5, 10>::MAX);
+
+ let rand: $opt<5, 10> = rand010::random();
+ if let Some(rand) = rand.get() {
+ assert!(rand >= $t::<5, 10>::MIN);
+ assert!(rand <= $t::<5, 10>::MAX);
+ }
+ )*}
+
#[cfg(feature = "num")]
#[test]
fn num() {$(
### external/vendor/num-conv/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"9d07ec3e10af67b4752a03a676e5f2a38198b09bcf0c49bea746a7075033c459","Cargo.toml":"c1d8999190f493d43b84b07eaffd2a9144e16be197bb3ef13eb69305e2f23047","Cargo.toml.orig":"93898318a8e671e7b324de151b1b262f4ae77413753ac7b7ce377ceda5cc57b7","LICENSE-Apache":"c0fd5f9df8d17e13587f8fe403d2326b835e60d532817d0b42ae4aea44209251","LICENSE-MIT":"af85fff507d80e6c7ff242acfc4b0a7f5de9a72286bb3c883c782772ca4b4402","README.md":"081b57a3244bd2d42ae1c9592c90556bf50fc2155a53760d9049c9dacbe92354","src/lib.rs":"ab6c4b28902164204179f5c31473753fbe5220a4b23082e227478e19c2aa47ca"},"package":"51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"d6796518ecb4a22c4fa88353e4fa621353f944a0a79a61152c419bdc0b8a1ab1","Cargo.lock":"5e8bc520f9f81d5820f9e46d46f1abf22a6d402ba29a74292eb422aa3f5f7194","Cargo.toml":"ecd9eaa1fb85eb5c739bce95bf50387e018e3b3f0d109e97416111acbb190028","Cargo.toml.orig":"59aa824bbf80cc75cd8c3056f67c1ca43b9452130831d53d907c967790128531","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"e2e245f2b566d0bfafb0f6a04c16b82d710c4e6e7d799e39bb4ef6e541b85b98","README.md":"b06b19b8a6dec1dfa913e035ba9f99e04fd6a1a170a86fa03d9d3b9fb03c7de0","src/lib.rs":"3d341469c5f036f5b7aca71752a24cfd3d834ecfab1c570b26eb6a2676a8e388"},"package":"521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"}
\ No newline at end of file
### external/vendor/num-conv/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "b6606e5c451f5fb2bffc085a6d8d9530f3d44a48"
+ "sha1": "b022fe87ac3ad5b0d7606ea7465549eaa92efe97"
},
"path_in_vcs": ""
}
\ No newline at end of file
### external/vendor/num-conv/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 3
+
+[[package]]
+name = "num-conv"
+version = "0.2.2"
### external/vendor/num-conv/Cargo.toml
@@ -13,12 +13,18 @@
edition = "2021"
rust-version = "1.57.0"
name = "num-conv"
-version = "0.1.0"
+version = "0.2.2"
authors = ["Jacob Pratt <jacob@jhpratt.dev>"]
+build = false
include = [
"src/**/*",
"LICENSE-*",
]
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
`num_conv` is a crate to convert between integer types without using `as` casts. This provides
better certainty when refactoring, makes the exact behavior of code more explicit, and allows using
@@ -45,6 +51,10 @@ rustdoc-args = ["--generate-link-to-definition"]
[features]
+[lib]
+name = "num_conv"
+path = "src/lib.rs"
+
[lints.clippy]
alloc-instead-of-core = "deny"
std-instead-of-core = "deny"
### external/vendor/num-conv/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "num-conv"
-version = "0.1.0"
+version = "0.2.2"
authors = ["Jacob Pratt <jacob@jhpratt.dev>"]
edition = "2021"
rust-version = "1.57.0"
### external/vendor/num-conv/LICENSE-Apache
@@ -175,28 +175,3 @@
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 Jacob Pratt
-
- 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.
### external/vendor/num-conv/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2023 Jacob Pratt
+Copyright (c) Jacob Pratt
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
### external/vendor/num-conv/README.md
@@ -2,4 +2,5 @@
`num_conv` is a crate to convert between integer types without using `as` casts. This provides
better certainty when refactoring, makes the exact behavior of code more explicit, and allows using
-turbofish syntax.
+turbofish syntax. The crate is currently in the process of being uplifted into the standard library;
+see [rust-lang/rust#154330](https://github.com/rust-lang/rust/issues/154330) for details.
### external/vendor/num-conv/src/lib.rs
@@ -1,6 +1,8 @@
//! `num_conv` is a crate to convert between integer types without using `as` casts. This provides
//! better certainty when refactoring, makes the exact behavior of code more explicit, and allows
-//! using turbofish syntax.
+//! using turbofish syntax. The crate is currently in the process of being uplifted into the
+//! standard library; see [rust-lang/rust#154330](https://github.com/rust-lang/rust/issues/154330)
+//! for details.
#![no_std]
@@ -13,7 +15,8 @@
/// use num_conv::prelude::*;
/// ```
pub mod prelude {
- pub use crate::{CastSigned as _, CastUnsigned as _, Extend as _, Truncate as _};
+ #[allow(deprecated)]
+ pub use crate::{Extend as _, Truncate as _, Widen as _};
}
mod sealed {
@@ -30,90 +33,75 @@ mod sealed {
i8 i16 i32 i64 i128 isize
}
+ #[deprecated(since = "0.2.2", note = "use `WidenTargetSealed` instead")]
pub trait ExtendTargetSealed<T> {
+ #[deprecated(since = "0.2.2", note = "use `widen` instead")]
fn extend(self) -> T;
}
+ pub trait WidenTargetSealed<T> {
+ fn widen(self) -> T;
+ }
+
pub trait TruncateTargetSealed<T> {
fn truncate(self) -> T;
+ fn saturating_truncate(self) -> T;
+ fn checked_truncate(self) -> Option<T>;
}
}
-/// Cast to a signed integer of the same size.
-///
-/// This trait is implemented for all integers. Unsigned to signed casts are equivalent to
-/// `0.wrapping_add_signed(value)`, while signed to signed casts are an identity conversion.
-///
-/// ```rust
-/// # use num_conv::CastSigned;
-/// assert_eq!(u8::MAX.cast_signed(), -1_i8);
-/// assert_eq!(u16::MAX.cast_signed(), -1_i16);
-/// assert_eq!(u32::MAX.cast_signed(), -1_i32);
-/// assert_eq!(u64::MAX.cast_signed(), -1_i64);
-/// assert_eq!(u128::MAX.cast_signed(), -1_i128);
-/// assert_eq!(usize::MAX.cast_signed(), -1_isize);
-/// ```
+/// A type that can be used with turbofish syntax in [`Extend::extend`].
///
-/// ```rust
-/// # use num_conv::CastSigned;
-/// assert_eq!(0_i8.cast_signed(), 0_i8);
-/// assert_eq!(0_i16.cast_signed(), 0_i16);
-/// assert_eq!(0_i32.cast_signed(), 0_i32);
-/// assert_eq!(0_i64.cast_signed(), 0_i64);
-/// assert_eq!(0_i128.cast_signed(), 0_i128);
-/// assert_eq!(0_isize.cast_signed(), 0_isize);
-/// ```
-pub trait CastSigned: sealed::Integer {
- /// The signed integer type with the same size as `Self`.
- type Signed;
+/// It is unlikely that you will want to use this trait directly. You are probably looking for the
+/// [`Extend`] trait.
+#[deprecated(since = "0.2.2", note = "use `WidenTarget` instead")]
+#[allow(deprecated)]
+pub trait ExtendTarget<T>: sealed::ExtendTargetSealed<T> {}
- /// Cast an integer to the signed integer of the same size.
- fn cast_signed(self) -> Self::Signed;
-}
+/// A type that can be used with turbofish syntax in [`Widen::widen`].
+///
+/// It is unlikely that you will want to use this trait directly. You are probably looking for the
+/// [`Widen`] trait.
+pub trait WidenTarget<T>: sealed::WidenTargetSealed<T> {}
-/// Cast to an unsigned integer of the same size.
+/// A type that can be used with turbofish syntax in [`Truncate::truncate`].
///
-/// This trait is implemented for all integers. Signed to unsigned casts are equivalent to
-/// `0.wrapping_add_unsigned(value)`, while unsigned to unsigned casts are an identity conversion.
+/// It is unlikely that you will want to use this trait directly. You are probably looking for the
+/// [`Truncate`] trait.
+pub trait TruncateTarget<T>: sealed::TruncateTargetSealed<T> {}
+
+/// Widen to an integer of the same size or larger, preserving its value.
///
/// ```rust
-/// # use num_conv::CastUnsigned;
-/// assert_eq!((-1_i8).cast_unsigned(), u8::MAX);
-/// assert_eq!((-1_i16).cast_unsigned(), u16::MAX);
-/// assert_eq!((-1_i32).cast_unsigned(), u32::MAX);
-/// assert_eq!((-1_i64).cast_unsigned(), u64::MAX);
-/// assert_eq!((-1_i128).cast_unsigned(), u128::MAX);
-/// assert_eq!((-1_isize).cast_unsigned(), usize::MAX);
+/// # use num_conv::Widen;
+/// assert_eq!(0_u8.widen::<u16>(), 0_u16);
+/// assert_eq!(0_u16.widen::<u32>(), 0_u32);
+/// assert_eq!(0_u32.widen::<u64>(), 0_u64);
+/// assert_eq!(0_u64.widen::<u128>(), 0_u128);
/// ```
///
/// ```rust
-/// # use num_conv::CastUnsigned;
-/// assert_eq!(0_u8.cast_unsigned(), 0_u8);
-/// assert_eq!(0_u16.cast_unsigned(), 0_u16);
-/// assert_eq!(0_u32.cast_unsigned(), 0_u32);
-/// assert_eq!(0_u64.cast_unsigned(), 0_u64);
-/// assert_eq!(0_u128.cast_unsigned(), 0_u128);
-/// assert_eq!(0_usize.cast_unsigned(), 0_usize);
+/// # use num_conv::Widen;
+/// assert_eq!((-1_i8).widen::<i16>(), -1_i16);
+/// assert_eq!((-1_i16).widen::<i32>(), -1_i32);
+/// assert_eq!((-1_i32).widen::<i64>(), -1_i64);
+/// assert_eq!((-1_i64).widen::<i128>(), -1_i128);
/// ```
-pub trait CastUnsigned: sealed::Integer {
- /// The unsigned integer type with the same size as `Self`.
- type Unsigned;
-
- /// Cast an integer to the unsigned integer of the same size.
- fn cast_unsigned(self) -> Self::Unsigned;
+pub trait Widen: sealed::Integer {
+ /// Widen an integer to an integer of the same size or larger, preserving its value.
+ fn widen<T>(self) -> T
+ where
+ Self: WidenTarget<T>;
}
-/// A type that can be used with turbofish syntax in [`Extend::extend`].
-///
-/// It is unlikely that you will want to use this trait directly. You are probably looking for the
-/// [`Extend`] trait.
-pub trait ExtendTarget<T>: sealed::ExtendTargetSealed<T> {}
-
-/// A type that can be used with turbofish syntax in [`Truncate::truncate`].
-///
-/// It is unlikely that you will want to use this trait directly. You are probably looking for the
-/// [`Truncate`] trait.
-pub trait TruncateTarget<T>: sealed::TruncateTargetSealed<T> {}
+impl<T: sealed::Integer> Widen for T {
+ fn widen<U>(self) -> U
+ where
+ T: WidenTarget<U>,
+ {
+ sealed::WidenTargetSealed::widen(self)
+ }
+}
/// Extend to an integer of the same size or larger, preserving its value.
///
@@ -132,13 +120,16 @@ pub trait TruncateTarget<T>: sealed::TruncateTargetSealed<T> {}
/// assert_eq!((-1_i32).extend::<i64>(), -1_i64);
/// assert_eq!((-1_i64).extend::<i128>(), -1_i128);
/// ```
+#[deprecated(since = "0.2.2", note = "use `Widen` instead")]
+#[allow(deprecated)]
pub trait Extend: sealed::Integer {
/// Extend an integer to an integer of the same size or larger, preserving its value.
fn extend<T>(self) -> T
where
Self: ExtendTarget<T>;
}
+#[allow(deprecated)]
impl<T: sealed::Integer> Extend for T {
fn extend<U>(self) -> U
where
@@ -148,7 +139,9 @@ impl<T: sealed::Integer> Extend for T {
}
}
-/// Truncate to an integer of the same size or smaller, preserving the least significant bits.
+/// Truncate to an integer of the same size or smaller.
+///
+/// Preserve the least significant bits with `.truncate()`:
///
/// ```rust
/// # use num_conv::Truncate;
@@ -165,12 +158,60 @@ impl<T: sealed::Integer> Extend for T {
/// assert_eq!((-1_i64).truncate::<i32>(), -1_i32);
/// assert_eq!((-1_i128).truncate::<i64>(), -1_i64);
/// ```
+///
+/// Saturate to the numeric bounds with `.saturating_truncate()`:
+///
+/// ```rust
+/// # use num_conv::Truncate;
+/// assert_eq!(500_u16.saturating_truncate::<u8>(), u8::MAX);
+/// assert_eq!(u32::MAX.saturating_truncate::<u16>(), u16::MAX);
+/// assert_eq!(u64::MAX.saturating_truncate::<u32>(), u32::MAX);
+/// assert_eq!(u128::MAX.saturating_truncate::<u64>(), u64::MAX);
+/// ```
+///
+/// ```rust
+/// # use num_conv::Truncate;
+/// assert_eq!((-500_i16).saturating_truncate::<i8>(), i8::MIN);
+/// assert_eq!(i32::MIN.saturating_truncate::<i16>(), i16::MIN);
+/// assert_eq!(i64::MIN.saturating_truncate::<i32>(), i32::MIN);
+/// assert_eq!(i128::MIN.saturating_truncate::<i64>(), i64::MIN);
+/// ```
+///
+/// Checked with `.checked_truncate()`, returning `None` if the value is out of range:
+///
+/// ```rust
+/// # use num_conv::Truncate;
+/// assert_eq!(u16::MAX.checked_truncate::<u8>(), None);
+/// assert_eq!(u32::MAX.checked_truncate::<u16>(), None);
+/// assert_eq!(u64::MAX.checked_truncate::<u32>(), None);
+/// assert_eq!(u128::MAX.checked_truncate::<u64>(), None);
+/// ```
+///
+/// ```rust
+/// # use num_conv::Truncate;
+/// assert_eq!(i16::MIN.checked_truncate::<i8>(), None);
+/// assert_eq!(i32::MIN.checked_truncate::<i16>(), None);
+/// assert_eq!(i64::MIN.checked_truncate::<i32>(), None);
+/// assert_eq!(i128::MIN.checked_truncate::<i64>(), None);
+/// ```
pub trait Truncate: sealed::Integer {
/// Truncate an integer to an integer of the same size or smaller, preserving the least
/// significant bits.
fn truncate<T>(self) -> T
where
Self: TruncateTarget<T>;
+
+ /// Truncate an integer to an integer of the same size or smaller, saturating to the numeric
+ /// bounds instead of wrapping.
+ fn saturating_truncate<T>(self) -> T
+ where
+ Self: TruncateTarget<T>;
+
+ /// Truncate an integer to an integer of the same size or smaller, returning `None` if the value
+ /// is out of range.
+ fn checked_truncate<T>(self) -> Option<T>
+ where
+ Self: TruncateTarget<T>;
}
impl<T: sealed::Integer> Truncate for T {
@@ -180,58 +221,28 @@ impl<T: sealed::Integer> Truncate for T {
{
sealed::TruncateTargetSealed::truncate(self)
}
-}
-
-macro_rules! impl_cast_signed {
- ($($($from:ty),+ => $to:ty;)*) => {$($(
- const _: () = assert!(
- core::mem::size_of::<$from>() == core::mem::size_of::<$to>(),
- concat!(
- "cannot cast ",
- stringify!($from),
- " to ",
- stringify!($to),
- " because they are different sizes"
- )
- );
-
- impl CastSigned for $from {
- type Signed = $to;
- fn cast_signed(self) -> Self::Signed {
- self as _
- }
- }
- )+)*};
-}
-macro_rules! impl_cast_unsigned {
- ($($($from:ty),+ => $to:ty;)*) => {$($(
- const _: () = assert!(
- core::mem::size_of::<$from>() == core::mem::size_of::<$to>(),
- concat!(
- "cannot cast ",
- stringify!($from),
- " to ",
- stringify!($to),
- " because they are different sizes"
- )
- );
+ fn saturating_truncate<U>(self) -> U
+ where
+ T: TruncateTarget<U>,
+ {
+ sealed::TruncateTargetSealed::saturating_truncate(self)
+ }
- impl CastUnsigned for $from {
- type Unsigned = $to;
- fn cast_unsigned(self) -> Self::Unsigned {
- self as _
- }
- }
- )+)*};
+ fn checked_truncate<U>(self) -> Option<U>
+ where
+ T: TruncateTarget<U>,
+ {
+ sealed::TruncateTargetSealed::checked_truncate(self)
+ }
}
-macro_rules! impl_extend {
+macro_rules! impl_widen {
($($from:ty => $($to:ty),+;)*) => {$($(
const _: () = assert!(
core::mem::size_of::<$from>() <= core::mem::size_of::<$to>(),
concat!(
- "cannot extend ",
+ "cannot widen ",
stringify!($from),
" to ",
stringify!($to),
@@ -242,13 +253,24 @@ macro_rules! impl_extend {
)
);
+ #[allow(deprecated)]
impl sealed::ExtendTargetSealed<$to> for $from {
+ #[inline]
fn extend(self) -> $to {
self as _
}
}
+ impl sealed::WidenTargetSealed<$to> for $from {
+ #[inline]
+ fn widen(self) -> $to {
+ self as _
+ }
+ }
+
+ #[allow(deprecated)]
impl ExtendTarget<$to> for $from {}
+ impl WidenTarget<$to> for $from {}
)+)*};
}
@@ -269,34 +291,37 @@ macro_rules! impl_truncate {
);
impl sealed::TruncateTargetSealed<$to> for $from {
+ #[inline]
fn truncate(self) -> $to {
self as _
}
+
+ #[inline]
+ fn saturating_truncate(self) -> $to {
+ if self > <$to>::MAX as _ {
+ <$to>::MAX
+ } else if self < <$to>::MIN as _ {
+ <$to>::MIN
+ } else {
+ self as _
+ }
+ }
+
+ #[inline]
+ fn checked_truncate(self) -> Option<$to> {
+ if self > <$to>::MAX as _ || self < <$to>::MIN as _ {
+ None
+ } else {
+ Some(self as _)
+ }
+ }
}
impl TruncateTarget<$to> for $from {}
)+)*};
}
-impl_cast_signed! {
- u8, i8 => i8;
- u16, i16 => i16;
- u32, i32 => i32;
- u64, i64 => i64;
- u128, i128 => i128;
- usize, isize => isize;
-}
-
-impl_cast_unsigned! {
- u8, i8 => u8;
- u16, i16 => u16;
- u32, i32 => u32;
- u64, i64 => u64;
- u128, i128 => u128;
- usize, isize => usize;
-}
-
-impl_extend! {
+impl_widen! {
u8 => u8, u16, u32, u64, u128, usize;
u16 => u16, u32, u64, u128, usize;
u32 => u32, u64, u128;
### external/vendor/time-core/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"48dd5646402d97fb3677e20e223f61baf24daefe6a3f593fed2345217b93e63d","Cargo.lock":"50a995426b9324184c9872b034a462a7bf679d0220e9e7102446150433b9a377","Cargo.toml":"b4279d320a3fc294152ba2ce3963c598101bbb438779776ac6fbd45432375a85","Cargo.toml.orig":"607719b275aa5a6d58b8051461b1c113140766e0e415a300135f586a132e0b46","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","src/convert.rs":"b77b3f89f505a28b1c1a48008ddd88f8d4c03ae3918dcffef8d07086eee1fce2","src/hint.rs":"3ab785980313b8c7593a6f06f0a09e0c32863e602b56faeba35b198042f21619","src/lib.rs":"3c727b5ea68b6992751cad27282921055cec1dfa700bb0f885d25a25c118247e","src/util.rs":"442af080e6546305cc883df2512df0e940e6ef4f9c60ccd6b2e302e44054ae14"},"package":"40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"ae8357049d05a68929c409c262d5a6ad68bdc34198a4e9459d120f80e1a96b9e","Cargo.lock":"05e04805f5ae445d8f18e9a765bda47bc36b35b7488792d72e6c47154b3ac7c9","Cargo.toml":"e4fcb8945ac8299fa6ece980320f557d1f1b32f9281e4dc9d047c87bc81fb41e","Cargo.toml.orig":"3189bca58e349f0368a4de337d76dd6129c6f2ccdd45453912d6783e7128ed2f","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","src/hint.rs":"3ab785980313b8c7593a6f06f0a09e0c32863e602b56faeba35b198042f21619","src/lib.rs":"471d4a128ebd5fec6565c63c1e546bdba7154d7c434e9323bbe5343c3b8ad3ed","src/unit.rs":"5149bc68ad39ac3c1a36b2b2c09d2bf699a90e52284a49b4eec53cb65e5fc4bb","src/util.rs":"d8aea82023758a2d81c01ed28c08274cc56b3444ff95510af5d67b0cba54c171"},"package":"9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"}
\ No newline at end of file
### external/vendor/time-core/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "45b9932e57ffedb43257bf2837c171ebc37a73c3"
+ "sha1": "5d8737c39b9170c36c99cfc1f9f49cf0c059c63a"
},
"path_in_vcs": "time-core"
}
\ No newline at end of file
### external/vendor/time-core/Cargo.lock
@@ -1,7 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "time-core"
-version = "0.1.6"
+version = "0.1.9"
### external/vendor/time-core/Cargo.toml
@@ -10,10 +10,10 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.81.0"
+edition = "2024"
+rust-version = "1.88.0"
name = "time-core"
-version = "0.1.6"
+version = "0.1.9"
authors = [
"Jacob Pratt <open-source@jhpratt.dev>",
"Time contributors",
@@ -37,14 +37,17 @@ license = "MIT OR Apache-2.0"
repository = "https://github.com/time-rs/time"
[package.metadata.docs.rs]
+all-features = true
+targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = ["--generate-link-to-definition"]
+[features]
+large-dates = []
+
[lib]
name = "time_core"
path = "src/lib.rs"
-[dependencies]
-
[lints.clippy]
alloc-instead-of-core = "deny"
as-underscore = "warn"
### external/vendor/time-core/Cargo.toml.orig
@@ -1,19 +1,22 @@
+lints.workspace = true
+
[package]
name = "time-core"
-version = "0.1.6"
-authors = ["Jacob Pratt <open-source@jhpratt.dev>", "Time contributors"]
-edition = "2021"
-rust-version = "1.81.0"
-repository = "https://github.com/time-rs/time"
-keywords = ["date", "time", "calendar", "duration"]
+version = "0.1.9"
categories = ["date-and-time"]
-license = "MIT OR Apache-2.0"
description = "This crate is an implementation detail and should not be relied upon directly."
+authors.workspace = true
+edition.workspace = true
+keywords.workspace = true
+license.workspace = true
+repository.workspace = true
+rust-version.workspace = true
+
[package.metadata.docs.rs]
+all-features = true
+targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = ["--generate-link-to-definition"]
-[lints]
-workspace = true
-
-[dependencies]
+[features]
+large-dates = []
### external/vendor/time-core/src/lib.rs
@@ -7,6 +7,6 @@
#![doc(html_logo_url = "https://avatars0.githubusercontent.com/u/55999857")]
#![doc(test(attr(deny(warnings))))]
-pub mod convert;
mod hint;
+pub mod unit;
pub mod util;
### external/vendor/time-core/src/unit.rs
@@ -2,21 +2,6 @@
use self::sealed::{DefaultOutput, MultipleOf};
-mod sealed {
- /// A trait for defining the ratio of two units of time.
- ///
- /// This trait is used to implement the `per` method on the various structs.
- #[diagnostic::on_unimplemented(message = "`{Self}` is not an integer multiple of `{T}`")]
- pub trait MultipleOf<T, Output> {
- /// The number of one unit of time in the other.
- const VALUE: Output;
- }
-
- pub trait DefaultOutput<T> {
- type Output;
- }
-}
-
/// Given the list of types, stringify them as a list.
macro_rules! stringify_outputs {
(@inner $first:ty) => {
@@ -33,28 +18,24 @@ macro_rules! stringify_outputs {
};
}
-// Split this out to a separate function to permit naming `T` while also using `impl Trait` as a
-// parameter in the public API.`
-const fn multiple_of_value<T, U, Output>(_: T) -> Output
-where
- T: MultipleOf<U, Output> + Copy,
-{
- T::VALUE
+/// Declare all unit types.
+macro_rules! declare_types {
+ ($($t:ident ($str:literal))+) => {$(
+ #[doc = concat!("A unit of time representing exactly `N` ", $str, "s.")]
+ #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+ pub struct $t<const N: u128 = 1>;
+ )+};
}
-/// Declare and implement `Per` for all relevant types. Identity implementations are automatic.
+/// Implement `Per` for all relevant types. Identity implementations are automatic.
macro_rules! impl_per {
- ($($t:ident ($str:literal) per {$(
+ ($($t:ident per {$(
$larger:ident : [$default_output:ty]
$($int_output:ty)|+ = $int_value:expr;
$($float_output:ty)|+ = $float_value:expr;
)+})*) => {$(
- #[doc = concat!("A unit of time representing exactly one ", $str, ".")]
- #[derive(Debug, Clone, Copy)]
- pub struct $t;
-
- impl $t {
+ impl $t<1> {
#[doc = concat!("Obtain the number of times `", stringify!($t), "` can fit into `T`.")]
#[doc = concat!("If `T` is smaller than `", stringify!($t), "`, the code will fail to")]
/// compile. The return type is the smallest unsigned integer type that can represent
@@ -106,8 +87,118 @@ macro_rules! impl_per {
)*};
}
+/// Implement `PartialEq` and `PartialOrd` between unit types.
+macro_rules! impl_partial_eq_ord {
+ ($($self:ident {
+ $(> $($bigger:ident)+;)?
+ $(< $($smaller:ident)+;)?
+ })*) => {$(
+ $($(
+ impl<const N: u128> PartialEq<$bigger<N>> for $self<N> {
+ #[inline]
+ fn eq(&self, _: &$bigger<N>) -> bool {
+ false
+ }
+ }
+
+ impl<const N: u128> PartialOrd<$bigger<N>> for $self<N> {
+ #[inline]
+ fn partial_cmp(&self, _: &$bigger<N>) -> Option<core::cmp::Ordering> {
+ Some(core::cmp::Ordering::Greater)
+ }
+ }
+ )+)?
+
+ $($(
+ impl<const N: u128> PartialEq<$smaller<N>> for $self<N> {
+ #[inline]
+ fn eq(&self, _: &$smaller<N>) -> bool {
+ false
+ }
+ }
+
+ impl<const N: u128> PartialOrd<$smaller<N>> for $self<N> {
+ #[inline]
+ fn partial_cmp(&self, _: &$smaller<N>) -> Option<core::cmp::Ordering> {
+ Some(core::cmp::Ordering::Less)
+ }
+ }
+ )+)?
+ )*};
+}
+
+/// Symmetrically implement `PartialEq` and `PartialOrd` between `Unit` and all unit types.
+macro_rules! impl_partial_eq_ord_for_unit {
+ ($($ty:ident)+) => {$(
+ impl<const N: u128> PartialEq<$ty<N>> for Unit<N> {
+ #[inline]
+ fn eq(&self, _: &$ty<N>) -> bool {
+ *self == Self::$ty
+ }
+ }
+
+ impl<const N: u128> PartialEq<Unit<N>> for $ty<N> {
+ #[inline]
+ fn eq(&self, other: &Unit<N>) -> bool {
+ *other == Unit::$ty
+ }
+ }
+
+ impl<const N: u128> PartialOrd<$ty<N>> for Unit<N> {
+ #[inline]
+ fn partial_cmp(&self, _: &$ty<N>) -> Option<core::cmp::Ordering> {
+ self.partial_cmp(&Unit::$ty)
+ }
+ }
+
+ impl<const N: u128> PartialOrd<Unit<N>> for $ty<N> {
+ #[inline]
+ fn partial_cmp(&self, other: &Unit<N>) -> Option<core::cmp::Ordering> {
+ Unit::$ty.partial_cmp(other)
+ }
+ }
+ )+};
+}
+
+mod sealed {
+ /// A trait for defining the ratio of two units of time.
+ ///
+ /// This trait is used to implement the `per` method on the various structs.
+ #[diagnostic::on_unimplemented(message = "`{Self}` is not an integer multiple of `{T}`")]
+ pub trait MultipleOf<T, Output> {
+ /// The number of one unit of time in the other.
+ const VALUE: Output;
+ }
+
+ /// A trait for defining the default output type for the `per` method.
+ pub trait DefaultOutput<T> {
+ /// The default output type for the `per` method.
+ type Output;
+ }
+}
+
+// Split this out to a separate function to permit naming `T` while also using `impl Trait` as a
+// parameter in the public API.`
+const fn multiple_of_value<T, U, Output>(_: T) -> Output
+where
+ T: MultipleOf<U, Output> + Copy,
+{
+ T::VALUE
+}
+
+declare_types! {
+ Nanosecond ("nanosecond")
+ Microsecond ("microsecond")
+ Millisecond ("millisecond")
+ Second ("second")
+ Minute ("minute")
+ Hour ("hour")
+ Day ("day")
+ Week ("week")
+}
+
impl_per! {
- Nanosecond ("nanosecond") per {
+ Nanosecond per {
Nanosecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Microsecond: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.;
Millisecond: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 1_000_000; f32|f64 = 1_000_000.;
@@ -118,7 +209,7 @@ impl_per! {
Day: [u64] u64|u128|i64|i128 = 86_400_000_000_000; f32|f64 = 86_400_000_000_000.;
Week: [u64] u64|u128|i64|i128 = 604_800_000_000_000; f32|f64 = 604_800_000_000_000.;
}
- Microsecond ("microsecond") per {
+ Microsecond per {
Microsecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Millisecond: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.;
Second: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 1_000_000; f32|f64 = 1_000_000.;
@@ -127,37 +218,94 @@ impl_per! {
Day: [u64] u64|u128|i64|i128 = 86_400_000_000; f32|f64 = 86_400_000_000.;
Week: [u64] u64|u128|i64|i128 = 604_800_000_000; f32|f64 = 604_800_000_000.;
}
- Millisecond ("millisecond") per {
+ Millisecond per {
Millisecond: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Second: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_000; f32|f64 = 1_000.;
Minute: [u16] u16|u32|u64|u128|usize|i32|i64|i128|isize = 60_000; f32|f64 = 60_000.;
Hour: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 3_600_000; f32|f64 = 3_600_000.;
Day: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 86_400_000; f32|f64 = 86_400_000.;
Week: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 604_800_000; f32|f64 = 604_800_000.;
}
- Second ("second") per {
+ Second per {
Second: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Minute: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 60; f32|f64 = 60.;
Hour: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 3_600; f32|f64 = 3_600.;
Day: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 86_400; f32|f64 = 86_400.;
Week: [u32] u32|u64|u128|usize|i32|i64|i128|isize = 604_800; f32|f64 = 604_800.;
}
- Minute ("minute") per {
+ Minute per {
Minute: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Hour: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 60; f32|f64 = 60.;
Day: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 1_440; f32|f64 = 1_440.;
Week: [u16] u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 10_080; f32|f64 = 10_080.;
}
- Hour ("hour") per {
+ Hour per {
Hour: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Day: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 24; f32|f64 = 24.;
Week: [u8] u8|u16|u32|u64|u128|usize|i16|i32|i64|i128|isize = 168; f32|f64 = 168.;
}
- Day ("day") per {
+ Day per {
Day: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
Week: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 7; f32|f64 = 7.;
}
- Week ("week") per {
+ Week per {
Week: [u8] u8|u16|u32|u64|u128|usize|i8|i16|i32|i64|i128|isize = 1; f32|f64 = 1.;
}
}
+
+impl_partial_eq_ord! {
+ Nanosecond {
+ < Microsecond Millisecond Second Minute Hour Day Week;
+ }
+ Microsecond {
+ > Nanosecond;
+ < Millisecond Second Minute Hour Day Week;
+ }
+ Millisecond {
+ > Nanosecond Microsecond;
+ < Second Minute Hour Day Week;
+ }
+ Second {
+ > Nanosecond Microsecond Millisecond;
+ < Minute Hour Day Week;
+ }
+ Minute {
+ > Nanosecond Microsecond Millisecond Second;
+ < Hour Day Week;
+ }
+ Hour {
+ > Nanosecond Microsecond Millisecond Second Minute;
+ < Day Week;
+ }
+ Day {
+ > Nanosecond Microsecond Millisecond Second Minute Hour;
+ < Week;
+ }
+ Week {
+ > Nanosecond Microsecond Millisecond Second Minute Hour Day;
+ }
+}
+
+/// A statically-known multiple of a given unit of time.
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
+pub enum Unit<const N: u128 = 1> {
+ #[expect(missing_docs)]
+ Nanosecond,
+ #[expect(missing_docs)]
+ Microsecond,
+ #[expect(missing_docs)]
+ Millisecond,
+ #[expect(missing_docs)]
+ Second,
+ #[expect(missing_docs)]
+ Minute,
+ #[expect(missing_docs)]
+ Hour,
+ #[expect(missing_docs)]
+ Day,
+ #[expect(missing_docs)]
+ Week,
+}
+
+impl_partial_eq_ord_for_unit![Nanosecond Microsecond Millisecond Second Minute Hour Day Week];
### external/vendor/time-core/src/util.rs
@@ -2,6 +2,70 @@
use crate::hint;
+/// Versions of functions that are optimized for when the year has already been range-validated.
+///
+/// The implementations of these functions depend on whether the `large-dates` feature is enabled.
+///
+/// Note: This module is not exposed by the `time` crate. It is an implementation detail.
+pub mod range_validated {
+ /// Returns if the provided year is a leap year in the proleptic Gregorian calendar, assuming
+ /// the year has already been range-validated.
+ ///
+ /// Behavior is unspecified for years outside the valid range.
+ ///
+ /// Note: This function is not exposed by the `time` crate. It is an implementation detail.
+ #[inline]
+ #[track_caller]
+ pub const fn is_leap_year(year: i32) -> bool {
+ #[cfg(feature = "large-dates")]
+ {
+ super::is_leap_year(year)
+ }
+ #[cfg(not(feature = "large-dates"))]
+ {
+ debug_assert!(year >= -9999);
+ debug_assert!(year <= 9999);
+ year.unsigned_abs().wrapping_mul(0x20003D7) & 0x6007C0F <= 0x7C00
+ }
+ }
+
+ /// Get the number of calendar days in a given year, assuming the year has already been
+ /// range-validated.
+ ///
+ /// Behavior is unspecified for years outside the valid range.
+ ///
+ /// Note: This function is not exposed by the `time` crate. It is an implementation detail.
+ #[inline]
+ #[track_caller]
+ pub const fn days_in_year(year: i32) -> u16 {
+ #[cfg(feature = "large-dates")]
+ {
+ super::days_in_year(year)
+ }
+ #[cfg(not(feature = "large-dates"))]
+ {
+ if is_leap_year(year) { 366 } else { 365 }
+ }
+ }
+
+ /// Get the number of days in the month of a given year, assuming the year has already been
+ /// range-validated.
+ ///
+ /// Note: This function is not exposed by the `time` crate. It is an implementation detail.
+ #[inline]
+ #[track_caller]
+ pub const fn days_in_month(month: u8, year: i32) -> u8 {
+ #[cfg(feature = "large-dates")]
+ {
+ super::days_in_month(month, year)
+ }
+ #[cfg(not(feature = "large-dates"))]
+ {
+ super::days_in_month_leap(month, is_leap_year(year))
+ }
+ }
+}
+
/// Returns if the provided year is a leap year in the proleptic Gregorian calendar. Uses
/// [astronomical year numbering](https://en.wikipedia.org/wiki/Astronomical_year_numbering).
///
@@ -13,10 +77,14 @@ use crate::hint;
/// assert!(!is_leap_year(2005));
/// assert!(!is_leap_year(2100));
/// ```
+// https://hueffner.de/falk/blog/a-leap-year-check-in-three-instructions.html
#[inline]
pub const fn is_leap_year(year: i32) -> bool {
- let d = if year % 100 == 0 { 15 } else { 3 };
- year & d == 0
+ (year as i64)
+ .unsigned_abs()
+ .wrapping_mul(0x4000_0000_28F5_C28F)
+ & 0xC000_000F_8000_000F
+ <= 0xF_8000_0000
}
/// Get the number of calendar days in a given year.
@@ -33,11 +101,7 @@ pub const fn is_leap_year(year: i32) -> bool {
/// ```
#[inline]
pub const fn days_in_year(year: i32) -> u16 {
- if is_leap_year(year) {
- 366
- } else {
- 365
- }
+ if is_leap_year(year) { 366 } else { 365 }
}
/// Get the number of weeks in the ISO year.
@@ -76,16 +140,23 @@ pub const fn weeks_in_year(year: i32) -> u8 {
///
/// Note: This function is not exposed by the `time` crate. It is an implementation detail.
#[inline]
+#[track_caller]
pub const fn days_in_month(month: u8, year: i32) -> u8 {
+ days_in_month_leap(month, is_leap_year(year))
+}
+
+/// Get the number of days in the month. The year does not need to be known, but whether the
+/// year is a leap year does.
+///
+/// Note: This function is not exposed by the `time` crate. It is an implementation detail.
+#[inline]
+#[track_caller]
+pub const fn days_in_month_leap(month: u8, is_leap_year: bool) -> u8 {
debug_assert!(month >= 1);
debug_assert!(month <= 12);
if hint::unlikely(month == 2) {
- if is_leap_year(year) {
- 29
- } else {
- 28
- }
+ if is_leap_year { 29 } else { 28 }
} else {
30 | month ^ (month >> 3)
}
### external/vendor/time/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"05a2c36695180f175d6728746d7c3841b1a101f457d067a2458eaecb2e8c42e3","Cargo.lock":"9a61723da0c719a9784de34f15d3adb41a0891a0e602c2bcbbd97e1151d77322","Cargo.toml":"1cc4d9ea5fc853fd25c38ebc1710bef1e8d0f69c1632deaf89c6a7bae23417fc","Cargo.toml.orig":"767142e0fa169cd8caa591da389681070cde1885ed43eb376e93ec4a6cf3dcd5","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","README.md":"2678dc82b3ed3e7145d25a5d846117f08415451b92fe885fb9e9b776867ba22e","src/date.rs":"fc3a5e54e9107e00f4eea4711419a020556695d654fd23c588c65219bbec2891","src/duration.rs":"7fe20a72cac760c7b59584c93149b9e3a6f4abb83ba5019429a6e7e214365c88","src/error/component_range.rs":"1f188dc522190369ac4563149228bda765f9eb00c71ba1e006d2b455c20b6ed4","src/error/conversion_range.rs":"b5f436fda3c3fc238f2e94fbbb4c27ff583f74a650b600845b7be2dc78cd3d88","src/error/different_variant.rs":"f790e3e7a81dee90ea5142b18562af3ea0d0541737fa477d6170dc3d2dfbeeb3","src/error/format.rs":"ea24ca2036e2fcfe86ad06a03ff65bc984b722929c40950b97f45cce965537eb","src/error/indeterminate_offset.rs":"668737c953d9a53f275d07f1628c13f32e416055fb53a7c36f9093a1f6e4665f","src/error/invalid_format_description.rs":"a56308c9cefb3429254f2ba89820a80102f70d51c5e20163f19edea6fa2cdbe8","src/error/invalid_variant.rs":"4e471e88ff7db4319d49a00fd3c7078b366bb2eef40bcdfa75e6fd8d145d449b","src/error/mod.rs":"d56970e05086af93156b4daf262c2ace04e773c8ba037e5cab1d4e894e5ca817","src/error/parse.rs":"14efda450fb37c06de9ea4d88849433d21d3003e127ef48abf6ec2da773973ae","src/error/parse_from_description.rs":"f20b165557b49ecc76e929473104f2e3c5a5b296637765ebd133be5ae56d2cd9","src/error/try_from_parsed.rs":"30474fc2c707471bcfbd314a098b15dfd7c009af85f67a845f669e4dfa69d23f","src/ext/digit_count.rs":"0c6a8f1bdf1594698e393ad840c08291c82911ee28e24fc6e09cb9eeacc0dc6c","src/ext/instant.rs":"33eba05f3750eacb612f1df4446db5aac4dd3d659f70387817f5712ed3cc2066","src/ext/mod.rs":"75035e71d192eaf7a19238d55eca8b4344bb81183f5b9dae0b5abd777941e28f","src/ext/numerical_duration.rs":"7e1e1f79161c62e1bd04b87298fb39625e8fa8a4574ff86fa3f0dbbe9df692bf","src/ext/numerical_std_duration.rs":"9a86091d174d86dafa70263ef62a470d453eee15bbf11aca81931782a75b6535","src/ext/systemtime.rs":"943cbb769684b12543bc36d1d9789f33300bc9fe44dd3ce0327ca8b4938e6b7d","src/format_description/borrowed_format_item.rs":"f51f2a5411c0ccfae39abc48c707eede3d1026a5aa195b3e9af5ac9b9ab32e21","src/format_description/component.rs":"b65c0ca896ea6ec8dbfc7570c69849c88cbba6031a2847dcfdce06d721a59397","src/format_description/mod.rs":"d6ca12469c42910fd459d2cf5cebf93e694220cf51a6028cca6912fbe92b96ff","src/format_description/modifier.rs":"32da407f663296477b5025f6833e340abfd987d04275e47df1f724dfc8c257b4","src/format_description/owned_format_item.rs":"330299c87d2028142acf9f6448a3e979b03def9b01f687a09d09eeaa89c90a33","src/format_description/parse/ast.rs":"c91a033d805cc4b3e5158164474dbb1c13e4c5baddcfe45074e15f1a58ce5f97","src/format_description/parse/format_item.rs":"16a0347e54c01f0c6fc435febbe305c4736a22cad41144b9f02d3fbbcd032fc8","src/format_description/parse/lexer.rs":"9e8b717a4525f010827d0b94a63f6a4cd7673f3bfbb373eb2632addba87ce820","src/format_description/parse/mod.rs":"28a4588cd173bbc9e95f821d00fd20b215c0cd995151f4e41063424a34d8f495","src/format_description/parse/strftime.rs":"79e02a5ec5f639a13b2251756b4e14ab6b93a6c8bc8ff4501d6739607add5022","src/format_description/well_known/iso8601.rs":"6c51777c274ba6fe2c6820c17cbf90eb976cf1066fa541fe809de775553397f9","src/format_description/well_known/iso8601/adt_hack.rs":"8583c220699a2e8c9d4042f91e7d731c4794d988d426f45eae69dba9083ca19c","src/format_description/well_known/rfc2822.rs":"36c23394724ae12250d4193cab26887a6ff8f82ca441ea6b0d03c4f1c928b3dd","src/format_description/well_known/rfc3339.rs":"1a6318dffd3ebb6ac7cf96eae3d9b1eb44b1089cf4284fa6a7e935c6fcf1b43c","src/formatting/formattable.rs":"489fb7f6b4bf313ce70aa82b6f16b377197dcd494ee060773da64bbdf8bb63af","src/formatting/iso8601.rs":"f63c9597ef4ba5be43599b6a103aee89a1ff10caf3b66b361810c57bdbf852b1","src/formatting/mod.rs":"26a77b59d35a081b4587f8580d2ec686fa51e29740cf52b29510444c7c69289e","src/hint.rs":"ca02b549ec40bed70b147ebd9e2f3d777726bebe5e5d6463481ffd0f51ee4c2e","src/instant.rs":"ab623d093907cfe795afea2a082ebb0a4ac6fde45702ca7c02e954baaa9886ff","src/internal_macros.rs":"fd0d0c4849f4a88780abb21d728c6cf2521475cf0ad078013af28581a4381cc0","src/interop/js_sys_date_offsetdatetime.rs":"1c4ce21be4cd987f5fe71d96ccfe9c1c8ced2d9d42ff573dd923dd0b4480a0ef","src/interop/js_sys_date_utcdatetime.rs":"ecf07652dc7eb39da484c1c1b9c71764376fc5d6cd16c4b8deec76880d21da69","src/interop/mod.rs":"d8c0905e9fea22e4dddab981a020f79a637f849e17f53e5102416dbce1f6dbea","src/interop/offsetdatetime_systemtime.rs":"e4c9b358f41857837d233d870e26b04dc5c297a8551d5a431cc6729391910238","src/interop/offsetdatetime_utcdatetime.rs":"7d92bd57f274ffb8393e6414222180d61cc17e7a817c8a260f8e5a34e0e7fd99","src/interop/utcdatetime_systemtime.rs":"f99b71d406aba7052c3feee4a039e7904d0985363a64077c805577dd97eb4f90","src/lib.rs":"6b47f2ae4984020f8e15a9d322f3f8d5f5e55aa5fcda24d1f57ce7e1e6752f82","src/macros.rs":"c35b4f4fbb4781dadf70a952649cedf4f4e29b3b571c8bbfa58e9f6ad4071423","src/month.rs":"c5e07c912c5357b1e40a3ed3d1754ae010c485692d32b66c3c202b1bf26f3367","src/offset_date_time.rs":"430e43022cfb9491d66173b0e5e0d69ef2a7e61449fa53b18afd48c5569f6496","src/parsing/combinator/mod.rs":"d6f062140871e0a90786b07caf843fe4e1a7fff08389067230839de16e4de6cb","src/parsing/combinator/rfc/iso8601.rs":"f97e2167a8eac32d87b2a1ef1eda2d83fa952180e1f08b8fca5d4e5b78df2ef5","src/parsing/combinator/rfc/mod.rs":"f30b75d248f5ae92c27646d504703f5489185afb76c998cc4375437b3d15c822","src/parsing/combinator/rfc/rfc2234.rs":"229cf74e6e9ac31d69e33938e2847fdee8ae5940d90a7ac5e1ccf3726723afb1","src/parsing/combinator/rfc/rfc2822.rs":"e27fcfcbd280ce49724f66024bff18f94478de3c2413323c5c4a8af1850c7fdd","src/parsing/component.rs":"80bfaa2d5830dfae1c12c2e2bb822cebd5c755a01fc3d1426cb4ea0031b14bf9","src/parsing/iso8601.rs":"b9033f842c3a81fcc561b0d90ba779a038da3404b99e26471fd1a0c4f3ab712a","src/parsing/mod.rs":"facd9e2622d79ab58beefd80f8451a9176deb575adc1bbe717caccdbae266609","src/parsing/parsable.rs":"2464bd68be308a182ad41e806961378e96f41253fb0824355a654e91ebe53850","src/parsing/parsed.rs":"114db5d793199f4242c0a476beb1c6e91d5bfb48e10fed87c06db7da7a9b105b","src/parsing/shim.rs":"fe685f86fd60f8458cff732219eebac7ad09fa1f2300863a74ceb53959d23359","src/primitive_date_time.rs":"ebf49724584c03106c2c8b3eee7b9f9f29f7b0fa1ff9ed07d28837977cd56b16","src/quickcheck.rs":"a0e57bc78d2d36069a8464785eb9efe60f2a26b928f9ec48a1c2456c7bf155e6","src/rand08.rs":"350246e7a39f0eb60eedfd40b91a10a7658b2cd91ae94772bebf647b94615b9c","src/rand09.rs":"a4973f00730f6dffa0b10b5418f61582ceb1c5c1512dd5e5032d28aad4eca7e2","src/serde/iso8601.rs":"a110fceeb0979824ac2fe844b1d26133c04254cfd2cc0d5dab29fcd498e35d46","src/serde/mod.rs":"cd1791b1071eb2b43c2fef0146b8c8cf68c1d2bd854c729de611b32c60703e08","src/serde/rfc2822.rs":"915284e0ce8878ea89758ce60b8085df8012a98757db4ab27f4876bc223c830d","src/serde/rfc3339.rs":"075e33f968476980931e60a23a5f96dab8942cba6dfe24b05c1e6f6a386e097d","src/serde/timestamp/microseconds.rs":"1995559b1b45059639be28e753003d33d50329401eaf340e05279efe939e33fa","src/serde/timestamp/milliseconds.rs":"28ed29e24e1a3c46efabb70f40049f1116cb2e6a6203c72c03950a06ea21a44d","src/serde/timestamp/milliseconds_i64.rs":"d8d000427559ec6991793921a0d29ca7dfdd615bdf06c9a73cb0058a65b423d3","src/serde/timestamp/mod.rs":"5f6e7d9e9ced37148659d788c043c82adf1e4698d7b3069b0b54aedea873404a","src/serde/timestamp/nanoseconds.rs":"644d047b6a5f9c377a80795d53447b6f47dc25d62646b309ccd5b12e78d66a8e","src/serde/visitor.rs":"329e770f95e46df2e69f50fe67549fed48984a3ad701b1a3d2707565d60a76b5","src/sys/local_offset_at/imp.rs":"66574bb79607617de39ab83f6e04b96f4baac0931533cd84ffbc108b62885b6a","src/sys/local_offset_at/mod.rs":"f5b9e1aeef106cf908f54d0efa0a4c68bb54e70bde40b80e1fc3d24bc455d6de","src/sys/local_offset_at/unix.rs":"f514dc3cc88a3f6469aa6716c5b716c1a0bc0309706d9cb5398d6f72685f263c","src/sys/local_offset_at/wasm_js.rs":"a15527d0cb1b48c984a925ffb074bff0f1790cf41385dfab616ea734afa6568b","src/sys/local_offset_at/windows.rs":"59a0580f3863eb36857a58f67fa236e303fefea25946aa6c663bffa75dedb32c","src/sys/mod.rs":"5e5649775aff43afa68d3ba0ca193273fd412e2de50e532828d7de65a1327f44","src/sys/refresh_tz/imp.rs":"b0940bd255367fb9b07dfd0f531da46fd744bd852ea2d5cfcde006801eaf1e2f","src/sys/refresh_tz/mod.rs":"9e332411d53b14b08ad0ce865eadc607197c31b85718fae50a826cb8b12b8bcd","src/sys/refresh_tz/unix.rs":"f00f446c18ef2befdcf00d8ac2f3da5200dd8aea4682ce5bcdb243e7982593d1","src/tests.rs":"b08345408bd091f4dbdc78f734a5ec0185b784f028107bc267ac31b56dfe1dea","src/time.rs":"393150317c778cf631a2760026e4dfbe89a36c216d4381dad624a19c39955da6","src/utc_date_time.rs":"1bff1ab2f0cd66ef11d64c39157adc405ed65378007ddfb805677fda72b8b773","src/utc_offset.rs":"989c98cd5638757df813a3dc970cd7c938300dee7300428509d45a6116d5b88a","src/util.rs":"477ebc22ffc147a7d268b6769cbda1b45ca28f2737e6d6efa062d5538024d849","src/weekday.rs":"84b5285df8b15b236dcd3899229e6355d5e6f19f81143f29734680f27da6b668"},"package":"91e7d9e3bb61134e77bde20dd4825b97c010155709965fedf0f49bb138e52a9d"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"52ddc75e025e5e488ee5634022e9424f78498b538ca669c722c8d999bcd8e020","Cargo.lock":"f4c01877ac65df3b97bc9006c1ba0f28795d734492e8109adb4620deb2103461","Cargo.toml":"cc10e8f4bdbda88efd94e5df3636c909a12df9780d198e41b75acab3ba25045a","Cargo.toml.orig":"68f252666cc75beb9f5df0da8c6045909d59f4d69c0da11d1108fd2552fa550e","LICENSE-Apache":"0d542e0c8804e39aa7f37eb00da5a762149dc682d7829451287e11b938e94594","LICENSE-MIT":"2537228d9a1b44a5dc595241349cae7090b326c8de165aaf89bfddef4a00d0fc","README.md":"0a55c228b30c4e7ea7e2d8eee09f6524bc19b6cee63d3b571faf2f1332526750","benchmarks/date.rs":"bd7d3c4549eb24435ff61057b95d2717f4f3b44ae7e2f10157146216d3658e9c","benchmarks/duration.rs":"c6458c61f55e848589e9ae0adaf4880985298f7c99142a9501a2cda1e65f7c67","benchmarks/formatting.rs":"437567a71243c0da15a4fd62c94ab3203cf1236645380180f01354471ea28012","benchmarks/instant.rs":"e8e2f6f7adfe9ee0cc62a09a0b5b0e7eee2d15e403351a4d858d0462130d4d6f","benchmarks/main.rs":"651f0a1899302dfc3712dcedb032ba29bdfe9110589ec1043418cdd01cd593ea","benchmarks/month.rs":"648f59ecadbfbd6c31182261e907ff77b3916bdae739c70638f3cdf52fcaff70","benchmarks/offset_date_time.rs":"8980c2ab7ebc46c6931975e6bb242ab18ac497e76748ff5bf68a301aad01f5c3","benchmarks/parse_format_description.rs":"6eccc4afda79ec20e91c938ad777729b55716272ef2a5b039279b34ce0f87a73","benchmarks/parsing.rs":"9c7135125e98107f43ac8e01ca650775f95f0b8e8cbabb5cafdf22a7aef5ad4a","benchmarks/plain_date_time.rs":"68ac0e3d9f89e296a516ea04778664d447689b8da4623226ed1a422479bbaac0","benchmarks/rand08.rs":"4f3bac80a5e29fbd3412c8e09ad04671195dd4aa78ebe5fd7dd63f90084e58d1","benchmarks/rand09.rs":"2187e9fe04d5511d531596c64ebfb7940734592520f63de68a3baaf6f5fd0a46","benchmarks/time.rs":"b4cae6c2700eac1f03bdd18cc55d8c6c56325b98036de6746466fdd89d1dfdec","benchmarks/utc_date_time.rs":"038673d26a852dee15df94c08c1c8a3a63c916728704862a865e66424ecaa87a","benchmarks/utc_offset.rs":"9eb288e0334ed4678a3d76c845606b017ff6dbd96644db1dbb12cec5c44c69df","benchmarks/util.rs":"e885fc3f50af9efde78bb80f5b48f6c7b77cee11564433c84957b9af44ab25f5","benchmarks/weekday.rs":"b7cf85cc69af3b891d78803f2862e7b18b674b1d3e27c139f830f41be689ffe9","src/date.rs":"c3e06960b197e37ef3c665a4ea0b81f0666763ac525cff3d9fa7eec8924ade7d","src/error/component_range.rs":"8a5f8bd2335e0827b1ccd9937b0fc3b12cbbc6d9577387e918f73af3d7e48063","src/error/conversion_range.rs":"b5f436fda3c3fc238f2e94fbbb4c27ff583f74a650b600845b7be2dc78cd3d88","src/error/different_variant.rs":"f790e3e7a81dee90ea5142b18562af3ea0d0541737fa477d6170dc3d2dfbeeb3","src/error/format.rs":"f0db80eede80afb366f471dbc3c4f663b51daf3734a7f11bb9ba8e8fadf8cd34","src/error/indeterminate_offset.rs":"668737c953d9a53f275d07f1628c13f32e416055fb53a7c36f9093a1f6e4665f","src/error/invalid_format_description.rs":"0f4435c286d5054820c8e15adee833a87205f1907edd8e0b472aec3ff633fdf7","src/error/invalid_variant.rs":"4e471e88ff7db4319d49a00fd3c7078b366bb2eef40bcdfa75e6fd8d145d449b","src/error/mod.rs":"d56970e05086af93156b4daf262c2ace04e773c8ba037e5cab1d4e894e5ca817","src/error/parse.rs":"14efda450fb37c06de9ea4d88849433d21d3003e127ef48abf6ec2da773973ae","src/error/parse_from_description.rs":"f20b165557b49ecc76e929473104f2e3c5a5b296637765ebd133be5ae56d2cd9","src/error/try_from_parsed.rs":"30474fc2c707471bcfbd314a098b15dfd7c009af85f67a845f669e4dfa69d23f","src/ext/digit_count.rs":"0c6a8f1bdf1594698e393ad840c08291c82911ee28e24fc6e09cb9eeacc0dc6c","src/ext/instant.rs":"ac5fb5c14c0717ff88f9c092a7274ed6d6e62a68f857f2bd0e5293ac844f6afa","src/ext/mod.rs":"75035e71d192eaf7a19238d55eca8b4344bb81183f5b9dae0b5abd777941e28f","src/ext/numerical_duration.rs":"ff2ec5d3c5c2d1a088a2a131b5a4390d53d40a8890801f76e3d81f2feca35ff6","src/ext/numerical_std_duration.rs":"ce9951a876c750a106b675a21db8281afed28e830c7f3e3a86dcf1d46b4809b4","src/ext/systemtime.rs":"2f296eb8b21b6c53d8697c94900b6492a671ad4f5c0ed9aea21cfdf7f0841c3d","src/format_description/borrowed_format_item.rs":"43e38779f89012add57b75d18614fbf4d71b91a9d50d478ed3fb3468054d4e11","src/format_description/component.rs":"5ea41d58d2ca162a0e63d512772baeeb89bb77bea5002234eea376cef74b1686","src/format_description/format_description_v3.rs":"9af5aafe12718ef0838bcacf82671059e74ea743502d116a717336633369bd13","src/format_description/mod.rs":"c8009a1fb6833bc16f3245c8342fdb8922ed69b0c440939117f8d58ca3658e99","src/format_description/modifier.rs":"2f37659e8b947208070f4b13e1bdec688ca5faa1be093830b0c48a14af02b4d1","src/format_description/owned_format_item.rs":"5758a3bc60683b977bacf7958fd87d86ae9fbe8e67c7d2c359fad8ee12e340b2","src/format_description/parse/format_item.rs":"2e634774d5ae82234caa0776aa8e3c021b200980909b2e7beb88e01c48dbaaa4","src/format_description/parse/lexer_ast.rs":"141d2090390bef8812b35358d44f78ce63ccc5562977acbe0e919ed25c698aec","src/format_description/parse/mod.rs":"7282ac6c41a1617826d052be277469a9278b14c13dd897317997bfc15c278b55","src/format_description/parse/strftime.rs":"bac2e03b1265a8b6978370c3dd8212a8600120a6e8e0bcf484acdcb14f70c392","src/format_description/well_known/iso8601.rs":"6c51777c274ba6fe2c6820c17cbf90eb976cf1066fa541fe809de775553397f9","src/format_description/well_known/iso8601/adt_hack.rs":"2f62bdeccf0ba4cdbeb69f6b55be56cb1084565bc4889d6f48140c8e1bc034de","src/format_description/well_known/rfc2822.rs":"36c23394724ae12250d4193cab26887a6ff8f82ca441ea6b0d03c4f1c928b3dd","src/format_description/well_known/rfc3339.rs":"1a6318dffd3ebb6ac7cf96eae3d9b1eb44b1089cf4284fa6a7e935c6fcf1b43c","src/formatting/component_provider.rs":"ee8b1f9157ad4bdd513b9becb6742e5e3455338ddaa0b090d42628b79cfcfc45","src/formatting/formattable.rs":"22fa0ce6d4179fce94b0c70967012487dab000a4e6e4d5a05039d7bb098857f3","src/formatting/iso8601.rs":"cd99683afafe2b74905375e73560ecefc34fee1fe724aaf73e5e7c722d3304c6","src/formatting/metadata.rs":"94a3a717d7c3dce5618819988aa4f0cb84b3984a230dba0b5eb6695f66ace0ef","src/formatting/mod.rs":"7ef8ecc802aab5fdd75b85b08d48bdc72b646b3e3ce1253d64e923eef5b60b0a","src/hint.rs":"ca02b549ec40bed70b147ebd9e2f3d777726bebe5e5d6463481ffd0f51ee4c2e","src/instant.rs":"6d93db53036124b4e23b39e6f45390c2222104fa30850b59e40f6712b4ce7b8c","src/internal_macros.rs":"c79d7b59e10bd049f79d2835f10222b9a19b26dd8e7dd3e4a4399eea997f6eeb","src/interop/js_sys_date_offsetdatetime.rs":"6c67284682fb58c8cac2dfa17cba10a59286c6351e614249d2a7ee00b9ee8c40","src/interop/js_sys_date_timestamp.rs":"a7e91ca360702f08b6c4e32787b67972198ea71a66f64e17bbcda943b3cd6773","src/interop/js_sys_date_utcdatetime.rs":"1db54a6faf4a38e13ec13839caaad8a955ab5474160d2d30598010ac68ba7a4a","src/interop/mod.rs":"0538f60928971b84b6950e77fcf2d1aca8a083617fec23b2b1e42d0a93709c0c","src/interop/offsetdatetime_systemtime.rs":"c685b38311d8bc6281b0522b333bdcbdc57b711e962596c83e2e92bf5dc5e406","src/interop/offsetdatetime_timestamp.rs":"1a851ba5d02af121fb9e32fe0801763d5b02b3d53d376ac8647c1f56a2152afe","src/interop/offsetdatetime_utcdatetime.rs":"fbabea738a735c8a85b2982a784c07aedbd2f921e76fd4bfa83ed12641e6525d","src/interop/systemdatetime_timestamp.rs":"03fb0bd8ec7e3bc59b51355a20bd93cbac1ca454ed87ba8c5a26b230797de316","src/interop/timestamp_utcdatetime.rs":"001707abf60ad92eb48dbb7c839e9e7e25c493fe5165d42bf9cb2abdf2836a78","src/interop/utcdatetime_systemtime.rs":"8e6f3a0d514d4b511e37fa55d67e2d485e89f6ab75e8f402451bbd314acfa90c","src/iter/date_iter.rs":"5699a02371b73f23620d3b5b0ab532027f209d2a8e78b81e6f7c1f0e51636037","src/iter/mod.rs":"741261cefb6b5ca0a52bc5de752bd301c587ac58ce8db3686b4ffc451ae3a827","src/iter/month_iter.rs":"52427775930ee96769b93034aec6183582d30f40351f28131fbc9e5678f56bd4","src/iter/weekday_iter.rs":"6d7275de078d0165d218af8da0f978b595302bae9991563e0a69e2f9f78023b4","src/lib.rs":"7384fe58915202075652a2a4b2fc7a72ebef86a5e793347b4f0f3ad1ebbe50a9","src/macros.rs":"d66414d2e608380771a229ea4f3fc6553cfa9b958ef6c35a8b6a8bf6832f6871","src/month.rs":"39355a037cb9591260b555505a40fb17040e81e6939681c14236a7d8ee90216b","src/num_fmt.rs":"ae104904123fea377ebb69d3a55b5f2bb48ba4cf8930b859a5d64130c627e962","src/offset_date_time.rs":"5b13397177adf6599a9ac328bec8085b029fccf892ab7ea3a14ece9d5a2ea951","src/parsing/combinator/mod.rs":"4595c3aff7f94959d74068bc631426b4bf9cd31054c1c12a04015ba454c4c8e7","src/parsing/combinator/rfc/iso8601.rs":"90272dd57c6a30881bca3e4e6106ab0f9c63f75a6886dee4c8e0d4e063e4b9c6","src/parsing/combinator/rfc/mod.rs":"f30b75d248f5ae92c27646d504703f5489185afb76c998cc4375437b3d15c822","src/parsing/combinator/rfc/rfc2234.rs":"229cf74e6e9ac31d69e33938e2847fdee8ae5940d90a7ac5e1ccf3726723afb1","src/parsing/combinator/rfc/rfc2822.rs":"07bb62298dcd3cafc81396d83f342323a7742d0c6fad55957eda1b9252cf024d","src/parsing/component.rs":"98fcba44876551d6e2ecb9f340e37632200e7ab6d52cbee9efd557b4b57f4fbb","src/parsing/iso8601.rs":"8acaad6159e46b9fa1882626fcd69ae4841ce4e2b4df04a1030f5c35b43e7beb","src/parsing/mod.rs":"4374cb14af00dc6dc85eaa24b1c579b6f9f5118d47716e6c6f23fb1c2280b6fa","src/parsing/parsable.rs":"c778bfee29de629a58300d63d4a3426b71aa06f2bd719b6ceff5a2d9d66f98d9","src/parsing/parsed.rs":"b725513b9206f0b937e2a0d4fc9278f4799246525377b71aca1619961e8c40ac","src/parsing/shim.rs":"825b9ca3833367f33f9d12092e04b88b3cfde214569222b120d74146364a7a3f","src/plain_date_time.rs":"8d1b9cb21edd09ea6788bc99efaad05aa87fac04f6849bf7d67acf1a97305879","src/quickcheck.rs":"25a9369aa9447709ea588b0ef71fdaddad83a14f190838641a015e835595f096","src/rand010.rs":"b38ea48c3679f25a5c2b5067505f6490906ff4bc21c022a263c0ff33068ccab9","src/rand08.rs":"8ce1fff4d166f564956fb7da12c59a8269de3b2fcccb616ad7c517d42fe9c2f9","src/rand09.rs":"d6661f9e377983494f8cfb68ed9356ed908312ea169b803037fd8160053c665f","src/serde/iso8601.rs":"3af78141e555af579727d1c2581b8383a5f6edbfda79ba5edcc4185269fb1285","src/serde/mod.rs":"6cc8450c983b11e5b2ae4419b11ef750c0fcc10159eaf2760df6d4709700ffad","src/serde/rfc2822.rs":"57d66cc4c45fd183589d035c0ebd6150616bfc7abdd491191ed07cffba113fa1","src/serde/rfc3339.rs":"9ea941c156033c327f857c62944a067b24d7d46ce866d751a6025f18e0cd811c","src/serde/timestamp/microseconds.rs":"77f293ad60f593126446ebf4f5d0eaecb043173137ac45270aaf771e2aa49b81","src/serde/timestamp/milliseconds.rs":"e33de22f0e78b65aa2dd2e339f84b17f4877247ddae9bbe37368b0527ae1d8d4","src/serde/timestamp/milliseconds_i64.rs":"933f2b1fa81a7f45bbd27a00689771f452dfa02b8a3333efa009e18d3c6b9de0","src/serde/timestamp/mod.rs":"1914557f35d81df063ae9b931a7d63541449bf45095ccd17857e0092d49a6c67","src/serde/timestamp/nanoseconds.rs":"5cf313c9e49eb50ca360f5354e6ff69836b9292469f0946f454748ef7e2ba70b","src/serde/visitor.rs":"e330e02d3856be96589b1f8f260a3ccb49de1e5fc7a3566f5fe06f6e66180343","src/signed_duration.rs":"8b63e5a85f81c20ecd4f101d1501bb9829d13b1869fde2eacc38b43113a982e6","src/sys/local_offset_at/imp.rs":"66574bb79607617de39ab83f6e04b96f4baac0931533cd84ffbc108b62885b6a","src/sys/local_offset_at/mod.rs":"f5b9e1aeef106cf908f54d0efa0a4c68bb54e70bde40b80e1fc3d24bc455d6de","src/sys/local_offset_at/unix.rs":"f514dc3cc88a3f6469aa6716c5b716c1a0bc0309706d9cb5398d6f72685f263c","src/sys/local_offset_at/wasm_js.rs":"8f96923afe2773c40c4bf0dc9cc72b3b276551b023a78c8b15c6ad68370d2416","src/sys/local_offset_at/windows.rs":"653de160770d37457472d8155a98144b0d1bb320cc3acfc4c7aff1559a576b69","src/sys/mod.rs":"5e5649775aff43afa68d3ba0ca193273fd412e2de50e532828d7de65a1327f44","src/sys/refresh_tz/imp.rs":"b0940bd255367fb9b07dfd0f531da46fd744bd852ea2d5cfcde006801eaf1e2f","src/sys/refresh_tz/mod.rs":"9e332411d53b14b08ad0ce865eadc607197c31b85718fae50a826cb8b12b8bcd","src/sys/refresh_tz/unix.rs":"bc8825647167244e81a63ed2be68d8e24a719ea11866973b6693f164b65d8f1c","src/tests.rs":"ad3c0929b5c36aaa4cf4ac9b950b368dde8a9d23d8caf1ac4e3037d1f586b173","src/time.rs":"0313c102ef25fe1e878830483f0a9ed1b6822ebd666a53c1ffdf84c66d110fb3","src/timestamp.rs":"76606776b10c80d09888cd7e7669637bc5a1d28ff32e21bf1529699782ed098e","src/utc_date_time.rs":"1eab27ee62167d7e0fc955b1d7391b15be4100c05daca947f40ddaf63e08aafe","src/utc_offset.rs":"e22ddd0113f5e47f6fcf2308ff8d5570f4f1e2563228608917d20222733fac27","src/util.rs":"2c09eec138af9628bb082951cc853408389f456fd4441145927c28f4caa75a3a","src/weekday.rs":"3c9237dd802c2696d0666bb71bb1f74ed294ce0f85b7e0e5c808f178a9800210","tests/integration/compile-fail/invalid_date.rs":"2e8b5513edf2c77914868b72b62e992ef6b7b064f3f2e109f094ed4ec0a77639","tests/integration/compile-fail/invalid_date.stderr":"cf328bcda9512974171f12a1c30481de2150d6e208e41a815dce1f6d3642f864","tests/integration/compile-fail/invalid_datetime.rs":"4442fde89f36a618420b590d361de2ce79f872f343b896b1102687df26465b71","tests/integration/compile-fail/invalid_datetime.stderr":"c6dabb4e2a4d76618b0361d1b5e260b794c82360f2b463fd172171dc7b7d458a","tests/integration/compile-fail/invalid_format_description.rs":"f33fa8ce4ef1e658297476cd5aa1bf572be1d817f04d3a5f86c7bccc7c85e788","tests/integration/compile-fail/invalid_format_description.stderr":"246c682dab859895067bf8ac289284ba9676371f2bf72716ce397026af02ae83","tests/integration/compile-fail/invalid_offset.rs":"3990fd0969032585dc3e4da75d9671af08281f4c9413acdf08cb56cb6ea06529","tests/integration/compile-fail/invalid_offset.stderr":"daa62d8e34426cdd74a74afb591a6fff9a3ff260ba9fbfc4d15b3b77e977ebd5","tests/integration/compile-fail/invalid_serializer.rs":"bcf1b1a590663962e2ffc837d31bd742522078c9e347e67bd8587a41bd97c53e","tests/integration/compile-fail/invalid_serializer.stderr":"065a4c0aefc0935ae62036551a51511a76565d00017aa69f8d9a4f04a9bc1c2d","tests/integration/compile-fail/invalid_time.rs":"feed0988a77c804b8456f95927ef1e9fa94ad356c2deab3d0da7142edeb778cb","tests/integration/compile-fail/invalid_time.stderr":"578760c2bff1bc7cb9fb1219f09f2ae15a0344151ad9fef6ce5d4c2ed13a5b8e","tests/integration/compile-fail/invalid_utc_datetime.rs":"1d9c1acc56d674971850af01240501b32fae367a371a28fce0c973f39f965ecb","tests/integration/compile-fail/invalid_utc_datetime.stderr":"d488c339a95d224ea6fb847b5096921714aeeb4e3677605379cbaa03ac2b7e80","tests/integration/convert.rs":"54fb0629726183b5f4e10c9e8cd004c4c15c60962db8bae56458821d3d29dfd3","tests/integration/date.rs":"7dedc87758c7bde14d7e1226be7a3a437c6d5df3c5dce369f84a5a5090b7e1e2","tests/integration/date_iter.rs":"80887e3445d1d8a95e35f02b9502e9ba40d1a78979179c1b11f77e94ee592897","tests/integration/derives.rs":"01c9af79eb8af64694e0986e938ae4177f711d0fd4d46bf0aab6b1e7d48349d6","tests/integration/duration.rs":"c2579f33d6c8e3f389cf1253b673a5d3bac114b25dd848a873efdb200f5983a7","tests/integration/error.rs":"e767edea524c4ff1b2456a700e865136b63deb8752f8df103b8387b646fbbf69","tests/integration/ext.rs":"fb00dcd94736ccd655fbe0a49f81d386223ce154c76e9010e03c38794ca8cf36","tests/integration/format_description.rs":"d7b6743b2ad1fc7ede5f87a0c2803b1e5892699f672451984aa1026f50484818","tests/integration/formatting.rs":"e39a54516ef6c83752e6ca440cb7da0d5aa2151bb3eae938f1c8297ad0c38060","tests/integration/instant.rs":"bf7e1bcfd44bb22756bc45324b2db31359632509803623e83e1515d946e50920","tests/integration/macros.rs":"efab8ff7f4419e2e9aeb06109d2daf3f143ddf420f8ec5de01edef2c73115236","tests/integration/main.rs":"a618fbc5a7157dfe6a3c377c810e193775c85a37d57bc9bf41cbbbc9490b164a","tests/integration/meta.rs":"432a1e4c497fe1c8a53f3b270184bfcda1c63867a59504f37a6e3e7e1f9ea97e","tests/integration/month.rs":"3081f638846858b35edda46edae2b18e4d2b782d0f08565858542876edf96d86","tests/integration/month_iter.rs":"ab75547211ad5b233eefaf0e9ba773acc6057091aeb900b91a5cfff508f4a407","tests/integration/offset_date_time.rs":"978b90138be6ba400ac4bf0b53121d3d899cdf80db4822b158736c499c9e6922","tests/integration/parse_format_description.rs":"7be495529c3d412407c8192658cea402287f5edd0ce4df14b25a74199c1df32a","tests/integration/parsed.rs":"ada3da88f5337ebd5489a3d274c11edfb651f5e2e00aaaf61b77be249e532e5a","tests/integration/parsing.rs":"7e6d36e9c2bb82a1be0f110d3252858c0d7690ed432d89ce1588650787f3b0ac","tests/integration/plain_date_time.rs":"f11b9789b23d35e2b866de3afdc3ec85ac20883529b96d5cf85e58de102246d0","tests/integration/quickcheck.rs":"93a8a092358c1ba5827b6074fa2f78f7a44e1e2aae74e9e2e7c3c0f0e2c0b732","tests/integration/rand.rs":"bc16d077f36c551503bb15e5f6b8444cd5d193e5f96477daf3f16c1da50377fe","tests/integration/serde/error_conditions.rs":"364d0130034a77c4d50d87f4f519eac0009fbc23b23e21836722e6fd02dec2d8","tests/integration/serde/iso8601.rs":"4122cd9aa1d62c0e37d036082663b12a3a36c9be3acbd63746c9d6533a563cf6","tests/integration/serde/json.rs":"46bf4c2191fefebd7fc39f6b75e4fddb4b33597ac7916c9bf5593f91180326fb","tests/integration/serde/macros.rs":"9d0afa8cd1843bfa759eda239d7f7040a13188ad46855cb035c6067078452fed","tests/integration/serde/mod.rs":"d7a3ab04c2a81adb7f5903e4f3dd4ff37384f19c1c0e5dd0e40e00b20669d477","tests/integration/serde/rfc2822.rs":"cf9f222b18dfd2c159c60e32369e376b106687565fcdc092f4fafef74ceae341","tests/integration/serde/rfc3339.rs":"25da009aff5993122e3aa4acca37ee805ccdb4c4cc08673868f72726d879def6","tests/integration/serde/timestamps.rs":"128f4cdcefd66f1063512acde616d88c78bc7a43c009d0319d384fd8a8438ddd","tests/integration/serde_helpers.rs":"3be6b1a11408d753a564b7fd50d5b6cc5e94c8067f599c6910e8afdea3a263e5","tests/integration/time.rs":"4c1b8ffec0a0de06ec9d7b1dd16ad443a41a891a5f07a5883dc8b7f929c837ed","tests/integration/timestamp.rs":"630500c962ccbc970bcc67f8dc8f50d3d5af514a953b3997e4f466d6716ff1fa","tests/integration/utc_date_time.rs":"4746560566b06aa564459cd1a9a7575f539beae41780253b96e60c69d304a1e4","tests/integration/utc_offset.rs":"42b7c959732c32554c8f567c718b997a2c40d01b03b910bf575be34f575c8c1a","tests/integration/util.rs":"bdba98f42ac166f4a21d293f97107b35b0902e3ccdd67e5d7c6ce4d76d810901","tests/integration/weekday.rs":"dae38db84b1fe05deece0173717c0d71972a01194a5f6d66054427fda43dfe35","tests/integration/weekday_iter.rs":"cfa5d0beafd6c182c5c3a8129a07991953084c391e483b95edeeb6728804f362"},"package":"cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134"}
\ No newline at end of file
### external/vendor/time/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "04c0ef283828e25a0c7fc270f28c053ceb26afcf"
+ "sha1": "857d9c404c5b6f6cb64d1bfa604c695be3369e12"
},
"path_in_vcs": "time"
}
\ No newline at end of file
### external/vendor/time/Cargo.lock
@@ -1,16 +1,25 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
-version = 3
+version = 4
[[package]]
name = "aho-corasick"
-version = "1.1.2"
+version = "1.1.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b2969dcb958b36655471fc61f7e416fa76033bdd4bfed0678d8fee1e2d07a1f0"
+checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
dependencies = [
"memchr",
]
+[[package]]
+name = "alloca"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e5a7d05ea6aea7e9e64d25b9156ba2fee3fdd659e34e41063cd2fc7cd020d7f4"
+dependencies = [
+ "cc",
+]
+
[[package]]
name = "anes"
version = "0.1.6"
@@ -19,39 +28,55 @@ checksum = "4b46cbb362ab8752921c97e041f5e366ee6297bd428a31275b9fcf1e380f7299"
[[package]]
name = "anstyle"
-version = "1.0.4"
+version = "1.0.13"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7079075b41f533b8c61d2a4d073c4676e1f8b249ff94a393b0595db304e0dd87"
+checksum = "5192cca8006f1fd4f7237516f40fa183bb07f8fbdfedaa0036de5ea9b0b45e78"
+
+[[package]]
+name = "anyhow"
+version = "1.0.101"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f0e0fee31ef5ed1ba1316088939cea399010ed7731dba877ed44aeb407a75ea"
[[package]]
name = "autocfg"
-version = "1.1.0"
+version = "1.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d468802bab17cbc0cc575e9b053f41e72aa36bfa6b7f55e3529ffa43161b97fa"
+checksum = "c08606f8c3cbf4ce6ec8e28fb0014a2c086708fe954eaa885384a6165172e7e8"
[[package]]
name = "bitflags"
-version = "2.4.2"
+version = "2.10.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ed570934406eb16438a4e976b1b4500774099c13b8cb96eec99f620f05090ddf"
+checksum = "812e12b5285cc515a9c72a5c1d3b6d46a19dac5acfef5265968c166106e31dd3"
[[package]]
name = "bumpalo"
-version = "3.14.0"
+version = "3.19.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7f30e7476521f6f8af1a1c4c0b8cc94f0bee37d91763d0ca2665f299b6cd8aec"
+checksum = "5dd9dc738b7a8311c7ade152424974d8115f2cdad61e8dab8dac9f2362298510"
[[package]]
name = "cast"
version = "0.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "37b2a672a2cb129a2e41c10b1224bb368f9f37a2b16b612598138befd7b37eb5"
+[[package]]
+name = "cc"
+version = "1.2.55"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b26a0954ae34af09b50f0de26458fa95369a0d478d8236d3f93082b219bd29"
+dependencies = [
+ "find-msvc-tools",
+ "shlex",
+]
+
[[package]]
name = "cfg-if"
-version = "1.0.0"
+version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
[[package]]
name = "ciborium"
@@ -82,247 +107,280 @@ dependencies = [
[[package]]
name = "clap"
-version = "4.4.18"
+version = "4.5.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1e578d6ec4194633722ccf9544794b71b1385c3c027efe0c55db226fc880865c"
+checksum = "6899ea499e3fb9305a65d5ebf6e3d2248c5fab291f300ad0a704fbe142eae31a"
dependencies = [
"clap_builder",
]
[[package]]
name = "clap_builder"
-version = "4.4.18"
+version = "4.5.57"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4df4df40ec50c46000231c914968278b1eb05098cf8f1b3a518a95030e71d1c7"
+checksum = "7b12c8b680195a62a8364d16b8447b01b6c2c8f9aaf68bee653be34d4245e238"
dependencies = [
"anstyle",
"clap_lex",
]
[[package]]
name = "clap_lex"
-version = "0.6.0"
+version = "0.7.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "702fc72eb24e5a1e48ce58027a675bc24edd52096d5397d4aea7c6dd9eca0bd1"
+checksum = "c3e64b0cc0439b12df2fa678eae89a1c56a529fd067a9115f7827f1fffd22b32"
[[package]]
name = "criterion"
-version = "0.5.1"
+version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f2b12d017a929603d80db1831cd3a24082f8137ce19c69e6447f54f5fc8d692f"
+checksum = "950046b2aa2492f9a536f5f4f9a3de7b9e2476e575e05bd6c333371add4d98f3"
dependencies = [
+ "alloca",
"anes",
"cast",
"ciborium",
"clap",
"criterion-plot",
- "is-terminal",
"itertools",
"num-traits",
- "once_cell",
"oorandom",
+ "page_size",
"regex",
"serde",
- "serde_derive",
"serde_json",
"tinytemplate",
"walkdir",
]
[[package]]
name = "criterion-plot"
-version = "0.5.0"
+version = "0.8.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6b50826342786a51a89e2da3a28f1c32b06e387201bc2d19791f622c673706b1"
+checksum = "d8d80a2f4f5b554395e47b5d8305bc3d27813bacb73493eb1001e8f76dae29ea"
dependencies = [
"cast",
"itertools",
]
[[package]]
name = "crunchy"
-version = "0.2.2"
+version = "0.2.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "7a81dae078cea95a014a339291cec439d2f232ebe854a9d672b796c6afafa9b7"
+checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5"
[[package]]
name = "deranged"
-version = "0.5.2"
+version = "0.5.8"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "75d7cc94194b4dd0fa12845ef8c911101b7f37633cda14997a6e82099aa0b693"
+checksum = "7cd812cc2bc1d69d4764bd80df88b4317eaef9e773c75226407d9bc0876b211c"
dependencies = [
- "powerfmt",
"quickcheck",
- "rand 0.8.5",
- "rand 0.9.2",
- "serde",
+ "rand 0.10.1",
+ "rand 0.8.6",
+ "rand 0.9.4",
+ "serde_core",
]
[[package]]
name = "either"
-version = "1.9.0"
+version = "1.15.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a26ae43d7bcc3b814de94796a5e736d4029efb0ee900c12e2d54c993ad1a1e07"
+checksum = "48c757948c5ede0e46177b7add2e67155f70e33c07fea8284df6576da70b3719"
[[package]]
name = "equivalent"
-version = "1.0.1"
+version = "1.0.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
+
+[[package]]
+name = "find-msvc-tools"
+version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5"
+checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
[[package]]
-name = "errno"
-version = "0.3.8"
+name = "foldhash"
+version = "0.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a258e46cdc063eb8519c00b9fc845fc47bcfca4130e2f08e88665ceda8474245"
+checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.2.17"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
dependencies = [
+ "cfg-if",
"libc",
- "windows-sys",
+ "wasi",
]
[[package]]
name = "getrandom"
-version = "0.2.12"
+version = "0.4.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "190092ea657667030ac6a35e305e62fc4dd69fd98ac98631e5d3a2b1575a12b5"
+checksum = "139ef39800118c7683f2fd3c98c1b23c09ae076556b435f8e9064ae108aaeeec"
dependencies = [
"cfg-if",
"libc",
- "wasi",
+ "r-efi",
+ "rand_core 0.10.0",
+ "wasip2",
+ "wasip3",
]
[[package]]
name = "glob"
-version = "0.3.1"
+version = "0.3.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b"
+checksum = "0cc23270f6e1808e30a928bdc84dea0b9b4136a8bc82338574f23baf47bbd280"
[[package]]
name = "half"
-version = "2.3.1"
+version = "2.7.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bc52e53916c08643f1b56ec082790d1e86a32e58dc5268f897f313fbae7b4872"
+checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b"
dependencies = [
"cfg-if",
"crunchy",
+ "zerocopy",
+]
+
+[[package]]
+name = "hashbrown"
+version = "0.15.5"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
+dependencies = [
+ "foldhash",
]
[[package]]
name = "hashbrown"
-version = "0.15.2"
+version = "0.16.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bf151400ff0baff5465007dd2f3e717f3fe502074ca563069ce3a6629d07b289"
+checksum = "841d1cc9bed7f9236f321df977030373f4a4163ae1a7dbfe1a51a2c1a51d9100"
[[package]]
-name = "hermit-abi"
-version = "0.3.4"
+name = "heck"
+version = "0.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5d3d0e0f38255e7fa3cf31335b3a56f05febd18025f4db5ef7a0cfb4f8da651f"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
[[package]]
-name = "indexmap"
-version = "2.7.1"
+name = "id-arena"
+version = "2.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8c9c992b02b5b4c94ea26e32fe5bccb7aa7d9f390ab5c1221ff895bc7ea8b652"
-dependencies = [
- "equivalent",
- "hashbrown",
-]
+checksum = "3d3067d79b975e8844ca9eb072e16b31c3c1c36928edf9c6789548c524d0d954"
[[package]]
-name = "is-terminal"
-version = "0.4.10"
+name = "indexmap"
+version = "2.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0bad00257d07be169d870ab665980b06cdb366d792ad690bf2e76876dc503455"
+checksum = "7714e70437a7dc3ac8eb7e6f8df75fd8eb422675fc7678aff7364301092b1017"
dependencies = [
- "hermit-abi",
- "rustix",
- "windows-sys",
+ "equivalent",
+ "hashbrown 0.16.1",
+ "serde",
+ "serde_core",
]
[[package]]
name = "itertools"
-version = "0.10.5"
+version = "0.13.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
+checksum = "413ee7dfc52ee1a4949ceeb7dbc8a33f2d6c088194d9f922fb8318faf1f01186"
dependencies = [
"either",
]
[[package]]
name = "itoa"
-version = "1.0.14"
+version = "1.0.17"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d75a2a4b1b190afb6f5425f10f6a8f959d2ea0b9c2b1d79553551850539e4674"
+checksum = "92ecc6618181def0457392ccd0ee51198e065e016d1d527a7ac1b6dc7c1f09d2"
[[package]]
name = "js-sys"
-version = "0.3.67"
+version = "0.3.85"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9a1d36f1235bc969acba30b7f5990b864423a6068a10f7c90ae8f0112e3a59d1"
+checksum = "8c942ebf8e95485ca0d52d97da7c5a2c387d0e7f0ba4c35e93bfcaee045955b3"
dependencies = [
+ "once_cell",
"wasm-bindgen",
]
[[package]]
-name = "libc"
-version = "0.2.152"
+name = "leb128fmt"
+version = "0.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "13e3bf6590cbc649f4d1a3eefc9d5d6eb746f5200ffb04e5e142700b8faa56e7"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
[[package]]
-name = "linux-raw-sys"
-version = "0.4.13"
+name = "libc"
+version = "0.2.182"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "01cda141df6706de531b6c46c3a33ecca755538219bd484262fa09410c13539c"
+checksum = "6800badb6cb2082ffd7b6a67e6125bb39f18782f793520caee8cb8846be06112"
[[package]]
name = "log"
-version = "0.4.20"
+version = "0.4.29"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b5e6163cb8c49088c2c36f57875e58ccd8c87c7427f7fbd50ea6710b2f3f2e8f"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
[[package]]
name = "memchr"
-version = "2.7.4"
+version = "2.8.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
[[package]]
name = "num-conv"
-version = "0.1.0"
+version = "0.2.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "51d515d32fb182ee37cda2ccdcb92950d6a3c2893aa280e540671c2cd0f3b1d9"
+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"
[[package]]
name = "num-traits"
-version = "0.2.17"
+version = "0.2.19"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "39e3200413f237f41ab11ad6d161bc7239c84dcb631773ccd7de3dfe4b5c267c"
+checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
dependencies = [
"autocfg",
]
[[package]]
name = "num_threads"
-version = "0.1.6"
+version = "0.1.7"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2819ce041d2ee131036f4fc9d6ae7ae125a3a40e97ba64d04fe799ad9dabbb44"
+checksum = "5c7398b9c8b70908f6371f47ed36737907c87c52af34c268fed0bf0ceb92ead9"
dependencies = [
"libc",
]
[[package]]
name = "once_cell"
-version = "1.19.0"
+version = "1.21.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3fdb12b2476b595f9358c5161aa467c2438859caa136dec86c26fdd2efe17b92"
+checksum = "42f5e15c9953c5e4ccceeb2e7382a716482c34515315f7b03532b8b4e8393d2d"
[[package]]
name = "oorandom"
-version = "11.1.3"
+version = "11.1.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0ab1bc2a289d34bd04a330323ac98a1b4bc82c9d9fcb1e66b63caa84da26b575"
+checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e"
+
+[[package]]
+name = "page_size"
+version = "0.6.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "30d5b2194ed13191c1999ae0704b7839fb18384fa22e49b57eeaa97d79ce40da"
+dependencies = [
+ "libc",
+ "winapi",
+]
[[package]]
name = "powerfmt"
@@ -332,53 +390,72 @@ checksum = "439ee305def115ba05938db6eb1644ff94165c5ab5e9420d1c1bcedbba909391"
[[package]]
name = "ppv-lite86"
-version = "0.2.17"
+version = "0.2.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
+dependencies = [
+ "zerocopy",
+]
+
+[[package]]
+name = "prettyplease"
+version = "0.2.37"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5b40af805b3121feab8a3c29f04d8ad262fa8e0561883e7653e024ae4479e6de"
+checksum = "479ca8adacdd7ce8f1fb39ce9ecccbfe93a3f1344b3d0d97f20bc0196208f62b"
+dependencies = [
+ "proc-macro2",
+ "syn",
+]
[[package]]
name = "proc-macro2"
-version = "1.0.93"
+version = "1.0.106"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
dependencies = [
"unicode-ident",
]
[[package]]
name = "quickcheck"
-version = "1.0.3"
+version = "1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "588f6378e4dd99458b60ec275b4477add41ce4fa9f64dcba6f15adccb19b50d6"
+checksum = "95c589f335db0f6aaa168a7cd27b1fc6920f5e1470c804f814d9cd6e62a0f70b"
dependencies = [
- "rand 0.8.5",
+ "rand 0.10.1",
]
[[package]]
name = "quickcheck_macros"
-version = "1.0.0"
+version = "1.2.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b22a693222d716a9587786f37ac3f6b4faedb5b80c23914e7303ff5a1d8016e9"
+checksum = "a9a28b8493dd664c8b171dd944da82d933f7d456b829bfb236738e1fe06c5ba4"
dependencies = [
"proc-macro2",
"quote",
- "syn 1.0.109",
+ "syn",
]
[[package]]
name = "quote"
-version = "1.0.38"
+version = "1.0.44"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc"
+checksum = "21b2ebcf727b7760c461f091f9f0f539b77b8e87f2fd88131e7f1b433b3cece4"
dependencies = [
"proc-macro2",
]
+[[package]]
+name = "r-efi"
+version = "5.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
+
[[package]]
name = "rand"
-version = "0.8.5"
+version = "0.8.6"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "34af8d1a0e25924bc5b7c43c079c942339d8f0a8b57c39049bef581b46327404"
+checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
dependencies = [
"libc",
"rand_chacha",
@@ -387,11 +464,21 @@ dependencies = [
[[package]]
name = "rand"
-version = "0.9.2"
+version = "0.9.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
+dependencies = [
+ "rand_core 0.9.5",
+]
+
+[[package]]
+name = "rand"
+version = "0.10.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "6db2770f06117d490610c7488547d543617b21bfa07796d7a12f6f1bd53850d1"
+checksum = "d2e8e8bcc7961af1fdac401278c6a831614941f6164ee3bf4ce61b7edb162207"
dependencies = [
- "rand_core 0.9.3",
+ "getrandom 0.4.1",
+ "rand_core 0.10.0",
]
[[package]]
@@ -410,20 +497,26 @@ version = "0.6.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
dependencies = [
- "getrandom",
+ "getrandom 0.2.17",
]
[[package]]
name = "rand_core"
-version = "0.9.3"
+version = "0.9.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "99d9a13982dcf210057a8a78572b2217b667c3beacbf3a0d8b454f6f82837d38"
+checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
+
+[[package]]
+name = "rand_core"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c8d0fd677905edcbeedbf2edb6494d676f0e98d54d5cf9bda0b061cb8fb8aba"
[[package]]
name = "regex"
-version = "1.11.1"
+version = "1.12.3"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b544ef1b4eac5dc2db33ea63606ae9ffcfac26c1416a2806ae0bf5f56b201191"
+checksum = "e10754a14b9137dd7b1e3e5b0493cc9171fdd105e0ab477f51b72e7f3ac0e276"
dependencies = [
"aho-corasick",
"memchr",
@@ -433,9 +526,9 @@ dependencies = [
[[package]]
name = "regex-automata"
-version = "0.4.9"
+version = "0.4.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "809e8dc61f6de73b46c85f4c96486310fe304c434cfa43669d7b40f711150908"
+checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
dependencies = [
"aho-corasick",
"memchr",
@@ -444,9 +537,9 @@ dependencies = [
[[package]]
name = "regex-syntax"
-version = "0.8.5"
+version = "0.8.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "2b15c43186be67a4fd63bee50d0303afffcef381492ebe2c5d87f324e1b8815c"
+checksum = "a96887878f22d7bad8a3b6dc5b7440e0ada9a245242924394987b21cf2210a4c"
[[package]]
name = "relative-path"
@@ -456,19 +549,18 @@ checksum = "ba39f3699c378cd8970968dcbff9c43159ea4cfbd88d43c00b22f2ef10a435d2"
[[package]]
name = "rstest"
-version = "0.23.0"
+version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0a2c585be59b6b5dd66a9d2084aa1d8bd52fbdb806eafdeffb52791147862035"
+checksum = "f5a3193c063baaa2a95a33f03035c8a72b83d97a54916055ba22d35ed3839d49"
dependencies = [
"rstest_macros",
- "rustc_version",
]
[[package]]
name = "rstest_macros"
-version = "0.23.0"
+version = "0.26.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "825ea780781b15345a146be27eaefb05085e337e869bff01b4306a4fd4a9ad5a"
+checksum = "9c845311f0ff7951c5506121a9ad75aec44d083c31583b2ea5a30bcb0b0abba0"
dependencies = [
"cfg-if",
"glob",
@@ -477,7 +569,7 @@ dependencies = [
"regex",
"relative-path",
"rustc_version",
- "syn 2.0.96",
+ "syn",
"unicode-ident",
]
@@ -488,8 +580,8 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b3a8fb4672e840a587a66fc577a5491375df51ddb88f2a2c2a792598c326fe14"
dependencies = [
"quote",
- "rand 0.8.5",
- "syn 2.0.96",
+ "rand 0.8.6",
+ "syn",
]
[[package]]
@@ -502,23 +594,10 @@ dependencies = [
]
[[package]]
-name = "rustix"
-version = "0.38.30"
+name = "rustversion"
+version = "1.0.22"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "322394588aaf33c24007e8bb3238ee3e4c5c09c084ab32bc73890b99ff326bca"
-dependencies = [
- "bitflags",
- "errno",
- "libc",
- "linux-raw-sys",
- "windows-sys",
-]
-
-[[package]]
-name = "ryu"
-version = "1.0.18"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f"
+checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
[[package]]
name = "same-file"
@@ -531,76 +610,82 @@ dependencies = [
[[package]]
name = "semver"
-version = "1.0.21"
+version = "1.0.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b97ed7a9823b74f99c7742f5336af7be5ecd3eeafcb1507d1fa93347b1d589b0"
+checksum = "d767eb0aabc880b29956c35734170f26ed551a859dbd361d140cdbeca61ab1e2"
[[package]]
name = "serde"
-version = "1.0.217"
+version = "1.0.228"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
+dependencies = [
+ "serde_core",
+ "serde_derive",
+]
+
+[[package]]
+name = "serde_core"
+version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "02fc4265df13d6fa1d00ecff087228cc0a2b5f3c0e87e258d8b94a156e984c70"
+checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
dependencies = [
"serde_derive",
]
[[package]]
name = "serde_derive"
-version = "1.0.217"
+version = "1.0.228"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5a9bf7cf98d04a2b28aead066b7496853d4779c9cc183c440dbac457641e19a0"
+checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
dependencies = [
"proc-macro2",
"quote",
- "syn 2.0.96",
+ "syn",
]
[[package]]
name = "serde_json"
-version = "1.0.137"
+version = "1.0.149"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "930cfb6e6abf99298aaad7d29abbef7a9999a9a8806a40088f55f0dcec03146b"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
dependencies = [
"itoa",
"memchr",
- "ryu",
"serde",
+ "serde_core",
+ "zmij",
]
[[package]]
name = "serde_spanned"
-version = "0.6.8"
+version = "1.0.4"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "87607cb1398ed59d48732e575a4c28a7a8ebf2454b964fe3f224f2afc07909e1"
+checksum = "f8bbf91e5a4d6315eee45e704372590b30e260ee83af6639d64557f51b067776"
dependencies = [
- "serde",
+ "serde_core",
]
[[package]]
-name = "serde_test"
-version = "1.0.176"
+name = "serde_test2"
+version = "2.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "5a2f49ace1498612d14f7e0b8245519584db8299541dfe31a06374a828d620ab"
+checksum = "95a9eac4d4fc2509eef1f6d4f03b7ee3834fe055349ba336ab5388206176cb30"
dependencies = [
- "serde",
+ "serde_core",
]
[[package]]
-name = "syn"
-version = "1.0.109"
+name = "shlex"
+version = "1.3.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"
-dependencies = [
- "proc-macro2",
- "quote",
- "unicode-ident",
-]
+checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64"
[[package]]
name = "syn"
-version = "2.0.96"
+version = "2.0.117"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d5d0adab1ae378d7f53bdebc67a39f1f151407ef230f0ce2883572f5d8985c80"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
dependencies = [
"proc-macro2",
"quote",
@@ -609,9 +694,9 @@ dependencies = [
[[package]]
name = "target-triple"
-version = "0.1.3"
+version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "42a4d50cdb458045afc8131fd91b64904da29548bcb63c7236e0844936c13078"
+checksum = "591ef38edfb78ca4771ee32cf494cb8771944bee237a9b91fc9c1424ac4b777b"
[[package]]
name = "termcolor"
@@ -624,41 +709,42 @@ dependencies = [
[[package]]
name = "time"
-version = "0.3.44"
+version = "0.3.55"
dependencies = [
"criterion",
"deranged",
- "itoa",
"js-sys",
"libc",
"num-conv",
"num_threads",
"powerfmt",
"quickcheck",
"quickcheck_macros",
- "rand 0.8.5",
- "rand 0.9.2",
+ "rand 0.10.1",
+ "rand 0.8.6",
+ "rand 0.9.4",
"rstest",
"rstest_reuse",
"serde",
+ "serde_core",
"serde_json",
- "serde_test",
+ "serde_test2",
"time-core",
"time-macros",
"trybuild",
]
[[package]]
name = "time-core"
-version = "0.1.6"
+version = "0.1.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "40868e7c1d2f0b8d73e4a8c7f0ff63af4f6d19be117e90bd73eb1d62cf831c6b"
+checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109"
[[package]]
name = "time-macros"
-version = "0.2.24"
+version = "0.2.32"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "30cfb0125f12d9c277f35663a0a33f8c30190f4e4574868a330595412d34ebf3"
+checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85"
dependencies = [
"num-conv",
"time-core",
@@ -676,43 +762,48 @@ dependencies = [
[[package]]
name = "toml"
-version = "0.8.19"
+version = "0.9.12+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a1ed1f98e3fdc28d6d910e6737ae6ab1a93bf1985935a1193e68f93eeb68d24e"
+checksum = "cf92845e79fc2e2def6a5d828f0801e29a2f8acc037becc5ab08595c7d5e9863"
dependencies = [
- "serde",
+ "indexmap",
+ "serde_core",
"serde_spanned",
"toml_datetime",
- "toml_edit",
+ "toml_parser",
+ "toml_writer",
+ "winnow",
]
[[package]]
name = "toml_datetime"
-version = "0.6.8"
+version = "0.7.5+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "0dd7358ecb8fc2f8d014bf86f6f638ce72ba252a2c3a2572f2a795f1d23efb41"
+checksum = "92e1cfed4a3038bc5a127e35a2d360f145e1f4b971b551a2ba5fd7aedf7e1347"
dependencies = [
- "serde",
+ "serde_core",
]
[[package]]
-name = "toml_edit"
-version = "0.22.22"
+name = "toml_parser"
+version = "1.0.7+spec-1.1.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4ae48d6208a266e853d946088ed816055e556cc6028c5e8e2b84d9fa5dd7c7f5"
+checksum = "247eaa3197818b831697600aadf81514e577e0cba5eab10f7e064e78ae154df1"
dependencies = [
- "indexmap",
- "serde",
- "serde_spanned",
- "toml_datetime",
"winnow",
]
+[[package]]
+name = "toml_writer"
+version = "1.0.6+spec-1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ab16f14aed21ee8bfd8ec22513f7287cd4a91aa92e44edfe2c17ddd004e92607"
+
[[package]]
name = "trybuild"
-version = "1.0.102"
+version = "1.0.115"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f14b5c02a137632f68194ec657ecb92304138948e8957c932127eb1b58c23be"
+checksum = "5f614c21bd3a61bad9501d75cbb7686f00386c806d7f456778432c25cf86948a"
dependencies = [
"glob",
"serde",
@@ -725,79 +816,128 @@ dependencies = [
[[package]]
name = "unicode-ident"
-version = "1.0.14"
+version = "1.0.24"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "adb9e6ca4f869e1180728b7950e35922a7fc6397f7b641499e8f3ef06e50dc83"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
[[package]]
name = "walkdir"
-version = "2.4.0"
+version = "2.5.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "d71d857dc86794ca4c280d616f7da00d2dbfd8cd788846559a6813e6aa4b54ee"
+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"
dependencies = [
"same-file",
"winapi-util",
]
[[package]]
name = "wasi"
-version = "0.11.0+wasi-snapshot-preview1"
+version = "0.11.1+wasi-snapshot-preview1"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9c8d87e72b64a3b4db28d11ce29237c246188f4f51057d65a7eab63b7987e423"
+checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
[[package]]
-name = "wasm-bindgen"
-version = "0.2.90"
+name = "wasip2"
+version = "1.0.2+wasi-0.2.9"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "b1223296a201415c7fad14792dbefaace9bd52b62d33453ade1c5b5f07555406"
+checksum = "9517f9239f02c069db75e65f174b3da828fe5f5b945c4dd26bd25d89c03ebcf5"
dependencies = [
- "cfg-if",
- "wasm-bindgen-macro",
+ "wit-bindgen",
]
[[package]]
-name = "wasm-bindgen-backend"
-version = "0.2.90"
+name = "wasip3"
+version = "0.4.0+wasi-0.3.0-rc-2026-01-06"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fcdc935b63408d58a32f8cc9738a0bffd8f05cc7c002086c6ef20b7312ad9dcd"
+checksum = "5428f8bf88ea5ddc08faddef2ac4a67e390b88186c703ce6dbd955e1c145aca5"
dependencies = [
- "bumpalo",
- "log",
+ "wit-bindgen",
+]
+
+[[package]]
+name = "wasm-bindgen"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "64024a30ec1e37399cf85a7ffefebdb72205ca1c972291c51512360d90bd8566"
+dependencies = [
+ "cfg-if",
"once_cell",
- "proc-macro2",
- "quote",
- "syn 2.0.96",
+ "rustversion",
+ "wasm-bindgen-macro",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-macro"
-version = "0.2.90"
+version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3e4c238561b2d428924c49815533a8b9121c664599558a5d9ec51f8a1740a999"
+checksum = "008b239d9c740232e71bd39e8ef6429d27097518b6b30bdf9086833bd5b6d608"
dependencies = [
"quote",
"wasm-bindgen-macro-support",
]
[[package]]
name = "wasm-bindgen-macro-support"
-version = "0.2.90"
+version = "0.2.108"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bae1abb6806dc1ad9e560ed242107c0f6c84335f1749dd4e8ddb012ebd5e25a7"
+checksum = "5256bae2d58f54820e6490f9839c49780dff84c65aeab9e772f15d5f0e913a55"
dependencies = [
+ "bumpalo",
"proc-macro2",
"quote",
- "syn 2.0.96",
- "wasm-bindgen-backend",
+ "syn",
"wasm-bindgen-shared",
]
[[package]]
name = "wasm-bindgen-shared"
-version = "0.2.90"
+version = "0.2.108"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1f01b580c9ac74c8d8f0c0e4afb04eeef2acf145458e52c03845ee9cd23e3d12"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "wasm-encoder"
+version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4d91413b1c31d7539ba5ef2451af3f0b833a005eb27a631cec32bc0635a8602b"
+checksum = "990065f2fe63003fe337b932cfb5e3b80e0b4d0f5ff650e6985b1048f62c8319"
+dependencies = [
+ "leb128fmt",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasm-metadata"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909"
+dependencies = [
+ "anyhow",
+ "indexmap",
+ "wasm-encoder",
+ "wasmparser",
+]
+
+[[package]]
+name = "wasmparser"
+version = "0.244.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe"
+dependencies = [
+ "bitflags",
+ "hashbrown 0.15.5",
+ "indexmap",
+ "semver",
+]
[[package]]
name = "winapi"
@@ -817,11 +957,11 @@ checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6"
[[package]]
name = "winapi-util"
-version = "0.1.6"
+version = "0.1.11"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "f29e6f9198ba0d26b4c9f07dbe6f9ed633e1f3d5b8b414090084349e46a52596"
+checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22"
dependencies = [
- "winapi",
+ "windows-sys",
]
[[package]]
@@ -830,77 +970,137 @@ version = "0.4.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f"
+[[package]]
+name = "windows-link"
+version = "0.2.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
+
[[package]]
name = "windows-sys"
-version = "0.52.0"
+version = "0.61.2"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
dependencies = [
- "windows-targets",
+ "windows-link",
]
[[package]]
-name = "windows-targets"
-version = "0.52.0"
+name = "winnow"
+version = "0.7.14"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8a18201040b24831fbb9e4eb208f8892e1f50a37feb53cc7ff887feb8f50e7cd"
-dependencies = [
- "windows_aarch64_gnullvm",
- "windows_aarch64_msvc",
- "windows_i686_gnu",
- "windows_i686_msvc",
- "windows_x86_64_gnu",
- "windows_x86_64_gnullvm",
- "windows_x86_64_msvc",
-]
+checksum = "5a5364e9d77fcdeeaa6062ced926ee3381faa2ee02d3eb83a5c27a8825540829"
[[package]]
-name = "windows_aarch64_gnullvm"
-version = "0.52.0"
+name = "wit-bindgen"
+version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cb7764e35d4db8a7921e09562a0304bf2f93e0a51bfccee0bd0bb0b666b015ea"
+checksum = "d7249219f66ced02969388cf2bb044a09756a083d0fab1e566056b04d9fbcaa5"
+dependencies = [
+ "wit-bindgen-rust-macro",
+]
[[package]]
-name = "windows_aarch64_msvc"
-version = "0.52.0"
+name = "wit-bindgen-core"
+version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "bbaa0368d4f1d2aaefc55b6fcfee13f41544ddf36801e793edbbfd7d7df075ef"
+checksum = "ea61de684c3ea68cb082b7a88508a8b27fcc8b797d738bfc99a82facf1d752dc"
+dependencies = [
+ "anyhow",
+ "heck",
+ "wit-parser",
+]
[[package]]
-name = "windows_i686_gnu"
-version = "0.52.0"
+name = "wit-bindgen-rust"
+version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "a28637cb1fa3560a16915793afb20081aba2c92ee8af57b4d5f28e4b3e7df313"
+checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21"
+dependencies = [
+ "anyhow",
+ "heck",
+ "indexmap",
+ "prettyplease",
+ "syn",
+ "wasm-metadata",
+ "wit-bindgen-core",
+ "wit-component",
+]
[[package]]
-name = "windows_i686_msvc"
-version = "0.52.0"
+name = "wit-bindgen-rust-macro"
+version = "0.51.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ffe5e8e31046ce6230cc7215707b816e339ff4d4d67c65dffa206fd0f7aa7b9a"
+checksum = "0c0f9bfd77e6a48eccf51359e3ae77140a7f50b1e2ebfe62422d8afdaffab17a"
+dependencies = [
+ "anyhow",
+ "prettyplease",
+ "proc-macro2",
+ "quote",
+ "syn",
+ "wit-bindgen-core",
+ "wit-bindgen-rust",
+]
[[package]]
-name = "windows_x86_64_gnu"
-version = "0.52.0"
+name = "wit-component"
+version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3d6fa32db2bc4a2f5abeacf2b69f7992cd09dca97498da74a151a3132c26befd"
+checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2"
+dependencies = [
+ "anyhow",
+ "bitflags",
+ "indexmap",
+ "log",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "wasm-encoder",
+ "wasm-metadata",
+ "wasmparser",
+ "wit-parser",
+]
[[package]]
-name = "windows_x86_64_gnullvm"
-version = "0.52.0"
+name = "wit-parser"
+version = "0.244.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "1a657e1e9d3f514745a572a6846d3c7aa7dbe1658c056ed9c3344c4109a6949e"
+checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736"
+dependencies = [
+ "anyhow",
+ "id-arena",
+ "indexmap",
+ "log",
+ "semver",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "unicode-xid",
+ "wasmparser",
+]
[[package]]
-name = "windows_x86_64_msvc"
-version = "0.52.0"
+name = "zerocopy"
+version = "0.8.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "dff9641d1cd4be8d1a070daf9e3773c5f67e78b4d9d42263020c057706765c04"
+checksum = "db6d35d663eadb6c932438e763b262fe1a70987f9ae936e60158176d710cae4a"
+dependencies = [
+ "zerocopy-derive",
+]
[[package]]
-name = "winnow"
-version = "0.6.24"
+name = "zerocopy-derive"
+version = "0.8.39"
source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c8d71a593cc5c42ad7876e2c1fda56f314f3754c084128833e64f1345ff8a03a"
+checksum = "4122cd3169e94605190e77839c9a40d40ed048d305bfdc146e7df40ab0f3e517"
dependencies = [
- "memchr",
+ "proc-macro2",
+ "quote",
+ "syn",
]
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/time/Cargo.toml
@@ -10,17 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.81.0"
+edition = "2024"
+rust-version = "1.88.0"
name = "time"
-version = "0.3.44"
+version = "0.3.55"
authors = [
"Jacob Pratt <open-source@jhpratt.dev>",
"Time contributors",
]
build = false
include = [
- "src/**/*",
+ "{src,tests,benchmarks}/**/*",
"LICENSE-*",
"README.md",
]
@@ -53,14 +53,16 @@ targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = ["--generate-link-to-definition"]
[features]
-alloc = ["serde?/alloc"]
+alloc = ["serde_core?/alloc"]
default = ["std"]
formatting = [
- "dep:itoa",
"std",
"time-macros?/formatting",
]
-large-dates = ["time-macros?/large-dates"]
+large-dates = [
+ "time-core/large-dates",
+ "time-macros?/large-dates",
+]
local-offset = [
"std",
"dep:libc",
@@ -76,6 +78,11 @@ quickcheck = [
rand = [
"rand08",
"rand09",
+ "rand010",
+]
+rand010 = [
+ "dep:rand010",
+ "deranged/rand010",
]
rand08 = [
"dep:rand08",
@@ -86,7 +93,7 @@ rand09 = [
"deranged/rand09",
]
serde = [
- "dep:serde",
+ "dep:serde_core",
"time-macros?/serde",
"deranged/serde",
]
@@ -108,16 +115,20 @@ name = "time"
path = "src/lib.rs"
bench = false
-[dependencies.deranged]
-version = "0.5.2"
-features = ["powerfmt"]
+[[test]]
+name = "tests"
+path = "tests/integration/main.rs"
-[dependencies.itoa]
-version = "1.0.1"
-optional = true
+[[bench]]
+name = "benchmarks"
+path = "benchmarks/main.rs"
+harness = false
+
+[dependencies.deranged]
+version = "0.5.8"
[dependencies.num-conv]
-version = "0.1.0"
+version = "0.2.2"
[dependencies.powerfmt]
version = "0.2.0"
@@ -128,66 +139,76 @@ version = "1.0.3"
optional = true
default-features = false
+[dependencies.rand010]
+version = "0.10.1"
+optional = true
+default-features = false
+package = "rand"
+
[dependencies.rand08]
-version = "0.8.4"
+version = "0.8.6"
optional = true
default-features = false
package = "rand"
[dependencies.rand09]
-version = "0.9.2"
+version = "0.9.4"
optional = true
default-features = false
package = "rand"
-[dependencies.serde]
-version = "1.0.184"
+[dependencies.serde_core]
+version = "1.0.220"
optional = true
default-features = false
[dependencies.time-core]
-version = "=0.1.6"
+version = "=0.1.9"
[dependencies.time-macros]
-version = "=0.2.24"
+version = "=0.2.32"
optional = true
[dev-dependencies.num-conv]
-version = "0.1.0"
+version = "0.2.2"
[dev-dependencies.quickcheck_macros]
version = "1.0.0"
[dev-dependencies.rand08]
-version = "0.8.4"
+version = "0.8.6"
default-features = false
package = "rand"
[dev-dependencies.rand09]
-version = "0.9.2"
+version = "0.9.4"
+features = ["small_rng"]
default-features = false
package = "rand"
[dev-dependencies.rstest]
-version = "0.23.0"
+version = "0.26.1"
default-features = false
[dev-dependencies.rstest_reuse]
version = "0.7.0"
[dev-dependencies.serde]
version = "1.0.184"
-features = ["derive"]
+features = [
+ "derive",
+ "alloc",
+]
default-features = false
[dev-dependencies.serde_json]
version = "1.0.68"
-[dev-dependencies.serde_test]
-version = "1.0.126"
+[dev-dependencies.serde_test2]
+version = "2.0.0"
[dev-dependencies.time-macros]
-version = "=0.2.24"
+version = "=0.2.32"
[target."cfg(__ui_tests)".dev-dependencies.trybuild]
version = "1.0.102"
@@ -197,7 +218,7 @@ version = "0.3.58"
optional = true
[target."cfg(bench)".dev-dependencies.criterion]
-version = "0.5.1"
+version = "0.8.1"
default-features = false
[target.'cfg(target_family = "unix")'.dependencies.libc]
@@ -218,6 +239,7 @@ get-unwrap = "warn"
manual-let-else = "warn"
missing-docs-in-private-items = "warn"
missing-enforced-import-renames = "warn"
+missing-panics-doc = "warn"
obfuscated-if-else = "warn"
print-stdout = "warn"
semicolon-outside-block = "warn"
### external/vendor/time/Cargo.toml.orig
@@ -1,47 +1,48 @@
+lints.workspace = true
+
[package]
name = "time"
-version = "0.3.44"
-authors = ["Jacob Pratt <open-source@jhpratt.dev>", "Time contributors"]
-edition = "2021"
-rust-version = "1.81.0"
-repository = "https://github.com/time-rs/time"
-homepage = "https://time-rs.github.io"
-keywords = ["date", "time", "calendar", "duration"]
+version = "0.3.55"
categories = [
"date-and-time",
"no-std",
"parser-implementations",
"value-formatting",
]
-readme = "../README.md"
-license = "MIT OR Apache-2.0"
description = "Date and time library. Fully interoperable with the standard library. Mostly compatible with #![no_std]."
-include = ["src/**/*", "LICENSE-*", "README.md"]
-
-[lib]
-bench = false
+include = ["{src,tests,benchmarks}/**/*", "LICENSE-*", "README.md"]
+readme = "../README.md"
-[lints]
-workspace = true
+authors.workspace = true
+edition.workspace = true
+homepage.workspace = true
+keywords.workspace = true
+license.workspace = true
+repository.workspace = true
+rust-version.workspace = true
[package.metadata.docs.rs]
all-features = true
targets = ["x86_64-unknown-linux-gnu"]
rustdoc-args = ["--generate-link-to-definition"]
+[lib]
+bench = false
+
[features]
default = ["std"]
-alloc = ["serde?/alloc"]
-formatting = ["dep:itoa", "std", "time-macros?/formatting"]
-large-dates = ["time-macros?/large-dates"]
+alloc = ["serde_core?/alloc"]
+formatting = ["std", "time-macros?/formatting"]
+large-dates = ["time-core/large-dates", "time-macros?/large-dates"]
local-offset = ["std", "dep:libc", "dep:num_threads"]
macros = ["dep:time-macros"]
parsing = ["time-macros?/parsing"]
quickcheck = ["dep:quickcheck", "alloc", "deranged/quickcheck"]
-rand = ["rand08", "rand09"]
+rand = ["rand08", "rand09", "rand010"]
rand08 = ["dep:rand08", "deranged/rand08"]
rand09 = ["dep:rand09", "deranged/rand09"]
-serde = ["dep:serde", "time-macros?/serde", "deranged/serde"]
+rand010 = ["dep:rand010", "deranged/rand010"]
+serde = ["dep:serde_core", "time-macros?/serde", "deranged/serde"]
serde-human-readable = ["serde", "formatting", "parsing"]
# Deprecated in favor of using the relevant flags directly.
serde-well-known = ["serde", "formatting", "parsing"]
@@ -51,15 +52,15 @@ wasm-bindgen = ["dep:js-sys"]
# If adding an optional dependency, be sure to use the `dep:` prefix above to avoid an implicit
# feature gate.
[dependencies]
-deranged = { workspace = true }
-itoa = { workspace = true, optional = true }
-num-conv = { workspace = true }
-powerfmt = { workspace = true }
+deranged.workspace = true
+num-conv.workspace = true
+powerfmt.workspace = true
quickcheck = { workspace = true, optional = true }
rand08 = { workspace = true, optional = true }
rand09 = { workspace = true, optional = true }
-serde = { workspace = true, optional = true }
-time-core = { workspace = true }
+rand010 = { workspace = true, optional = true }
+serde_core = { workspace = true, optional = true }
+time-core.workspace = true
time-macros = { workspace = true, optional = true }
[target.'cfg(target_family = "unix")'.dependencies]
@@ -70,29 +71,28 @@ num_threads = { workspace = true, optional = true }
js-sys = { workspace = true, optional = true }
[dev-dependencies]
-num-conv = { workspace = true }
-rand08 = { workspace = true }
-rand09 = { workspace = true }
-serde = { workspace = true, features = ["derive"] }
-serde_json = { workspace = true }
-serde_test = { workspace = true }
-quickcheck_macros = { workspace = true }
-time-macros = { workspace = true }
-rstest = { workspace = true }
-rstest_reuse = { workspace = true }
+num-conv.workspace = true
+rand08.workspace = true
+rand09 = { workspace = true, features = ["small_rng"] }
+serde = { workspace = true, features = ["derive", "alloc"] }
+serde_json.workspace = true
+serde_test2.workspace = true
+quickcheck_macros.workspace = true
+time-macros.workspace = true
+rstest.workspace = true
+rstest_reuse.workspace = true
[target.'cfg(__ui_tests)'.dev-dependencies]
-trybuild = { workspace = true }
+trybuild.workspace = true
[target.'cfg(bench)'.dev-dependencies]
-criterion = { workspace = true }
+criterion.workspace = true
-# Significant contributions to the benchmarks provided by Emil Lundberg.
[[bench]]
name = "benchmarks"
harness = false
-path = "../benchmarks/main.rs"
+path = "benchmarks/main.rs"
[[test]]
name = "tests"
-path = "../tests/main.rs"
+path = "tests/integration/main.rs"
### external/vendor/time/README.md
@@ -1,6 +1,6 @@
# time
-[](https://www.whatrustisit.com)
+[](https://www.whatrustisit.com)
[](https://crates.io/crates/time)
[](https://github.com/time-rs/time/actions)
[](https://codecov.io/gh/time-rs/time)
### external/vendor/time/benchmarks/date.rs
@@ -0,0 +1,354 @@
+#![expect(
+ clippy::large_stack_frames,
+ reason = "iterating over large array; does not cause stack overflow"
+)]
+
+use std::hint::black_box as bb;
+use std::sync::LazyLock;
+
+use criterion::Bencher;
+use time::ext::{NumericalDuration, NumericalStdDuration};
+use time::macros::date;
+use time::{Date, Time};
+
+/// Generate a representative sample of all dates.
+///
+/// The ratio of month sizes, week sizes, year sign, leap years, etc. are all identical to the full
+/// range. This ensures that benchmarks accurately reflect random data.
+//
+// Note that this is a _very_ large array (over 1 MiB), so we silence the warning about large stack
+// frames at the top of this file.
+fn representative_dates() -> [Date; 292_194] {
+ static DATES: LazyLock<[Date; 292_194]> = LazyLock::new(|| {
+ let mut dates = [Date::MIN; _];
+ for (i, date) in date!(-0400-01-01).iter_to(date!(0399-12-31)).enumerate() {
+ dates[i] = date;
+ }
+ crate::shuffle(dates)
+ });
+
+ *DATES
+}
+
+setup_benchmark! {
+ "Date",
+
+ fn noop(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(date);
+ }
+ });
+ }
+
+ fn noop_windows(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates().windows(2) {
+ let first = date[0];
+ let second = date[1];
+ let _ = bb((bb(first), bb(second)));
+ }
+ });
+ }
+
+ fn from_calendar_date(ben: &mut Bencher<'_>) {
+ let dates = representative_dates().map(Date::to_calendar_date);
+ ben.iter(|| {
+ for (year, month, day) in dates {
+ let _ = bb(Date::from_calendar_date(bb(year), bb(month), bb(day)));
+ }
+ });
+ }
+
+ fn from_ordinal_date(ben: &mut Bencher<'_>) {
+ let dates = representative_dates().map(Date::to_ordinal_date);
+ ben.iter(|| {
+ for (year, ordinal) in dates {
+ let _ = bb(Date::from_ordinal_date(bb(year), bb(ordinal)));
+ }
+ });
+
+ }
+
+ fn from_iso_week_date(ben: &mut Bencher<'_>) {
+ let dates = representative_dates().map(Date::to_iso_week_date);
+ ben.iter(|| {
+ for (year, week, weekday) in dates {
+ let _ = bb(Date::from_iso_week_date(bb(year), bb(week), bb(weekday)));
+ }
+ });
+ }
+
+ fn from_julian_day(ben: &mut Bencher<'_>) {
+ let dates = representative_dates().map(Date::to_julian_day);
+ ben.iter(|| {
+ for julian_day in dates {
+ let _ = bb(Date::from_julian_day(bb(julian_day)));
+ }
+ });
+ }
+
+ fn year(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).year());
+ }
+ });
+ }
+
+ fn month(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).month());
+ }
+ });
+ }
+
+ fn day(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).day());
+ }
+ });
+ }
+
+ fn ordinal(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).ordinal());
+ }
+ });
+ }
+
+ fn iso_week(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).iso_week());
+ }
+ });
+ }
+
+ fn sunday_based_week(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).sunday_based_week());
+ }
+ });
+ }
+
+ fn monday_based_week(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).monday_based_week());
+ }
+ });
+ }
+
+ fn to_calendar_date(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).to_calendar_date());
+ }
+ });
+ }
+
+ fn to_ordinal_date(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).to_ordinal_date());
+ }
+ });
+ }
+
+ fn to_iso_week_date(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).to_iso_week_date());
+ }
+ });
+ }
+
+ fn weekday(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).weekday());
+ }
+ });
+ }
+
+ fn next_day(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).next_day());
+ }
+ });
+ }
+
+ fn previous_day(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).previous_day());
+ }
+ });
+ }
+
+ fn to_julian_day(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).to_julian_day());
+ }
+ });
+ }
+
+ fn midnight(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).midnight());
+ }
+ });
+ }
+
+ fn with_time(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).with_time(bb(Time::MIDNIGHT)));
+ }
+ });
+ }
+
+ fn with_hms(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).with_hms(bb(0), bb(0), bb(0)));
+ }
+ });
+ }
+
+ fn with_hms_milli(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).with_hms_milli(bb(0), bb(0), bb(0), bb(0)));
+ }
+ });
+ }
+
+ fn with_hms_micro(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).with_hms_micro(bb(0), bb(0), bb(0), bb(0)));
+ }
+ });
+ }
+
+ fn with_hms_nano(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date).with_hms_nano(bb(0), bb(0), bb(0), bb(0)));
+ }
+ });
+ }
+
+ fn add(ben: &mut Bencher<'_>) {
+ let dt = 5.days();
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date) + bb(dt));
+ }
+ });
+ }
+
+ fn add_std(ben: &mut Bencher<'_>) {
+ let dt = 5.std_days();
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date) - bb(dt));
+ }
+ });
+ }
+
+ fn add_assign(ben: &mut Bencher<'_>) {
+ let dt = 1.days();
+ ben.iter(|| {
+ for mut date in representative_dates() {
+ date += bb(dt);
+ let _ = bb(date);
+ }
+ });
+ }
+
+ fn add_assign_std(ben: &mut Bencher<'_>) {
+ let dt = 1.std_days();
+ ben.iter(|| {
+ for mut date in representative_dates() {
+ date += bb(dt);
+ let _ = bb(date);
+ }
+ });
+ }
+
+ fn sub(ben: &mut Bencher<'_>) {
+ let dt = 5.days();
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date) - bb(dt));
+ }
+ });
+ }
+
+ fn sub_std(ben: &mut Bencher<'_>) {
+ let dt = 5.std_days();
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date) - bb(dt));
+ }
+ });
+ }
+
+ fn sub_assign(ben: &mut Bencher<'_>) {
+ let dt = 1.days();
+ ben.iter(|| {
+ for mut date in representative_dates() {
+ date -= bb(dt);
+ let _ = bb(date);
+ }
+ });
+ }
+
+ fn sub_assign_std(ben: &mut Bencher<'_>) {
+ let dt = 1.std_days();
+ ben.iter(|| {
+ for mut date in representative_dates() {
+ date -= bb(dt);
+ let _ = bb(date);
+ }
+ });
+ }
+
+ fn sub_self(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates() {
+ let _ = bb(bb(date) - bb(date));
+ }
+ });
+ }
+
+ fn partial_ord(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates().windows(2) {
+ let first = date[0];
+ let second = date[1];
+ let _ = bb(bb(first).partial_cmp(&bb(second)));
+ }
+ });
+ }
+
+ fn ord(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for date in representative_dates().windows(2) {
+ let first = date[0];
+ let second = date[1];
+ let _ = bb(bb(first).cmp(&bb(second)));
+ }
+ });
+ }
+}
### external/vendor/time/benchmarks/duration.rs
@@ -0,0 +1,714 @@
+use std::time::Duration as StdDuration;
+
+use criterion::Bencher;
+use time::SignedDuration;
+use time::ext::{NumericalDuration, NumericalStdDuration};
+
+setup_benchmark! {
+ "SignedDuration",
+
+ fn is_zero(ben: &mut Bencher<'_>) {
+ let a = (-1).nanoseconds();
+ let b = 0.seconds();
+ let c = 1.nanoseconds();
+ ben.iter(|| a.is_zero());
+ ben.iter(|| b.is_zero());
+ ben.iter(|| c.is_zero());
+ }
+
+ fn is_negative(ben: &mut Bencher<'_>) {
+ let a = (-1).seconds();
+ let b = 0.seconds();
+ let c = 1.seconds();
+ ben.iter(|| a.is_negative());
+ ben.iter(|| b.is_negative());
+ ben.iter(|| c.is_negative());
+ }
+
+ fn is_positive(ben: &mut Bencher<'_>) {
+ let a = (-1).seconds();
+ let b = 0.seconds();
+ let c = 1.seconds();
+ ben.iter(|| a.is_positive());
+ ben.iter(|| b.is_positive());
+ ben.iter(|| c.is_positive());
+ }
+
+ fn abs(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 0.seconds();
+ let c = (-1).seconds();
+ ben.iter(|| a.abs());
+ ben.iter(|| b.abs());
+ ben.iter(|| c.abs());
+ }
+
+ fn unsigned_abs(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 0.seconds();
+ let c = (-1).seconds();
+ ben.iter(|| a.unsigned_abs());
+ ben.iter(|| b.unsigned_abs());
+ ben.iter(|| c.unsigned_abs());
+ }
+
+ fn new(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::new(1, 0));
+ ben.iter(|| SignedDuration::new(-1, 0));
+ ben.iter(|| SignedDuration::new(1, 2_000_000_000));
+
+ ben.iter(|| SignedDuration::new(0, 0));
+ ben.iter(|| SignedDuration::new(0, 1_000_000_000));
+ ben.iter(|| SignedDuration::new(-1, 1_000_000_000));
+ ben.iter(|| SignedDuration::new(-2, 1_000_000_000));
+
+ ben.iter(|| SignedDuration::new(1, -1));
+ ben.iter(|| SignedDuration::new(-1, 1));
+ ben.iter(|| SignedDuration::new(1, 1));
+ ben.iter(|| SignedDuration::new(-1, -1));
+ ben.iter(|| SignedDuration::new(0, 1));
+ ben.iter(|| SignedDuration::new(0, -1));
+
+ ben.iter(|| SignedDuration::new(-1, 1_400_000_000));
+ ben.iter(|| SignedDuration::new(-2, 1_400_000_000));
+ ben.iter(|| SignedDuration::new(-3, 1_400_000_000));
+ ben.iter(|| SignedDuration::new(1, -1_400_000_000));
+ ben.iter(|| SignedDuration::new(2, -1_400_000_000));
+ ben.iter(|| SignedDuration::new(3, -1_400_000_000));
+ }
+
+ fn weeks(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::weeks(1));
+ ben.iter(|| SignedDuration::weeks(2));
+ ben.iter(|| SignedDuration::weeks(-1));
+ ben.iter(|| SignedDuration::weeks(-2));
+ }
+
+ fn days(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::days(1));
+ ben.iter(|| SignedDuration::days(2));
+ ben.iter(|| SignedDuration::days(-1));
+ ben.iter(|| SignedDuration::days(-2));
+ }
+
+ fn hours(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::hours(1));
+ ben.iter(|| SignedDuration::hours(2));
+ ben.iter(|| SignedDuration::hours(-1));
+ ben.iter(|| SignedDuration::hours(-2));
+ }
+
+ fn minutes(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::minutes(1));
+ ben.iter(|| SignedDuration::minutes(2));
+ ben.iter(|| SignedDuration::minutes(-1));
+ ben.iter(|| SignedDuration::minutes(-2));
+ }
+
+ fn seconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::seconds(1));
+ ben.iter(|| SignedDuration::seconds(2));
+ ben.iter(|| SignedDuration::seconds(-1));
+ ben.iter(|| SignedDuration::seconds(-2));
+ }
+
+ fn seconds_f64(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::seconds_f64(0.5));
+ ben.iter(|| SignedDuration::seconds_f64(-0.5));
+ }
+
+ fn seconds_f32(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::seconds_f32(0.5));
+ ben.iter(|| SignedDuration::seconds_f32(-0.5));
+ }
+
+ fn saturating_seconds_f64(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::saturating_seconds_f64(0.5));
+ ben.iter(|| SignedDuration::saturating_seconds_f64(-0.5));
+ }
+
+ fn saturating_seconds_f32(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::saturating_seconds_f32(0.5));
+ ben.iter(|| SignedDuration::saturating_seconds_f32(-0.5));
+ }
+
+ fn checked_seconds_f64(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::checked_seconds_f64(0.5));
+ ben.iter(|| SignedDuration::checked_seconds_f64(-0.5));
+ }
+
+ fn checked_seconds_f32(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::checked_seconds_f32(0.5));
+ ben.iter(|| SignedDuration::checked_seconds_f32(-0.5));
+ }
+
+ fn milliseconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::milliseconds(1));
+ ben.iter(|| SignedDuration::milliseconds(-1));
+ }
+
+ fn microseconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::microseconds(1));
+ ben.iter(|| SignedDuration::microseconds(-1));
+ }
+
+ fn nanoseconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| SignedDuration::nanoseconds(1));
+ ben.iter(|| SignedDuration::nanoseconds(-1));
+ }
+
+ fn whole_weeks(ben: &mut Bencher<'_>) {
+ let a = SignedDuration::weeks(1);
+ let b = SignedDuration::weeks(-1);
+ let c = SignedDuration::days(6);
+ let d = SignedDuration::days(-6);
+ ben.iter(|| a.whole_weeks());
+ ben.iter(|| b.whole_weeks());
+ ben.iter(|| c.whole_weeks());
+ ben.iter(|| d.whole_weeks());
+ }
+
+ fn whole_days(ben: &mut Bencher<'_>) {
+ let a = SignedDuration::days(1);
+ let b = SignedDuration::days(-1);
+ let c = SignedDuration::hours(23);
+ let d = SignedDuration::hours(-23);
+ ben.iter(|| a.whole_days());
+ ben.iter(|| b.whole_days());
+ ben.iter(|| c.whole_days());
+ ben.iter(|| d.whole_days());
+ }
+
+ fn whole_hours(ben: &mut Bencher<'_>) {
+ let a = SignedDuration::hours(1);
+ let b = SignedDuration::hours(-1);
+ let c = SignedDuration::minutes(59);
+ let d = SignedDuration::minutes(-59);
+ ben.iter(|| a.whole_hours());
+ ben.iter(|| b.whole_hours());
+ ben.iter(|| c.whole_hours());
+ ben.iter(|| d.whole_hours());
+ }
+
+ fn whole_minutes(ben: &mut Bencher<'_>) {
+ let a = 1.minutes();
+ let b = (-1).minutes();
+ let c = 59.seconds();
+ let d = (-59).seconds();
+ ben.iter(|| a.whole_minutes());
+ ben.iter(|| b.whole_minutes());
+ ben.iter(|| c.whole_minutes());
+ ben.iter(|| d.whole_minutes());
+ }
+
+ fn whole_seconds(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = (-1).seconds();
+ let c = 1.minutes();
+ let d = (-1).minutes();
+ ben.iter(|| a.whole_seconds());
+ ben.iter(|| b.whole_seconds());
+ ben.iter(|| c.whole_seconds());
+ ben.iter(|| d.whole_seconds());
+ }
+
+ fn as_seconds_f64(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = (-1).seconds();
+ let c = 1.minutes();
+ let d = (-1).minutes();
+ let e = 1.5.seconds();
+ let f = (-1.5).seconds();
+ ben.iter(|| a.as_seconds_f64());
+ ben.iter(|| b.as_seconds_f64());
+ ben.iter(|| c.as_seconds_f64());
+ ben.iter(|| d.as_seconds_f64());
+ ben.iter(|| e.as_seconds_f64());
+ ben.iter(|| f.as_seconds_f64());
+ }
+
+ fn as_seconds_f32(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = (-1).seconds();
+ let c = 1.minutes();
+ let d = (-1).minutes();
+ let e = 1.5.seconds();
+ let f = (-1.5).seconds();
+ ben.iter(|| a.as_seconds_f32());
+ ben.iter(|| b.as_seconds_f32());
+ ben.iter(|| c.as_seconds_f32());
+ ben.iter(|| d.as_seconds_f32());
+ ben.iter(|| e.as_seconds_f32());
+ ben.iter(|| f.as_seconds_f32());
+ }
+
+ fn whole_milliseconds(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = (-1).seconds();
+ let c = 1.milliseconds();
+ let d = (-1).milliseconds();
+ ben.iter(|| a.whole_milliseconds());
+ ben.iter(|| b.whole_milliseconds());
+ ben.iter(|| c.whole_milliseconds());
+ ben.iter(|| d.whole_milliseconds());
+ }
+
+ fn subsec_milliseconds(ben: &mut Bencher<'_>) {
+ let a = 1.4.seconds();
+ let b = (-1.4).seconds();
+ ben.iter(|| a.subsec_milliseconds());
+ ben.iter(|| b.subsec_milliseconds());
+ }
+
+ fn whole_microseconds(ben: &mut Bencher<'_>) {
+ let a = 1.milliseconds();
+ let b = (-1).milliseconds();
+ let c = 1.microseconds();
+ let d = (-1).microseconds();
+ ben.iter(|| a.whole_microseconds());
+ ben.iter(|| b.whole_microseconds());
+ ben.iter(|| c.whole_microseconds());
+ ben.iter(|| d.whole_microseconds());
+ }
+
+ fn subsec_microseconds(ben: &mut Bencher<'_>) {
+ let a = 1.0004.seconds();
+ let b = (-1.0004).seconds();
+ ben.iter(|| a.subsec_microseconds());
+ ben.iter(|| b.subsec_microseconds());
+ }
+
+ fn whole_nanoseconds(ben: &mut Bencher<'_>) {
+ let a = 1.microseconds();
+ let b = (-1).microseconds();
+ let c = 1.nanoseconds();
+ let d = (-1).nanoseconds();
+ ben.iter(|| a.whole_nanoseconds());
+ ben.iter(|| b.whole_nanoseconds());
+ ben.iter(|| c.whole_nanoseconds());
+ ben.iter(|| d.whole_nanoseconds());
+ }
+
+ fn subsec_nanoseconds(ben: &mut Bencher<'_>) {
+ let a = 1.000_000_4.seconds();
+ let b = (-1.000_000_4).seconds();
+ ben.iter(|| a.subsec_nanoseconds());
+ ben.iter(|| b.subsec_nanoseconds());
+ }
+
+ fn checked_add(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = SignedDuration::MAX;
+ let c = (-5).seconds();
+
+ let a2 = 5.seconds();
+ let b2 = 1.nanoseconds();
+ let c2 = 5.seconds();
+
+ ben.iter(|| a.checked_add(a2));
+ ben.iter(|| b.checked_add(b2));
+ ben.iter(|| c.checked_add(c2));
+ }
+
+ fn checked_sub(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = SignedDuration::MIN;
+ let c = 5.seconds();
+
+ let a2 = 5.seconds();
+ let b2 = 1.nanoseconds();
+ let c2 = 10.seconds();
+
+ ben.iter(|| a.checked_sub(a2));
+ ben.iter(|| b.checked_sub(b2));
+ ben.iter(|| c.checked_sub(c2));
+ }
+
+ fn checked_mul(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = SignedDuration::MAX;
+ ben.iter(|| a.checked_mul(2));
+ ben.iter(|| b.checked_mul(2));
+ }
+
+ fn checked_div(ben: &mut Bencher<'_>) {
+ let a = 10.seconds();
+ ben.iter(|| a.checked_div(2));
+ ben.iter(|| a.checked_div(0));
+ }
+
+ fn saturating_add(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = SignedDuration::MAX;
+ let c = SignedDuration::MIN;
+ let d = (-5).seconds();
+
+ let a2 = 5.seconds();
+ let b2 = 1.nanoseconds();
+ let c2 = (-1).nanoseconds();
+ let d2 = 5.seconds();
+
+ ben.iter(|| a.saturating_add(a2));
+ ben.iter(|| b.saturating_add(b2));
+ ben.iter(|| c.saturating_add(c2));
+ ben.iter(|| d.saturating_add(d2));
+ }
+
+ fn saturating_sub(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = SignedDuration::MIN;
+ let c = SignedDuration::MAX;
+ let d = 5.seconds();
+
+ let a2 = 5.seconds();
+ let b2 = 1.nanoseconds();
+ let c2 = (-1).nanoseconds();
+ let d2 = 10.seconds();
+
+ ben.iter(|| a.saturating_sub(a2));
+ ben.iter(|| b.saturating_sub(b2));
+ ben.iter(|| c.saturating_sub(c2));
+ ben.iter(|| d.saturating_sub(d2));
+ }
+
+ fn saturating_mul(ben: &mut Bencher<'_>) {
+ let a = 5.seconds();
+ let b = 5.seconds();
+ let c = 5.seconds();
+ let d = SignedDuration::MAX;
+ let e = SignedDuration::MIN;
+ let f = SignedDuration::MAX;
+ let g = SignedDuration::MIN;
+
+ ben.iter(|| a.saturating_mul(2));
+ ben.iter(|| b.saturating_mul(-2));
+ ben.iter(|| c.saturating_mul(0));
+ ben.iter(|| d.saturating_mul(2));
+ ben.iter(|| e.saturating_mul(2));
+ ben.iter(|| f.saturating_mul(-2));
+ ben.iter(|| g.saturating_mul(-2));
+ }
+
+ fn try_from_std_duration(ben: &mut Bencher<'_>) {
+ let a = 0.std_seconds();
+ let b = 1.std_seconds();
+ ben.iter(|| SignedDuration::try_from(a));
+ ben.iter(|| SignedDuration::try_from(b));
+ }
+
+ fn try_to_std_duration(ben: &mut Bencher<'_>) {
+ let a = 0.seconds();
+ let b = 1.seconds();
+ let c = (-1).seconds();
+ ben.iter(|| StdDuration::try_from(a));
+ ben.iter(|| StdDuration::try_from(b));
+ ben.iter(|| StdDuration::try_from(c));
+ }
+
+ fn add(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 2.seconds();
+ let c = 500.milliseconds();
+ let d = (-1).seconds();
+ ben.iter(|| a + b + c + d);
+ }
+
+ fn add_std(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 2.std_seconds();
+ ben.iter(|| a + b);
+ }
+
+ fn std_add(ben: &mut Bencher<'_>) {
+ let a = 1.std_seconds();
+ let b = 2.seconds();
+ ben.iter(|| a + b);
+ }
+
+ fn add_assign(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 500.milliseconds();
+ let c = (-1).seconds();
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration += a,
+ |duration| *duration += b,
+ |duration| *duration += c,
+ ]
+ );
+ }
+
+ fn add_assign_std(ben: &mut Bencher<'_>) {
+ let a = 1.std_seconds();
+ let b = 500.std_milliseconds();
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration += a,
+ |duration| *duration += b,
+ ]
+ );
+ }
+
+ fn neg(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = (-1).seconds();
+ let c = 0.seconds();
+ ben.iter(|| -a);
+ ben.iter(|| -b);
+ ben.iter(|| -c);
+ }
+
+ fn sub(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 1.seconds();
+ let c = 1_500.milliseconds();
+ let d = 500.milliseconds();
+ let e = 1.seconds();
+ let f = (-1).seconds();
+ ben.iter(|| a - b);
+ ben.iter(|| b - c);
+ ben.iter(|| c - d);
+ ben.iter(|| d - e);
+ ben.iter(|| e - f);
+ ben.iter(|| f - a);
+ }
+
+ fn sub_std(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 2.std_seconds();
+ ben.iter(|| a - b);
+ }
+
+ fn std_sub(ben: &mut Bencher<'_>) {
+ let a = 1.std_seconds();
+ let b = 2.seconds();
+ ben.iter(|| a - b);
+ }
+
+ fn sub_assign(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 500.milliseconds();
+ let c = (-1).seconds();
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration -= a,
+ |duration| *duration -= b,
+ |duration| *duration -= c,
+ ]
+ );
+ }
+
+ fn mul_int(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| d * 2);
+ ben.iter(|| d * -2);
+ }
+
+ fn mul_int_assign(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration *= 2,
+ |duration| *duration *= -2,
+ ]
+ );
+ }
+
+ fn int_mul(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| 2 * d);
+ ben.iter(|| -2 * d);
+ }
+
+ fn div_int(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| d / 2);
+ ben.iter(|| d / -2);
+ }
+
+ fn div_int_assign(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration /= 2,
+ |duration| *duration /= -2,
+ ]
+ );
+ }
+
+ fn div(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 0.5.seconds();
+ ben.iter(|| a / b);
+ }
+
+ fn mul_float(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| d * 1.5_f32);
+ ben.iter(|| d * 2.5_f32);
+ ben.iter(|| d * -1.5_f32);
+ ben.iter(|| d * 0_f32);
+ ben.iter(|| d * 1.5_f64);
+ ben.iter(|| d * 2.5_f64);
+ ben.iter(|| d * -1.5_f64);
+ ben.iter(|| d * 0_f64);
+ }
+
+ fn float_mul(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| 1.5_f32 * d);
+ ben.iter(|| 2.5_f32 * d);
+ ben.iter(|| -1.5_f32 * d);
+ ben.iter(|| 0_f32 * d);
+ ben.iter(|| 1.5_f64 * d);
+ ben.iter(|| 2.5_f64 * d);
+ ben.iter(|| -1.5_f64 * d);
+ ben.iter(|| 0_f64 * d);
+ }
+
+ fn mul_float_assign(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || 1.seconds(),
+ [
+ |duration| *duration *= 1.5_f32,
+ |duration| *duration *= 2.5_f32,
+ |duration| *duration *= -1.5_f32,
+ |duration| *duration *= 3.15_f32,
+ |duration| *duration *= 1.5_f64,
+ |duration| *duration *= 2.5_f64,
+ |duration| *duration *= -1.5_f64,
+ |duration| *duration *= 0_f64,
+ ]
+ );
+ }
+
+ fn div_float(ben: &mut Bencher<'_>) {
+ let d = 1.seconds();
+ ben.iter(|| d / 1_f32);
+ ben.iter(|| d / 2_f32);
+ ben.iter(|| d / -1_f32);
+ ben.iter(|| d / 1_f64);
+ ben.iter(|| d / 2_f64);
+ ben.iter(|| d / -1_f64);
+ }
+
+ fn div_float_assign(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || 10.seconds(),
+ [
+ |duration| *duration /= 1_f32,
+ |duration| *duration /= 2_f32,
+ |duration| *duration /= -1_f32,
+ |duration| *duration /= 1_f64,
+ |duration| *duration /= 2_f64,
+ |duration| *duration /= -1_f64,
+ ]
+ );
+ }
+
+ fn partial_eq(ben: &mut Bencher<'_>) {
+ let a = 1.minutes();
+ let b = (-1).minutes();
+ let c = 40.seconds();
+ ben.iter(|| a == b);
+ ben.iter(|| c == a);
+ }
+
+ fn partial_eq_std(ben: &mut Bencher<'_>) {
+ let a = (-1).seconds();
+ let b = 1.std_seconds();
+ let c = (-1).minutes();
+ let d = 1.std_minutes();
+ let e = 40.seconds();
+ ben.iter(|| a == b);
+ ben.iter(|| c == d);
+ ben.iter(|| e == d);
+ }
+
+ fn std_partial_eq(ben: &mut Bencher<'_>) {
+ let a = 1.std_seconds();
+ let b = (-1).seconds();
+ let c = 1.std_minutes();
+ let d = (-1).minutes();
+ let e = 40.std_seconds();
+ let f = 1.minutes();
+ ben.iter(|| a == b);
+ ben.iter(|| c == d);
+ ben.iter(|| e == f);
+ }
+
+ fn partial_ord(ben: &mut Bencher<'_>) {
+ let a = 0.seconds();
+ let b = 1.seconds();
+ let c = (-1).seconds();
+ let d = 1.minutes();
+ let e = (-1).minutes();
+ ben.iter(|| a.partial_cmp(&a));
+ ben.iter(|| b.partial_cmp(&a));
+ ben.iter(|| b.partial_cmp(&c));
+ ben.iter(|| c.partial_cmp(&b));
+ ben.iter(|| a.partial_cmp(&c));
+ ben.iter(|| a.partial_cmp(&b));
+ ben.iter(|| c.partial_cmp(&a));
+ ben.iter(|| d.partial_cmp(&b));
+ ben.iter(|| e.partial_cmp(&c));
+ }
+
+ fn partial_ord_std(ben: &mut Bencher<'_>) {
+ let a = 0.seconds();
+ let b = 0.std_seconds();
+ let c = 1.seconds();
+ let d = (-1).seconds();
+ let e = 1.std_seconds();
+ let f = 1.minutes();
+ let g = u64::MAX.std_seconds();
+ ben.iter(|| a.partial_cmp(&b));
+ ben.iter(|| c.partial_cmp(&b));
+ ben.iter(|| d.partial_cmp(&e));
+ ben.iter(|| a.partial_cmp(&e));
+ ben.iter(|| d.partial_cmp(&b));
+ ben.iter(|| f.partial_cmp(&e));
+ ben.iter(|| a.partial_cmp(&g));
+ }
+
+ fn std_partial_ord(ben: &mut Bencher<'_>) {
+ let a = 0.std_seconds();
+ let b = 0.seconds();
+ let c = 1.std_seconds();
+ let d = (-1).seconds();
+ let e = 1.seconds();
+ let f = 1.std_minutes();
+ ben.iter(|| a.partial_cmp(&b));
+ ben.iter(|| c.partial_cmp(&b));
+ ben.iter(|| c.partial_cmp(&d));
+ ben.iter(|| a.partial_cmp(&d));
+ ben.iter(|| a.partial_cmp(&e));
+ ben.iter(|| f.partial_cmp(&e));
+ }
+
+ fn ord(ben: &mut Bencher<'_>) {
+ let a = 1.seconds();
+ let b = 0.seconds();
+ let c = (-1).seconds();
+ let d = 1.minutes();
+ let e = (-1).minutes();
+ ben.iter(|| a > b);
+ ben.iter(|| a > c);
+ ben.iter(|| c < a);
+ ben.iter(|| b > c);
+ ben.iter(|| b < a);
+ ben.iter(|| c < b);
+ ben.iter(|| d > a);
+ ben.iter(|| e < c);
+ }
+}
### external/vendor/time/benchmarks/formatting.rs
@@ -0,0 +1,190 @@
+use std::io;
+
+use criterion::Bencher;
+use time::format_description;
+use time::format_description::well_known::{Rfc2822, Rfc3339};
+use time::macros::{date, datetime, format_description as fd, offset, time};
+
+setup_benchmark! {
+ "Formatting",
+
+ fn format_rfc3339(ben: &mut Bencher<'_>) {
+ macro_rules! item {
+ ($value:expr) => {
+ $value.format_into(&mut io::sink(), &Rfc3339)
+ }
+ }
+
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.1 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.12 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_4 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_45 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456_7 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456_78 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456_789 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456_789 -01:02)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05.123_456_789 +01:02)));
+ }
+
+ fn format_rfc2822(ben: &mut Bencher<'_>) {
+ macro_rules! item {
+ ($value:expr) => {
+ $value.format_into(&mut io::sink(), &Rfc2822)
+ }
+ }
+
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05 UTC)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05 +06:07)));
+ ben.iter(|| item!(datetime!(2021-01-02 03:04:05 -06:07)));
+ }
+
+
+ fn format_time(ben: &mut Bencher<'_>) {
+ macro_rules! item {
+ ($format:expr) => {
+ time!(13:02:03.456_789_012).format_into(
+ &mut io::sink(),
+ &$format,
+ )
+ }
+ }
+
+ ben.iter(|| item!(fd!("[hour]")));
+ ben.iter(|| item!(fd!("[hour repr:12]")));
+ ben.iter(|| item!(fd!("[hour repr:12 padding:none]")));
+ ben.iter(|| item!(fd!("[hour repr:12 padding:space]")));
+ ben.iter(|| item!(fd!("[hour repr:24]")));
+ ben.iter(|| item!(fd!("[hour repr:24]")));
+ ben.iter(|| item!(fd!("[hour repr:24 padding:none]")));
+ ben.iter(|| item!(fd!("[hour repr:24 padding:space]")));
+ ben.iter(|| item!(fd!("[minute]")));
+ ben.iter(|| item!(fd!("[minute padding:none]")));
+ ben.iter(|| item!(fd!("[minute padding:space]")));
+ ben.iter(|| item!(fd!("[minute padding:zero]")));
+ ben.iter(|| item!(fd!("[period]")));
+ ben.iter(|| item!(fd!("[period case:upper]")));
+ ben.iter(|| item!(fd!("[period case:lower]")));
+ ben.iter(|| item!(fd!("[second]")));
+ ben.iter(|| item!(fd!("[second padding:none]")));
+ ben.iter(|| item!(fd!("[second padding:space]")));
+ ben.iter(|| item!(fd!("[second padding:zero]")));
+ ben.iter(|| item!(fd!("[subsecond]")));
+ ben.iter(|| item!(fd!("[subsecond digits:1]")));
+ ben.iter(|| item!(fd!("[subsecond digits:2]")));
+ ben.iter(|| item!(fd!("[subsecond digits:3]")));
+ ben.iter(|| item!(fd!("[subsecond digits:4]")));
+ ben.iter(|| item!(fd!("[subsecond digits:5]")));
+ ben.iter(|| item!(fd!("[subsecond digits:6]")));
+ ben.iter(|| item!(fd!("[subsecond digits:7]")));
+ ben.iter(|| item!(fd!("[subsecond digits:8]")));
+ ben.iter(|| item!(fd!("[subsecond digits:9]")));
+ ben.iter(|| item!(fd!("[subsecond digits:1+]")));
+ }
+
+ fn display_time(ben: &mut Bencher<'_>) {
+ ben.iter(|| time!(0:00).to_string());
+ ben.iter(|| time!(23:59).to_string());
+ ben.iter(|| time!(23:59:59).to_string());
+ ben.iter(|| time!(0:00:01).to_string());
+ ben.iter(|| time!(0:00:00.001).to_string());
+ ben.iter(|| time!(0:00:00.000_001).to_string());
+ ben.iter(|| time!(0:00:00.000_000_001).to_string());
+ }
+
+ fn format_date(ben: &mut Bencher<'_>) {
+ macro_rules! item {
+ ($format:expr) => {
+ date!(2019-12-31).format_into(&mut io::sink(), &$format)
+ }
+ }
+
+ ben.iter(|| item!(fd!("[day]")));
+ ben.iter(|| item!(fd!("[month]")));
+ ben.iter(|| item!(fd!("[month repr:short]")));
+ ben.iter(|| item!(fd!("[month repr:long]")));
+ ben.iter(|| item!(fd!("[ordinal]")));
+ ben.iter(|| item!(fd!("[weekday]")));
+ ben.iter(|| item!(fd!("[weekday repr:short]")));
+ ben.iter(|| item!(fd!("[weekday repr:sunday]")));
+ ben.iter(|| item!(fd!("[weekday repr:sunday one_indexed:false]")));
+ ben.iter(|| item!(fd!("[weekday repr:monday]")));
+ ben.iter(|| item!(fd!("[weekday repr:monday one_indexed:false]")));
+ ben.iter(|| item!(fd!("[week_number]")));
+ ben.iter(|| item!(fd!("[week_number padding:none]")));
+ ben.iter(|| item!(fd!("[week_number padding:space]")));
+ ben.iter(|| item!(fd!("[week_number repr:sunday]")));
+ ben.iter(|| item!(fd!("[week_number repr:monday]")));
+ ben.iter(|| item!(fd!("[year]")));
+ ben.iter(|| item!(fd!("[year base:iso_week]")));
+ ben.iter(|| item!(fd!("[year sign:mandatory]")));
+ ben.iter(|| item!(fd!("[year base:iso_week sign:mandatory]")));
+ ben.iter(|| item!(fd!("[year repr:last_two]")));
+ ben.iter(|| item!(fd!("[year base:iso_week repr:last_two]")));
+ }
+
+ fn display_date(ben: &mut Bencher<'_>) {
+ ben.iter(|| date!(2019-01-01).to_string());
+ ben.iter(|| date!(2019-12-31).to_string());
+ ben.iter(|| date!(-4713-11-24).to_string());
+ ben.iter(|| date!(-0001-01-01).to_string());
+ }
+
+ fn format_offset(ben: &mut Bencher<'_>) {
+ macro_rules! item {
+ ($value:expr, $format:expr) => {
+ $value.format_into(&mut io::sink(), &$format)
+ }
+ }
+
+ ben.iter(|| item!(offset!(+01:02:03), fd!("[offset_hour sign:automatic]")));
+ ben.iter(|| item!(offset!(+01:02:03), fd!("[offset_hour sign:mandatory]")));
+ ben.iter(|| item!(offset!(-01:02:03), fd!("[offset_hour sign:automatic]")));
+ ben.iter(|| item!(offset!(-01:02:03), fd!("[offset_hour sign:mandatory]")));
+ ben.iter(|| item!(offset!(+01:02:03), fd!("[offset_minute]")));
+ ben.iter(|| item!(offset!(+01:02:03), fd!("[offset_second]")));
+ }
+
+ fn display_offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| offset!(UTC).to_string());
+ ben.iter(|| offset!(+0:00:01).to_string());
+ ben.iter(|| offset!(-0:00:01).to_string());
+ ben.iter(|| offset!(+1).to_string());
+ ben.iter(|| offset!(-1).to_string());
+ ben.iter(|| offset!(+23:59).to_string());
+ ben.iter(|| offset!(-23:59).to_string());
+ ben.iter(|| offset!(+23:59:59).to_string());
+ ben.iter(|| offset!(-23:59:59).to_string());
+ }
+
+ fn format_pdt(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ datetime!(1970-01-01 0:00).format_into(
+ &mut io::sink(),
+ fd!("[year]-[month]-[day] [hour]:[minute]:[second].[subsecond]"),
+ )
+ });
+ }
+
+ fn display_pdt(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(1970-01-01 0:00).to_string());
+ ben.iter(|| datetime!(1970-01-01 0:00:01).to_string());
+ }
+
+ fn format_odt(ben: &mut Bencher<'_>) {
+ let format_description = format_description::parse_borrowed::<1>(
+ "[year]-[month]-[day] [hour]:[minute]:[second].[subsecond] [offset_hour \
+ sign:mandatory]:[offset_minute]:[offset_second]",
+ ).expect("invalid format description");
+
+ ben.iter(|| {
+ datetime!(1970-01-01 0:00 UTC).format_into(&mut io::sink(), &format_description)
+ });
+ }
+
+ fn display_odt(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(1970-01-01 0:00 UTC).to_string());
+ }
+}
### external/vendor/time/benchmarks/instant.rs
@@ -0,0 +1,89 @@
+#![expect(deprecated)]
+
+use std::time::Instant as StdInstant;
+
+use criterion::Bencher;
+use time::ext::NumericalDuration;
+use time::{Instant, SignedDuration};
+
+setup_benchmark! {
+ "Instant",
+
+ fn checked_add(ben: &mut Bencher<'_>) {
+ let instant = Instant::now();
+ let dt = 5.seconds();
+ ben.iter(|| instant.checked_add(dt));
+ }
+
+ fn checked_sub(ben: &mut Bencher<'_>) {
+ let instant = Instant::now();
+ let dt = 5.seconds();
+ ben.iter(|| instant.checked_sub(dt));
+ }
+
+ fn sub(ben: &mut Bencher<'_>) {
+ let start: Instant = Instant::now();
+ let end: Instant = start + 1.milliseconds();
+ ben.iter(|| end - start);
+ }
+
+ fn add_duration(ben: &mut Bencher<'_>) {
+ let start = Instant::now();
+ let dt: SignedDuration = 1.seconds();
+ ben.iter(|| start + dt);
+ }
+
+ fn std_add_duration(ben: &mut Bencher<'_>) {
+ let start = StdInstant::now();
+ let dt: SignedDuration = 1.milliseconds();
+ ben.iter(|| start + dt);
+ }
+
+ fn add_assign_duration(ben: &mut Bencher<'_>) {
+ let dt: SignedDuration = 1.milliseconds();
+ iter_batched_ref!(
+ ben,
+ Instant::now,
+ [|start| *start += dt]
+ );
+ }
+
+ fn std_add_assign_duration(ben: &mut Bencher<'_>) {
+ let dt: SignedDuration = 1.milliseconds();
+ iter_batched_ref!(
+ ben,
+ StdInstant::now,
+ [|start| *start += dt]
+ );
+ }
+
+ fn sub_duration(ben: &mut Bencher<'_>) {
+ let instant = Instant::now();
+ let dt: SignedDuration = 100.milliseconds();
+ ben.iter(|| instant - dt);
+ }
+
+ fn std_sub_duration(ben: &mut Bencher<'_>) {
+ let instant = StdInstant::now();
+ let dt: SignedDuration = 100.milliseconds();
+ ben.iter(|| instant - dt);
+ }
+
+ fn sub_assign_duration(ben: &mut Bencher<'_>) {
+ let dt: SignedDuration = 100.milliseconds();
+ iter_batched_ref!(
+ ben,
+ Instant::now,
+ [|instant| *instant -= dt]
+ );
+ }
+
+ fn std_sub_assign_duration(ben: &mut Bencher<'_>) {
+ let dt: SignedDuration = 100.milliseconds();
+ iter_batched_ref!(
+ ben,
+ StdInstant::now,
+ [|instant| *instant -= dt]
+ );
+ }
+}
### external/vendor/time/benchmarks/main.rs
@@ -0,0 +1,119 @@
+//! Benchmarks for `time`.
+//!
+//! These benchmarks are not very precise, but they're good enough to catch major performance
+//! regressions. Run them if you think that may be the case. CI **does not** run benchmarks.
+
+#![allow(
+ clippy::std_instead_of_core,
+ clippy::std_instead_of_alloc,
+ clippy::alloc_instead_of_core,
+ reason = "irrelevant for benchmarks"
+)]
+#![allow(
+ clippy::missing_docs_in_private_items,
+ reason = "may be removed in the future"
+)]
+
+#[cfg(not(all(
+ feature = "default",
+ feature = "alloc",
+ feature = "formatting",
+ feature = "large-dates",
+ feature = "local-offset",
+ feature = "macros",
+ feature = "parsing",
+ feature = "quickcheck",
+ feature = "serde-human-readable",
+ feature = "serde-well-known",
+ feature = "std",
+ feature = "rand",
+ feature = "serde",
+ bench,
+)))]
+compile_error!(
+ "benchmarks must be run as `RUSTFLAGS=\"--cfg bench\" cargo criterion --all-features`"
+);
+
+macro_rules! setup_benchmark {
+ (
+ $group_prefix:literal,
+ $(
+ $(#[$fn_attr:meta])*
+ fn $fn_name:ident ($bencher:ident : $bencher_type:ty)
+ $code:block
+ )*
+ ) => {
+ $(
+ $(#[$fn_attr])*
+ fn $fn_name(
+ c: &mut ::criterion::Criterion
+ ) {
+ c.bench_function(
+ concat!($group_prefix, ": ", stringify!($fn_name)),
+ |$bencher: $bencher_type| $code
+ );
+ }
+ )*
+
+ ::criterion::criterion_group! {
+ name = benches;
+ config = ::criterion::Criterion::default()
+ // Set a stricter statistical significance threshold ("p-value")
+ // for deciding what's an actual performance change vs. noise.
+ // The more benchmarks, the lower this needs to be in order to
+ // not get lots of false positives.
+ .significance_level(0.0001)
+ // Ignore any performance change less than this (0.05 = 5%) as
+ // noise, regardless of statistical significance.
+ .noise_threshold(0.05)
+ // Reduce the time taken to run each benchmark
+ .warm_up_time(::std::time::Duration::from_millis(100))
+ .measurement_time(::std::time::Duration::from_millis(500));
+ targets = $($fn_name,)*
+ }
+ };
+}
+
+macro_rules! iter_batched_ref {
+ ($ben:ident, $initializer:expr,[$($routine:expr),+ $(,)?]) => {$(
+ $ben.iter_batched_ref(
+ $initializer,
+ $routine,
+ ::criterion::BatchSize::SmallInput,
+ );
+ )+};
+}
+
+macro_rules! mods {
+ ($(mod $mod:ident;)+) => {
+ $(mod $mod;)+
+ ::criterion::criterion_main!($($mod::benches),+);
+ }
+}
+
+mods![
+ mod date;
+ mod duration;
+ mod formatting;
+ mod instant;
+ mod month;
+ mod offset_date_time;
+ mod parse_format_description;
+ mod parsing;
+ mod plain_date_time;
+ mod rand08;
+ mod rand09;
+ mod time;
+ mod utc_offset;
+ mod util;
+ mod weekday;
+];
+
+/// Shuffle a slice in a random but deterministic manner.
+fn shuffle<T, const N: usize>(mut slice: [T; N]) -> [T; N] {
+ use ::rand09::prelude::*;
+
+ let mut seed = SmallRng::seed_from_u64(0);
+ slice.shuffle(&mut seed);
+ slice
+}
### external/vendor/time/benchmarks/month.rs
@@ -0,0 +1,66 @@
+use criterion::Bencher;
+use time::Month::*;
+
+setup_benchmark! {
+ "Month",
+
+ fn previous(ben: &mut Bencher<'_>) {
+ ben.iter(|| January.previous());
+ ben.iter(|| February.previous());
+ ben.iter(|| March.previous());
+ ben.iter(|| April.previous());
+ ben.iter(|| May.previous());
+ ben.iter(|| June.previous());
+ ben.iter(|| July.previous());
+ ben.iter(|| August.previous());
+ ben.iter(|| September.previous());
+ ben.iter(|| October.previous());
+ ben.iter(|| November.previous());
+ ben.iter(|| December.previous());
+ }
+
+ fn next(ben: &mut Bencher<'_>) {
+ ben.iter(|| January.next());
+ ben.iter(|| February.next());
+ ben.iter(|| March.next());
+ ben.iter(|| April.next());
+ ben.iter(|| May.next());
+ ben.iter(|| June.next());
+ ben.iter(|| July.next());
+ ben.iter(|| August.next());
+ ben.iter(|| September.next());
+ ben.iter(|| October.next());
+ ben.iter(|| November.next());
+ ben.iter(|| December.next());
+ }
+
+ fn length(ben: &mut Bencher<'_>) {
+ // Common year
+ ben.iter(|| January.length(2019));
+ ben.iter(|| February.length(2019));
+ ben.iter(|| March.length(2019));
+ ben.iter(|| April.length(2019));
+ ben.iter(|| May.length(2019));
+ ben.iter(|| June.length(2019));
+ ben.iter(|| July.length(2019));
+ ben.iter(|| August.length(2019));
+ ben.iter(|| September.length(2019));
+ ben.iter(|| October.length(2019));
+ ben.iter(|| November.length(2019));
+ ben.iter(|| December.length(2019));
+
+ // Leap year
+ ben.iter(|| January.length(2020));
+ ben.iter(|| February.length(2020));
+ ben.iter(|| March.length(2020));
+ ben.iter(|| April.length(2020));
+ ben.iter(|| May.length(2020));
+ ben.iter(|| June.length(2020));
+ ben.iter(|| July.length(2020));
+ ben.iter(|| August.length(2020));
+ ben.iter(|| September.length(2020));
+ ben.iter(|| October.length(2020));
+ ben.iter(|| November.length(2020));
+ ben.iter(|| December.length(2020));
+ }
+}
### external/vendor/time/benchmarks/offset_date_time.rs
@@ -0,0 +1,424 @@
+use std::hint::black_box;
+use std::time::SystemTime;
+
+use criterion::Bencher;
+use time::OffsetDateTime;
+use time::ext::{NumericalDuration, NumericalStdDuration};
+use time::macros::{date, datetime, offset, time};
+
+setup_benchmark! {
+ "OffsetDateTime",
+
+ fn now_utc(ben: &mut Bencher<'_>) {
+ ben.iter(OffsetDateTime::now_utc);
+ }
+
+ fn now_local(ben: &mut Bencher<'_>) {
+ ben.iter(OffsetDateTime::now_local);
+ }
+
+ fn to_offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2000-01-01 0:00 +11).to_offset(offset!(-5)));
+ ben.iter(|| datetime!(2000-01-01 0:00 +11).to_offset(offset!(-8)));
+ }
+
+ fn to_utc(ben: &mut Bencher<'_>) {
+ ben.iter(|| black_box(datetime!(2000-01-01 0:00 +11).to_utc()));
+ }
+
+ fn from_unix_timestamp(ben: &mut Bencher<'_>) {
+ ben.iter(|| OffsetDateTime::from_unix_timestamp(0));
+ ben.iter(|| OffsetDateTime::from_unix_timestamp(1_546_300_800));
+ }
+
+ fn from_unix_timestamp_nanos(ben: &mut Bencher<'_>) {
+ ben.iter(|| OffsetDateTime::from_unix_timestamp_nanos(0));
+ ben.iter(|| OffsetDateTime::from_unix_timestamp_nanos(1_546_300_800_000_000_000));
+ }
+
+ fn offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).offset());
+ ben.iter(|| datetime!(2019-01-01 0:00 +1).offset());
+ ben.iter(|| datetime!(2019-01-01 1:00 +1).offset());
+ }
+
+ fn unix_timestamp(ben: &mut Bencher<'_>) {
+ ben.iter(|| OffsetDateTime::UNIX_EPOCH.unix_timestamp());
+ ben.iter(|| datetime!(1970-01-01 1:00 +1).unix_timestamp());
+ ben.iter(|| datetime!(1970-01-01 0:00 -1).unix_timestamp());
+ }
+
+ fn unix_timestamp_nanos(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(1970-01-01 0:00 UTC).unix_timestamp_nanos());
+ ben.iter(|| datetime!(1970-01-01 1:00 +1).unix_timestamp_nanos());
+ ben.iter(|| datetime!(1970-01-01 0:00 -1).unix_timestamp_nanos());
+ }
+
+ fn date(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).date());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).date());
+ }
+
+ fn time(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).time());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).time());
+ }
+
+ fn year(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).year());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).year());
+ }
+
+ fn ordinal(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).ordinal());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).ordinal());
+ }
+
+ fn hour(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).hour());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).hour());
+ }
+
+ fn minute(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).minute());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).minute());
+ }
+
+ fn second(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC).second());
+ ben.iter(|| datetime!(2018-12-31 23:00 -1).second());
+ }
+
+ fn replace_time(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2020-01-01 5:00 UTC).replace_time(time!(12:00)));
+ ben.iter(|| datetime!(2020-01-01 12:00 -5).replace_time(time!(7:00)));
+ ben.iter(|| datetime!(2020-01-01 0:00 +1).replace_time(time!(12:00)));
+ }
+
+ fn replace_date(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2020-01-01 12:00 UTC).replace_date(date!(2020-01-30)));
+ ben.iter(|| datetime!(2020-01-01 0:00 +1).replace_date(date!(2020-01-30)));
+ }
+
+ fn replace_date_time(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2020-01-01 12:00 UTC).replace_date_time(datetime!(2020-01-30 16:00)));
+ ben.iter(|| datetime!(2020-01-01 12:00 +1).replace_date_time(datetime!(2020-01-30 0:00)));
+ }
+
+ fn replace_offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC).replace_offset(offset!(-5)));
+ }
+
+ fn partial_eq(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(1999-12-31 23:00 -1) == datetime!(2000-01-01 0:00 UTC));
+ }
+
+ fn partial_ord(ben: &mut Bencher<'_>) {
+ ben.iter(||
+ datetime!(2019-01-01 0:00 UTC).partial_cmp(&datetime!(1999-12-31 23:00 -1))
+ );
+ }
+
+ fn ord(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) == datetime!(2018-12-31 23:00 -1));
+ ben.iter(|| datetime!(2019-01-01 0:00:00.000_000_001 UTC) > datetime!(2019-01-01 0:00 UTC));
+ }
+
+ fn hash(ben: &mut Bencher<'_>) {
+ use std::collections::hash_map::DefaultHasher;
+ use std::hash::Hash;
+
+ iter_batched_ref!(
+ ben,
+ DefaultHasher::new,
+ [
+ |hasher| datetime!(2019-01-01 0:00 UTC).hash(hasher),
+ |hasher| datetime!(2018-12-31 23:00 -1).hash(hasher),
+ ]
+ );
+ }
+
+ fn add_duration(ben: &mut Bencher<'_>) {
+ let a = 5.days();
+ let b = 1.days();
+ let c = 2.seconds();
+ let d = (-2).seconds();
+ let e = 1.hours();
+
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) + a);
+ ben.iter(|| datetime!(2019-12-31 0:00 UTC) + b);
+ ben.iter(|| datetime!(2019-12-31 23:59:59 UTC) + c);
+ ben.iter(|| datetime!(2020-01-01 0:00:01 UTC) + d);
+ ben.iter(|| datetime!(1999-12-31 23:00 UTC) + e);
+ }
+
+ fn add_std_duration(ben: &mut Bencher<'_>) {
+ let a = 5.std_days();
+ let b = 1.std_days();
+ let c = 2.std_seconds();
+
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) + a);
+ ben.iter(|| datetime!(2019-12-31 0:00 UTC) + b);
+ ben.iter(|| datetime!(2019-12-31 23:59:59 UTC) + c);
+ }
+
+ fn add_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00 UTC),
+ [
+ |datetime| *datetime += a,
+ |datetime| *datetime += b,
+ ]
+ );
+ }
+
+ fn add_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_days();
+ let b = 1.std_seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00 UTC),
+ [
+ |datetime| *datetime += a,
+ |datetime| *datetime += b,
+ ]
+ );
+ }
+
+ fn sub_duration(ben: &mut Bencher<'_>) {
+ let a = 5.days();
+ let b = 1.days();
+ let c = 2.seconds();
+
+ ben.iter(|| datetime!(2019-01-06 0:00 UTC) - a);
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC) - b);
+ ben.iter(|| datetime!(2020-01-01 0:00:01 UTC) - c);
+ }
+
+ fn sub_std_duration(ben: &mut Bencher<'_>) {
+ let a = 5.std_days();
+ let b = 1.std_days();
+ let c = 2.std_seconds();
+
+ ben.iter(|| datetime!(2019-01-06 0:00 UTC) - a);
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC) - b);
+ ben.iter(|| datetime!(2020-01-01 0:00:01 UTC) - c);
+ }
+
+ fn sub_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00 UTC),
+ [
+ |datetime| *datetime -= a,
+ |datetime| *datetime -= b,
+ ]
+ );
+ }
+
+ fn sub_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_days();
+ let b = 1.std_seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00 UTC),
+ [
+ |datetime| *datetime -= a,
+ |datetime| *datetime -= b,
+ ]
+ );
+ }
+
+ fn std_add_duration(ben: &mut Bencher<'_>) {
+ let a1 = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let a2 = 0.seconds();
+ let b1 = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let b2 = 5.days();
+ let c1 = SystemTime::from(datetime!(2019-12-31 0:00 UTC));
+ let c2 = 1.days();
+ let d1 = SystemTime::from(datetime!(2019-12-31 23:59:59 UTC));
+ let d2 = 2.seconds();
+ let e1 = SystemTime::from(datetime!(2020-01-01 0:00:01 UTC));
+ let e2 = (-2).seconds();
+ ben.iter(|| a1 + a2);
+ ben.iter(|| b1 + b2);
+ ben.iter(|| c1 + c2);
+ ben.iter(|| d1 + d2);
+ ben.iter(|| e1 + e2);
+ }
+
+ fn std_add_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || SystemTime::from(datetime!(2019-01-01 0:00 UTC)),
+ [
+ |datetime| *datetime += a,
+ |datetime| *datetime += b,
+ ]
+ );
+ }
+
+ fn std_sub_duration(ben: &mut Bencher<'_>) {
+ let a1 = SystemTime::from(datetime!(2019-01-06 0:00 UTC));
+ let a2 = 5.days();
+ let b1 = SystemTime::from(datetime!(2020-01-01 0:00 UTC));
+ let b2 = 1.days();
+ let c1 = SystemTime::from(datetime!(2020-01-01 0:00:01 UTC));
+ let c2 = 2.seconds();
+ let d1 = SystemTime::from(datetime!(2019-12-31 23:59:59 UTC));
+ let d2 = (-2).seconds();
+ ben.iter(|| a1 - a2);
+ ben.iter(|| b1 - b2);
+ ben.iter(|| c1 - c2);
+ ben.iter(|| d1 - d2);
+ }
+
+ fn std_sub_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || SystemTime::from(datetime!(2019-01-01 0:00 UTC)),
+ [
+ |datetime| *datetime -= a,
+ |datetime| *datetime -= b,
+ ]
+ );
+ }
+
+ fn sub_self(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-02 0:00 UTC) - datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) - datetime!(2019-01-02 0:00 UTC));
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC) - datetime!(2019-12-31 0:00 UTC));
+ ben.iter(|| datetime!(2019-12-31 0:00 UTC) - datetime!(2020-01-01 0:00 UTC));
+ }
+
+ fn std_sub(ben: &mut Bencher<'_>) {
+ let a = SystemTime::from(datetime!(2019-01-02 0:00 UTC));
+ let b = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let c = SystemTime::from(datetime!(2020-01-01 0:00 UTC));
+ let d = SystemTime::from(datetime!(2019-12-31 0:00 UTC));
+
+ ben.iter(|| a - datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| b - datetime!(2019-01-02 0:00 UTC));
+ ben.iter(|| c - datetime!(2019-12-31 0:00 UTC));
+ ben.iter(|| d - datetime!(2020-01-01 0:00 UTC));
+ }
+
+ fn sub_std(ben: &mut Bencher<'_>) {
+ let a = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let b = SystemTime::from(datetime!(2019-01-02 0:00 UTC));
+ let c = SystemTime::from(datetime!(2019-12-31 0:00 UTC));
+ let d = SystemTime::from(datetime!(2020-01-01 0:00 UTC));
+
+ ben.iter(|| datetime!(2019-01-02 0:00 UTC) - a);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) - b);
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC) - c);
+ ben.iter(|| datetime!(2019-12-31 0:00 UTC) - d);
+ }
+
+ fn eq_std(ben: &mut Bencher<'_>) {
+ let a = OffsetDateTime::now_utc();
+ let b = SystemTime::from(a);
+ ben.iter(|| a == b);
+ }
+
+ fn std_eq(ben: &mut Bencher<'_>) {
+ let a = OffsetDateTime::now_utc();
+ let b = SystemTime::from(a);
+ ben.iter(|| b == a);
+ }
+
+ fn ord_std(ben: &mut Bencher<'_>) {
+ let a = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let b = SystemTime::from(datetime!(2020-01-01 0:00 UTC));
+ let c = SystemTime::from(datetime!(2019-02-01 0:00 UTC));
+ let d = SystemTime::from(datetime!(2019-01-02 0:00 UTC));
+ let e = SystemTime::from(datetime!(2019-01-01 1:00:00 UTC));
+ let f = SystemTime::from(datetime!(2019-01-01 0:01:00 UTC));
+ let g = SystemTime::from(datetime!(2019-01-01 0:00:01 UTC));
+ let h = SystemTime::from(datetime!(2019-01-01 0:00:00.001 UTC));
+ let i = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let j = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let k = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let l = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let m = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let n = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let o = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) == a);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < b);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < c);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < d);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < e);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < f);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < g);
+ ben.iter(|| datetime!(2019-01-01 0:00 UTC) < h);
+ ben.iter(|| datetime!(2020-01-01 0:00 UTC) > i);
+ ben.iter(|| datetime!(2019-02-01 0:00 UTC) > j);
+ ben.iter(|| datetime!(2019-01-02 0:00 UTC) > k);
+ ben.iter(|| datetime!(2019-01-01 1:00:00 UTC) > l);
+ ben.iter(|| datetime!(2019-01-01 0:01:00 UTC) > m);
+ ben.iter(|| datetime!(2019-01-01 0:00:01 UTC) > n);
+ ben.iter(|| datetime!(2019-01-01 0:00:00.000_000_001 UTC) > o);
+ }
+
+ fn std_ord(ben: &mut Bencher<'_>) {
+ let a = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let b = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let c = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let d = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let e = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let f = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let g = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let h = SystemTime::from(datetime!(2019-01-01 0:00 UTC));
+ let i = SystemTime::from(datetime!(2020-01-01 0:00 UTC));
+ let j = SystemTime::from(datetime!(2019-02-01 0:00 UTC));
+ let k = SystemTime::from(datetime!(2019-01-02 0:00 UTC));
+ let l = SystemTime::from(datetime!(2019-01-01 1:00:00 UTC));
+ let m = SystemTime::from(datetime!(2019-01-01 0:01:00 UTC));
+ let n = SystemTime::from(datetime!(2019-01-01 0:00:01 UTC));
+ let o = SystemTime::from(datetime!(2019-01-01 0:00:00.001 UTC));
+
+ ben.iter(|| a == datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| b < datetime!(2020-01-01 0:00 UTC));
+ ben.iter(|| c < datetime!(2019-02-01 0:00 UTC));
+ ben.iter(|| d < datetime!(2019-01-02 0:00 UTC));
+ ben.iter(|| e < datetime!(2019-01-01 1:00:00 UTC));
+ ben.iter(|| f < datetime!(2019-01-01 0:01:00 UTC));
+ ben.iter(|| g < datetime!(2019-01-01 0:00:01 UTC));
+ ben.iter(|| h < datetime!(2019-01-01 0:00:00.000_000_001 UTC));
+ ben.iter(|| i > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| j > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| k > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| l > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| m > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| n > datetime!(2019-01-01 0:00 UTC));
+ ben.iter(|| o > datetime!(2019-01-01 0:00 UTC));
+ }
+
+ fn from_std(ben: &mut Bencher<'_>) {
+ let a = SystemTime::UNIX_EPOCH;
+ let b = SystemTime::UNIX_EPOCH - 1.std_days();
+ let c = SystemTime::UNIX_EPOCH + 1.std_days();
+ ben.iter(|| OffsetDateTime::from(a));
+ ben.iter(|| OffsetDateTime::from(b));
+ ben.iter(|| OffsetDateTime::from(c));
+ }
+
+ fn to_std(ben: &mut Bencher<'_>) {
+ let a = OffsetDateTime::UNIX_EPOCH;
+ let b = OffsetDateTime::UNIX_EPOCH + 1.days();
+ let c = OffsetDateTime::UNIX_EPOCH - 1.days();
+ ben.iter(|| SystemTime::from(a));
+ ben.iter(|| SystemTime::from(b));
+ ben.iter(|| SystemTime::from(c));
+ }
+}
### external/vendor/time/benchmarks/parse_format_description.rs
@@ -0,0 +1,27 @@
+use std::hint::black_box;
+
+use criterion::Bencher;
+use time::format_description;
+
+const FORMAT_DESCRIPTION: &str =
+ "[year]-[month]-[day]T[hour]:[minute]:[second].[subsecond digits:3]";
+
+setup_benchmark! {
+ "Parse format description",
+
+ fn parse_borrowed_v2(ben: &mut Bencher<'_>) {
+ ben.iter(|| format_description::parse_borrowed::<2>(black_box(FORMAT_DESCRIPTION)));
+ }
+
+ fn parse_borrowed_v3(ben: &mut Bencher<'_>) {
+ ben.iter(|| format_description::parse_borrowed::<3>(black_box(FORMAT_DESCRIPTION)));
+ }
+
+ fn parse_owned_v2(ben: &mut Bencher<'_>) {
+ ben.iter(|| format_description::parse_owned::<2>(black_box(FORMAT_DESCRIPTION)));
+ }
+
+ fn parse_owned_v3(ben: &mut Bencher<'_>) {
+ ben.iter(|| format_description::parse_owned::<3>(black_box(FORMAT_DESCRIPTION)));
+ }
+}
### external/vendor/time/benchmarks/parsing.rs
@@ -0,0 +1,216 @@
+use criterion::Bencher;
+use time::OffsetDateTime;
+use time::format_description::well_known::{Rfc2822, Rfc3339};
+use time::format_description::{Component, modifier};
+use time::parsing::Parsed;
+
+macro_rules! component {
+ ($name:ident {$($field:ident : $value:expr),* $(,)? }) => {{
+ const COMPONENT: Component = Component::$name({
+ #[allow(unused_mut, reason = "macro-generated code")]
+ let mut modifier = modifier::$name::default();
+ $(modifier.$field = $value;)*
+ modifier
+ });
+ COMPONENT
+ }};
+}
+
+setup_benchmark! {
+ "Parsing",
+
+ fn parse_component_year(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(b"2021", Component::CalendarYearFullStandardRange(
+ modifier::CalendarYearFullStandardRange::default()
+ .with_padding(modifier::Padding::Zero)
+ .with_sign_is_mandatory(false)
+ ))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"21", Component::CalendarYearLastTwo(
+ modifier::CalendarYearLastTwo::default().with_padding(modifier::Padding::Zero)
+ ))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"2021", Component::IsoYearFullStandardRange(
+ modifier::IsoYearFullStandardRange::default()
+ .with_padding(modifier::Padding::Zero)
+ .with_sign_is_mandatory(false)
+ ))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"21", Component::IsoYearLastTwo(
+ modifier::IsoYearLastTwo::default().with_padding(modifier::Padding::Zero)
+ ))
+ });
+ }
+
+ fn parse_component_month(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(b" 1", Component::MonthNumerical(
+ modifier::MonthNumerical::default().with_padding(modifier::Padding::Space)
+ ))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"Jan", Component::MonthShort(
+ modifier::MonthShort::default().with_case_sensitive(true)
+ ))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"January", Component::MonthLong(
+ modifier::MonthLong::default().with_case_sensitive(true)
+ ))
+ });
+ }
+
+ fn parse_component_ordinal(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(b"012", component!(Ordinal {
+ padding: modifier::Padding::Zero,
+ }))
+ });
+ }
+
+ fn parse_component_weekday(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(
+ b"Sun",
+ Component::WeekdayShort(modifier::WeekdayShort::default())
+ )
+ });
+ ben.iter(|| {
+ parsed.parse_component(
+ b"Sunday",
+ Component::WeekdayLong(modifier::WeekdayLong::default())
+ )
+ });
+ ben.iter(|| {
+ parsed.parse_component(
+ b"0",
+ Component::WeekdaySunday(modifier::WeekdaySunday::default().with_one_indexed(false))
+ )
+ });
+ ben.iter(|| {
+ parsed.parse_component(
+ b"1",
+ Component::WeekdaySunday(modifier::WeekdaySunday::default().with_one_indexed(true))
+ )
+ });
+ ben.iter(|| {
+ parsed.parse_component(
+ b"6",
+ Component::WeekdayMonday(modifier::WeekdayMonday::default().with_one_indexed(false))
+ )
+ });
+ ben.iter(|| {
+ parsed.parse_component(
+ b"7",
+ Component::WeekdayMonday(modifier::WeekdayMonday::default().with_one_indexed(true))
+ )
+ });
+ }
+
+ fn parse_component_week_number(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(b"2", component!(WeekNumberSunday {
+ padding: modifier::Padding::None,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"2", component!(WeekNumberMonday {
+ padding: modifier::Padding::None,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"2", component!(WeekNumberIso {
+ padding: modifier::Padding::None,
+ }))
+ });
+ }
+
+ fn parse_component_subsecond(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| {
+ parsed.parse_component(b"1", component!(Subsecond {
+ digits: modifier::SubsecondDigits::One,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"12", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Two,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"123", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Three,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"1234", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Four,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"12345", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Five,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"123456", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Six,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"1234567", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Seven,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"12345678", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Eight,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"123456789", component!(Subsecond {
+ digits: modifier::SubsecondDigits::Nine,
+ }))
+ });
+ ben.iter(|| {
+ parsed.parse_component(b"123456789", component!(Subsecond {
+ digits: modifier::SubsecondDigits::OneOrMore,
+ }))
+ });
+ }
+
+ fn parse_component_unix_timestamp(ben: &mut Bencher<'_>) {
+ let mut parsed = Parsed::new();
+ ben.iter(|| parsed.parse_component(std::hint::black_box(b"1234567890"), component!(UnixTimestampSecond {})));
+ }
+
+ fn parse_rfc3339(ben: &mut Bencher<'_>) {
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.1Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.12Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.123Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.1234Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.12345Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.123456Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.1234567Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.12345678Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.123456789Z", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.123456789-01:02", &Rfc3339));
+ ben.iter(|| OffsetDateTime::parse("2021-01-02T03:04:05.123456789+01:02", &Rfc3339));
+ }
+
+ fn parse_rfc2822(ben: &mut Bencher<'_>) {
+ ben.iter(|| OffsetDateTime::parse("Sat, 02 Jan 2021 03:04:05 +0000", &Rfc2822));
+ ben.iter(|| OffsetDateTime::parse("Sat, 02 Jan 2021 03:04:05 +0607", &Rfc2822));
+ ben.iter(|| OffsetDateTime::parse("Sat, 02 Jan 2021 03:04:05 -0607", &Rfc2822));
+ }
+}
### external/vendor/time/benchmarks/plain_date_time.rs
@@ -0,0 +1,148 @@
+use criterion::Bencher;
+use time::ext::{NumericalDuration, NumericalStdDuration};
+use time::macros::{datetime, offset};
+
+setup_benchmark! {
+ "PlainDateTime",
+
+ // All getters are trivially dispatched to the relevant field, and do not need to be benchmarked
+ // a second time.
+
+ fn assume_offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00).assume_offset(offset!(UTC)));
+ ben.iter(|| datetime!(2019-01-01 0:00).assume_offset(offset!(-1)));
+ }
+
+ fn assume_utc(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00).assume_utc());
+ }
+
+ fn add_duration(ben: &mut Bencher<'_>) {
+ let a = 5.days();
+ let b = 1.days();
+ let c = 2.seconds();
+ let d = (-2).seconds();
+ let e = 1.hours();
+
+ ben.iter(|| datetime!(2019-01-01 0:00) + a);
+ ben.iter(|| datetime!(2019-12-31 0:00) + b);
+ ben.iter(|| datetime!(2019-12-31 23:59:59) + c);
+ ben.iter(|| datetime!(2020-01-01 0:00:01) + d);
+ ben.iter(|| datetime!(1999-12-31 23:00) + e);
+ }
+
+ fn add_std_duration(ben: &mut Bencher<'_>) {
+ let a = 5.std_days();
+ let b = 1.std_days();
+ let c = 2.std_seconds();
+
+ ben.iter(|| datetime!(2019-01-01 0:00) + a);
+ ben.iter(|| datetime!(2019-12-31 0:00) + b);
+ ben.iter(|| datetime!(2019-12-31 23:59:59) + c);
+ }
+
+ fn add_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00),
+ [
+ |datetime| *datetime += a,
+ |datetime| *datetime += b,
+ ]
+ );
+ }
+
+ fn add_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_days();
+ let b = 1.std_seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00),
+ [
+ |datetime| *datetime += a,
+ |datetime| *datetime += b,
+ ]
+ );
+ }
+
+ fn sub_duration(ben: &mut Bencher<'_>) {
+ let a = 5.days();
+ let b = 1.days();
+ let c = 2.seconds();
+ let d = (-2).seconds();
+ let e = (-1).hours();
+
+ ben.iter(|| datetime!(2019-01-06 0:00) - a);
+ ben.iter(|| datetime!(2020-01-01 0:00) - b);
+ ben.iter(|| datetime!(2020-01-01 0:00:01) - c);
+ ben.iter(|| datetime!(2019-12-31 23:59:59) - d);
+ ben.iter(|| datetime!(1999-12-31 23:00) - e);
+ }
+
+ fn sub_std_duration(ben: &mut Bencher<'_>) {
+ let a = 5.std_days();
+ let b = 1.std_days();
+ let c = 2.std_seconds();
+
+ ben.iter(|| datetime!(2019-01-06 0:00) - a);
+ ben.iter(|| datetime!(2020-01-01 0:00) - b);
+ ben.iter(|| datetime!(2020-01-01 0:00:01) - c);
+ }
+
+ fn sub_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.days();
+ let b = 1.seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00),
+ [
+ |datetime| *datetime -= a,
+ |datetime| *datetime -= b,
+ ]
+ );
+ }
+
+ fn sub_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_days();
+ let b = 1.std_seconds();
+ iter_batched_ref!(
+ ben,
+ || datetime!(2019-01-01 0:00),
+ [
+ |datetime| *datetime -= a,
+ |datetime| *datetime -= b,
+ ]
+ );
+ }
+
+ fn sub_datetime(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-02 0:00) - datetime!(2019-01-01 0:00));
+ ben.iter(|| datetime!(2019-01-01 0:00) - datetime!(2019-01-02 0:00));
+ ben.iter(|| datetime!(2020-01-01 0:00) - datetime!(2019-12-31 0:00));
+ ben.iter(|| datetime!(2019-12-31 0:00) - datetime!(2020-01-01 0:00));
+ }
+
+ fn ord(ben: &mut Bencher<'_>) {
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2020-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-02-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-02 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-01 1:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-01 0:01)));
+ ben.iter(|| datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-01 0:00:01)));
+ ben.iter(||
+ datetime!(2019-01-01 0:00).partial_cmp(&datetime!(2019-01-01 0:00:00.000_000_001))
+ );
+ ben.iter(|| datetime!(2020-01-01 0:00).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-02-01 0:00).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-02 0:00).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 1:00).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:01).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(|| datetime!(2019-01-01 0:00:01).partial_cmp(&datetime!(2019-01-01 0:00)));
+ ben.iter(||
+ datetime!(2019-01-01 0:00:00.000_000_001).partial_cmp(&datetime!(2019-01-01 0:00))
+ );
+ }
+}
### external/vendor/time/benchmarks/rand08.rs
@@ -0,0 +1,30 @@
+use criterion::Bencher;
+use rand08::Rng;
+use rand08::rngs::mock::StepRng;
+use time::{Date, Month, OffsetDateTime, PlainDateTime, SignedDuration, Time, UtcOffset, Weekday};
+
+macro_rules! bench_rand {
+ ($($name:ident : $type:ty),* $(,)?) => {
+ setup_benchmark! {
+ "Random",
+ $(fn $name(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || StepRng::new(0, 1),
+ [|rng| rng.r#gen::<$type>()]
+ );
+ })*
+ }
+ }
+}
+
+bench_rand![
+ time: Time,
+ date: Date,
+ utc_offset: UtcOffset,
+ plain_date_time: PlainDateTime,
+ offset_date_time: OffsetDateTime,
+ duration: SignedDuration,
+ weekday: Weekday,
+ month: Month,
+];
### external/vendor/time/benchmarks/rand09.rs
@@ -0,0 +1,61 @@
+use criterion::Bencher;
+use rand09::Rng;
+use time::{Date, Month, OffsetDateTime, PlainDateTime, SignedDuration, Time, UtcOffset, Weekday};
+
+macro_rules! bench_rand {
+ ($($name:ident : $type:ty),* $(,)?) => {
+ setup_benchmark! {
+ "Random",
+ $(fn $name(ben: &mut Bencher<'_>) {
+ iter_batched_ref!(
+ ben,
+ || StepRng::new(0, 1),
+ [|rng| rng.random::<$type>()]
+ );
+ })*
+ }
+ }
+}
+
+bench_rand![
+ time: Time,
+ date: Date,
+ utc_offset: UtcOffset,
+ plain_date_time: PlainDateTime,
+ offset_date_time: OffsetDateTime,
+ duration: SignedDuration,
+ weekday: Weekday,
+ month: Month,
+];
+
+// copy of `StepRng` from rand 0.8 to avoid deprecation warnings
+#[derive(Debug, Clone)]
+struct StepRng {
+ v: u64,
+ a: u64,
+}
+
+impl StepRng {
+ const fn new(initial: u64, increment: u64) -> Self {
+ Self {
+ v: initial,
+ a: increment,
+ }
+ }
+}
+
+impl rand09::RngCore for StepRng {
+ fn next_u32(&mut self) -> u32 {
+ self.next_u64() as u32
+ }
+
+ fn next_u64(&mut self) -> u64 {
+ let res = self.v;
+ self.v = self.v.wrapping_add(self.a);
+ res
+ }
+
+ fn fill_bytes(&mut self, dst: &mut [u8]) {
+ rand09::rand_core::impls::fill_bytes_via_next(self, dst)
+ }
+}
### external/vendor/time/benchmarks/time.rs
@@ -0,0 +1,271 @@
+use std::hint::black_box;
+
+use criterion::Bencher;
+use time::Time;
+use time::ext::{NumericalDuration, NumericalStdDuration};
+use time::macros::time;
+
+setup_benchmark! {
+ "Time",
+
+ fn from_hms(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::from_hms(1, 2, 3));
+ }
+
+ fn from_hms_milli(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::from_hms_milli(1, 2, 3, 4));
+ }
+
+ fn from_hms_micro(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::from_hms_micro(1, 2, 3, 4));
+ }
+
+ fn from_hms_nano(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::from_hms_nano(1, 2, 3, 4));
+ }
+
+ fn as_hms(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.as_hms());
+ }
+
+ fn as_hms_milli(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.as_hms_milli());
+ }
+
+ fn as_hms_micro(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.as_hms_micro());
+ }
+
+ fn as_hms_nano(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.as_hms_nano());
+ }
+
+ fn hour(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.hour());
+ }
+
+ fn minute(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.minute());
+ }
+
+ fn second(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.second());
+ }
+
+ fn millisecond(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.millisecond());
+ }
+
+ fn microsecond(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.microsecond());
+ }
+
+ fn nanosecond(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT.nanosecond());
+ }
+
+ fn add_duration(ben: &mut Bencher<'_>) {
+ let a = 1.milliseconds();
+ let b = 1.seconds();
+ let c = 1.minutes();
+ let d = 1.hours();
+ let e = 1.days();
+ ben.iter(|| Time::MIDNIGHT + a);
+ ben.iter(|| Time::MIDNIGHT + b);
+ ben.iter(|| Time::MIDNIGHT + c);
+ ben.iter(|| Time::MIDNIGHT + d);
+ ben.iter(|| Time::MIDNIGHT + e);
+ }
+
+ fn add_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.milliseconds();
+ let b = 1.seconds();
+ let c = 1.minutes();
+ let d = 1.hours();
+ let e = 1.days();
+ iter_batched_ref!(
+ ben,
+ || Time::MIDNIGHT,
+ [
+ |time| *time += a,
+ |time| *time += b,
+ |time| *time += c,
+ |time| *time += d,
+ |time| *time += e,
+ ]
+ );
+ }
+
+ fn sub_duration(ben: &mut Bencher<'_>) {
+ let a = 1.milliseconds();
+ let b = 1.seconds();
+ let c = 1.minutes();
+ let d = 1.hours();
+ let e = 1.days();
+ ben.iter(|| Time::MIDNIGHT - a);
+ ben.iter(|| Time::MIDNIGHT - b);
+ ben.iter(|| Time::MIDNIGHT - c);
+ ben.iter(|| Time::MIDNIGHT - d);
+ ben.iter(|| Time::MIDNIGHT - e);
+ }
+
+ fn sub_assign_duration(ben: &mut Bencher<'_>) {
+ let a = 1.milliseconds();
+ let b = 1.seconds();
+ let c = 1.minutes();
+ let d = 1.hours();
+ let e = 1.days();
+ iter_batched_ref!(
+ ben,
+ || Time::MIDNIGHT,
+ [
+ |time| *time -= a,
+ |time| *time -= b,
+ |time| *time -= c,
+ |time| *time -= d,
+ |time| *time -= e,
+ ]
+ );
+ }
+
+ fn add_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_milliseconds();
+ let b = 1.std_seconds();
+ let c = 1.std_minutes();
+ let d = 1.std_hours();
+ let e = 1.std_days();
+ ben.iter(|| Time::MIDNIGHT + a);
+ ben.iter(|| Time::MIDNIGHT + b);
+ ben.iter(|| Time::MIDNIGHT + c);
+ ben.iter(|| Time::MIDNIGHT + d);
+ ben.iter(|| Time::MIDNIGHT + e);
+ }
+
+ fn add_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_milliseconds();
+ let b = 1.std_seconds();
+ let c = 1.std_minutes();
+ let d = 1.std_hours();
+ let e = 1.std_days();
+ iter_batched_ref!(
+ ben,
+ || Time::MIDNIGHT,
+ [
+ |time| *time += a,
+ |time| *time += b,
+ |time| *time += c,
+ |time| *time += d,
+ |time| *time += e,
+ ]
+ );
+ }
+
+ fn sub_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_milliseconds();
+ let b = 1.std_seconds();
+ let c = 1.std_minutes();
+ let d = 1.std_hours();
+ let e = 1.std_days();
+ ben.iter(|| Time::MIDNIGHT - a);
+ ben.iter(|| Time::MIDNIGHT - b);
+ ben.iter(|| Time::MIDNIGHT - c);
+ ben.iter(|| Time::MIDNIGHT - d);
+ ben.iter(|| Time::MIDNIGHT - e);
+ }
+
+ fn sub_assign_std_duration(ben: &mut Bencher<'_>) {
+ let a = 1.std_milliseconds();
+ let b = 1.std_seconds();
+ let c = 1.std_minutes();
+ let d = 1.std_hours();
+ let e = 1.std_days();
+ iter_batched_ref!(
+ ben,
+ || Time::MIDNIGHT,
+ [
+ |time| *time -= a,
+ |time| *time -= b,
+ |time| *time -= c,
+ |time| *time -= d,
+ |time| *time -= e,
+ ]
+ );
+ }
+
+ fn sub_time(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT - time!(0:00:01));
+ ben.iter(|| time!(1:00) - Time::MIDNIGHT);
+ ben.iter(|| time!(1:00) - time!(0:00:01));
+ }
+
+ fn ordering(ben: &mut Bencher<'_>) {
+ ben.iter(|| Time::MIDNIGHT < time!(0:00:00.000_000_001));
+ ben.iter(|| Time::MIDNIGHT < time!(0:00:01));
+ ben.iter(|| time!(12:00) > time!(11:00));
+ ben.iter(|| Time::MIDNIGHT == time!(0:00:00.000_000_001));
+ }
+
+ fn sort_align_8(ben: &mut Bencher<'_>) {
+ ben.iter_batched_ref(
+ || {
+ #[repr(C,align(8))]
+ struct Padder {
+ arr: [Time;4096],
+ }
+ let mut res = Padder {
+ arr: [Time::MIDNIGHT;4096]
+ };
+ let mut last = Time::MIDNIGHT;
+ let mut last_hour = 0;
+ for t in &mut res.arr {
+ *t = last;
+ t.replace_hour(last_hour).expect("failed to replace hour");
+ last += 997.std_milliseconds();
+ last_hour = (last_hour + 5) % 24;
+ }
+ res.arr.sort_unstable_by_key(|t|
+ (t.nanosecond(),t.second(),t.minute(),t.hour())
+ );
+ res
+ },
+ |v| black_box(v).arr.sort_unstable(),
+ criterion::BatchSize::SmallInput
+ )
+ }
+
+ fn sort_align_4(ben: &mut Bencher<'_>) {
+ ben.iter_batched_ref(
+ || {
+ #[repr(C,align(8))]
+ struct Padder {
+ pad: u32,
+ arr: [Time;4096],
+ }
+ let mut res = Padder {
+ pad: 0,
+ arr: [Time::MIDNIGHT;4096]
+ };
+ let mut last = Time::MIDNIGHT;
+ let mut last_hour = 0;
+ for t in &mut res.arr {
+ *t = last;
+ t.replace_hour(last_hour).expect("failed to replace hour");
+ last += 997.std_milliseconds();
+ last_hour = (last_hour + 5) % 24;
+ }
+ res.arr.sort_unstable_by_key(|t|
+ (t.nanosecond(),t.second(),t.minute(),t.hour())
+ );
+ res
+ },
+ |v| black_box(v).arr.sort_unstable(),
+ criterion::BatchSize::SmallInput
+ )
+ }
+
+ fn duration_until(ben: &mut Bencher<'_>) {
+ let a = black_box(time!(1:02:03.004_005_006));
+ let b = black_box(time!(4:05:06.007_008_009));
+ ben.iter(|| black_box(a.duration_until(b)));
+ }
+}
### external/vendor/time/benchmarks/utc_date_time.rs
@@ -0,0 +1,12 @@
+use std::hint::black_box;
+
+use criterion::Bencher;
+use time::macros::{offset, utc_datetime};
+
+setup_benchmark! {
+ "UtcDateTime",
+
+ fn to_offset(ben: &mut Bencher<'_>) {
+ ben.iter(|| black_box(utc_datetime!(2000-01-01 0:00)).to_offset(black_box(offset!(-5))));
+ }
+}
### external/vendor/time/benchmarks/utc_offset.rs
@@ -0,0 +1,58 @@
+use criterion::Bencher;
+use time::{OffsetDateTime, UtcOffset};
+
+setup_benchmark! {
+ "UtcOffset",
+
+ fn from_hms(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::from_hms(0, 0, 0));
+ }
+
+ fn from_whole_seconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::from_whole_seconds(0));
+ }
+
+ fn as_hms(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.as_hms());
+ }
+
+ fn whole_hours(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.whole_hours());
+ }
+
+ fn whole_minutes(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.whole_minutes());
+ }
+
+ fn minutes_past_hour(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.minutes_past_hour());
+ }
+
+ fn whole_seconds(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.whole_seconds());
+ }
+
+ fn seconds_past_minute(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.seconds_past_minute());
+ }
+
+ fn is_utc(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.is_utc());
+ }
+
+ fn is_positive(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.is_positive());
+ }
+
+ fn is_negative(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::UTC.is_negative());
+ }
+
+ fn local_offset_at(ben: &mut Bencher<'_>) {
+ ben.iter(|| UtcOffset::local_offset_at(OffsetDateTime::UNIX_EPOCH));
+ }
+
+ fn current_local_offset(ben: &mut Bencher<'_>) {
+ ben.iter(UtcOffset::current_local_offset);
+ }
+}
### external/vendor/time/benchmarks/util.rs
@@ -0,0 +1,54 @@
+use std::hint::black_box as bb;
+use std::sync::LazyLock;
+
+use criterion::Bencher;
+use time::util;
+
+/// Generate a representative sample of all years.
+fn representative_years() -> [i32; 800] {
+ static DATES: LazyLock<[i32; 800]> = LazyLock::new(|| {
+ let mut years = [0; _];
+ for year in -400..400 {
+ years[(year + 400) as usize] = year;
+ }
+ crate::shuffle(years)
+ });
+
+ *DATES
+}
+
+setup_benchmark! {
+ "Utils",
+
+ fn noop(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for i in representative_years() {
+ let _ = bb(i);
+ }
+ });
+ }
+
+ fn is_leap_year(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for year in representative_years() {
+ let _ = bb(util::is_leap_year(bb(year)));
+ }
+ });
+ }
+
+ fn days_in_year(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for year in representative_years() {
+ let _ = bb(util::days_in_year(bb(year)));
+ }
+ });
+ }
+
+ fn weeks_in_year(ben: &mut Bencher<'_>) {
+ ben.iter(|| {
+ for year in representative_years() {
+ let _ = bb(util::weeks_in_year(bb(year)));
+ }
+ });
+ }
+}
### external/vendor/time/benchmarks/weekday.rs
@@ -0,0 +1,81 @@
+use criterion::Bencher;
+use time::Weekday::*;
+
+setup_benchmark! {
+ "Weekday",
+
+ fn previous(ben: &mut Bencher<'_>) {
+ ben.iter(|| Sunday.previous());
+ ben.iter(|| Monday.previous());
+ ben.iter(|| Tuesday.previous());
+ ben.iter(|| Wednesday.previous());
+ ben.iter(|| Thursday.previous());
+ ben.iter(|| Friday.previous());
+ ben.iter(|| Saturday.previous());
+ }
+
+ fn next(ben: &mut Bencher<'_>) {
+ ben.iter(|| Sunday.next());
+ ben.iter(|| Monday.next());
+ ben.iter(|| Tuesday.next());
+ ben.iter(|| Wednesday.next());
+ ben.iter(|| Thursday.next());
+ ben.iter(|| Friday.next());
+ ben.iter(|| Saturday.next());
+ }
+
+ fn nth(ben: &mut Bencher<'_>) {
+ ben.iter(|| Sunday.nth_next(0));
+ ben.iter(|| Sunday.nth_next(1));
+ ben.iter(|| Sunday.nth_next(2));
+ ben.iter(|| Sunday.nth_next(3));
+ ben.iter(|| Sunday.nth_next(4));
+ ben.iter(|| Sunday.nth_next(5));
+ ben.iter(|| Sunday.nth_next(6));
+
+ ben.iter(|| Sunday.nth_next(7));
+ ben.iter(|| Sunday.nth_next(u8::MAX));
+ ben.iter(|| Monday.nth_next(7));
+ ben.iter(|| Monday.nth_next(u8::MAX));
+ }
+
+ fn number_from_monday(ben: &mut Bencher<'_>) {
+ ben.iter(|| Monday.number_from_monday());
+ ben.iter(|| Tuesday.number_from_monday());
+ ben.iter(|| Wednesday.number_from_monday());
+ ben.iter(|| Thursday.number_from_monday());
+ ben.iter(|| Friday.number_from_monday());
+ ben.iter(|| Saturday.number_from_monday());
+ ben.iter(|| Sunday.number_from_monday());
+ }
+
+ fn number_from_sunday(ben: &mut Bencher<'_>) {
+ ben.iter(|| Sunday.number_from_sunday());
+ ben.iter(|| Monday.number_from_sunday());
+ ben.iter(|| Tuesday.number_from_sunday());
+ ben.iter(|| Wednesday.number_from_sunday());
+ ben.iter(|| Thursday.number_from_sunday());
+ ben.iter(|| Friday.number_from_sunday());
+ ben.iter(|| Saturday.number_from_sunday());
+ }
+
+ fn number_days_from_monday(ben: &mut Bencher<'_>) {
+ ben.iter(|| Monday.number_days_from_monday());
+ ben.iter(|| Tuesday.number_days_from_monday());
+ ben.iter(|| Wednesday.number_days_from_monday());
+ ben.iter(|| Thursday.number_days_from_monday());
+ ben.iter(|| Friday.number_days_from_monday());
+ ben.iter(|| Saturday.number_days_from_monday());
+ ben.iter(|| Sunday.number_days_from_monday());
+ }
+
+ fn number_days_from_sunday(ben: &mut Bencher<'_>) {
+ ben.iter(|| Sunday.number_days_from_sunday());
+ ben.iter(|| Monday.number_days_from_sunday());
+ ben.iter(|| Tuesday.number_days_from_sunday());
+ ben.iter(|| Wednesday.number_days_from_sunday());
+ ben.iter(|| Thursday.number_days_from_sunday());
+ ben.iter(|| Friday.number_days_from_sunday());
+ ben.iter(|| Saturday.number_days_from_sunday());
+ }
+}
### external/vendor/time/src/date.rs
@@ -2,32 +2,32 @@
#[cfg(feature = "formatting")]
use alloc::string::String;
+use core::fmt;
+use core::mem::MaybeUninit;
use core::num::NonZero;
-use core::ops::{Add, Sub};
+use core::ops::{Add, AddAssign, Sub, SubAssign};
use core::time::Duration as StdDuration;
-use core::{cmp, fmt};
#[cfg(feature = "formatting")]
use std::io;
-use deranged::RangedI32;
+use deranged::{ri32, ru8, ru32};
use num_conv::prelude::*;
-use powerfmt::ext::FormatterExt;
-use powerfmt::smart_display::{self, FormatterOptions, Metadata, SmartDisplay};
+use powerfmt::smart_display::{FormatterOptions, Metadata, SmartDisplay};
-use crate::convert::*;
-use crate::ext::DigitCount;
+#[cfg(any(feature = "formatting", feature = "parsing"))]
+use crate::PrivateMethod;
#[cfg(feature = "formatting")]
use crate::formatting::Formattable;
-use crate::internal_macros::{
- const_try, const_try_opt, div_floor, ensure_ranged, expect_opt, impl_add_assign,
- impl_sub_assign,
-};
+use crate::internal_macros::{const_try, const_try_opt, div_floor, ensure_ranged};
+use crate::iter::DateIter;
+use crate::num_fmt::{four_to_six_digits, str_from_raw_parts, two_digits_zero_padded};
#[cfg(feature = "parsing")]
-use crate::parsing::Parsable;
-use crate::util::{days_in_year, is_leap_year, weeks_in_year};
-use crate::{error, Duration, Month, PrimitiveDateTime, Time, Weekday};
+use crate::parsing::{Parsable, Parsed};
+use crate::unit::*;
+use crate::util::{days_in_month_leap, range_validated, weeks_in_year};
+use crate::{Month, PlainDateTime, SignedDuration, Time, Weekday, error, hint};
-type Year = RangedI32<MIN_YEAR, MAX_YEAR>;
+type Year = ri32<MIN_YEAR, MAX_YEAR>;
/// The minimum valid year.
pub(crate) const MIN_YEAR: i32 = if cfg!(feature = "large-dates") {
@@ -83,8 +83,9 @@ impl Date {
///
/// The value of this may vary depending on the feature flags enabled.
// Safety: `ordinal` is not zero.
- pub const MAX: Self =
- unsafe { Self::__from_ordinal_date_unchecked(MAX_YEAR, days_in_year(MAX_YEAR)) };
+ pub const MAX: Self = unsafe {
+ Self::__from_ordinal_date_unchecked(MAX_YEAR, range_validated::days_in_year(MAX_YEAR))
+ };
/// Construct a `Date` from its internal representation, the validity of which must be
/// guaranteed by the caller.
@@ -95,12 +96,12 @@ impl Date {
/// - `is_leap_year` must be `true` if and only if `year` is a leap year
#[inline]
#[track_caller]
- const unsafe fn from_parts(year: i32, is_leap_year: bool, ordinal: u16) -> Self {
+ pub(crate) const unsafe fn from_parts(year: i32, is_leap_year: bool, ordinal: u16) -> Self {
debug_assert!(year >= MIN_YEAR);
debug_assert!(year <= MAX_YEAR);
debug_assert!(ordinal != 0);
- debug_assert!(ordinal <= days_in_year(year));
- debug_assert!(crate::util::is_leap_year(year) == is_leap_year);
+ debug_assert!(ordinal <= range_validated::days_in_year(year));
+ debug_assert!(range_validated::is_leap_year(year) == is_leap_year);
Self {
// Safety: `ordinal` is not zero.
@@ -115,14 +116,15 @@ impl Date {
///
/// # Safety
///
- /// `ordinal` must be non-zero and at most the number of days in `year`. `year` should be in the
- /// range `MIN_YEAR..=MAX_YEAR`, but this is not a safety invariant.
+ /// - `year` must be in the range `MIN_YEAR..=MAX_YEAR`.
+ /// - `ordinal` must be non-zero and at most the number of days in `year`.
#[doc(hidden)]
#[inline]
#[track_caller]
pub const unsafe fn __from_ordinal_date_unchecked(year: i32, ordinal: u16) -> Self {
- // Safety: The caller must guarantee that `ordinal` is not zero.
- unsafe { Self::from_parts(year, is_leap_year(year), ordinal) }
+ // Safety: The caller must guarantee that `ordinal` is not zero and that the year is in
+ // range.
+ unsafe { Self::from_parts(year, range_validated::is_leap_year(year), ordinal) }
}
/// Attempt to create a `Date` from the year, month, and day.
@@ -150,26 +152,23 @@ impl Date {
];
ensure_ranged!(Year: year);
+
+ let is_leap_year = range_validated::is_leap_year(year);
match day {
1..=28 => {}
- 29..=31 if day <= month.length(year) => {}
+ 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
_ => {
- return Err(error::ComponentRange {
- name: "day",
- minimum: 1,
- maximum: month.length(year) as i64,
- value: day as i64,
- conditional_message: Some("for the given month and year"),
- });
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("day"));
}
}
- // Safety: `ordinal` is not zero.
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
Ok(unsafe {
- Self::__from_ordinal_date_unchecked(
+ Self::from_parts(
year,
- DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year(year) as usize][month as usize - 1]
- + day as u16,
+ is_leap_year,
+ DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
)
})
}
@@ -189,22 +188,19 @@ impl Date {
#[inline]
pub const fn from_ordinal_date(year: i32, ordinal: u16) -> Result<Self, error::ComponentRange> {
ensure_ranged!(Year: year);
+
+ let is_leap_year = range_validated::is_leap_year(year);
match ordinal {
1..=365 => {}
- 366 if is_leap_year(year) => {}
+ 366 if is_leap_year => hint::cold_path(),
_ => {
- return Err(error::ComponentRange {
- name: "ordinal",
- minimum: 1,
- maximum: days_in_year(year) as i64,
- value: ordinal as i64,
- conditional_message: Some("for the given year"),
- });
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("ordinal"));
}
}
// Safety: `ordinal` is not zero.
- Ok(unsafe { Self::__from_ordinal_date_unchecked(year, ordinal) })
+ Ok(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
}
/// Attempt to create a `Date` from the ISO year, week, and weekday.
@@ -228,15 +224,10 @@ impl Date {
ensure_ranged!(Year: year);
match week {
1..=52 => {}
- 53 if week <= weeks_in_year(year) => {}
+ 53 if week <= weeks_in_year(year) => hint::cold_path(),
_ => {
- return Err(error::ComponentRange {
- name: "week",
- minimum: 1,
- maximum: weeks_in_year(year) as i64,
- value: week as i64,
- conditional_message: Some("for the given year"),
- });
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("week"));
}
}
@@ -254,42 +245,48 @@ impl Date {
};
let ordinal = week as i16 * 7 + weekday.number_from_monday() as i16 - jan_4;
- Ok(if ordinal <= 0 {
+ if ordinal <= 0 {
// Safety: `ordinal` is not zero.
- unsafe {
+ return Ok(unsafe {
Self::__from_ordinal_date_unchecked(
year - 1,
- (ordinal as u16).wrapping_add(days_in_year(year - 1)),
+ ordinal
+ .cast_unsigned()
+ .wrapping_add(range_validated::days_in_year(year - 1)),
)
+ });
+ }
+
+ let is_leap_year = range_validated::is_leap_year(year);
+ let days_in_year = if is_leap_year { 366 } else { 365 };
+ let ordinal = ordinal.cast_unsigned();
+ Ok(if ordinal > days_in_year {
+ // Issue #777
+ if hint::unlikely(year == MAX_YEAR) {
+ return Err(error::ComponentRange::conditional("weekday"));
}
- } else if ordinal > days_in_year(year) as i16 {
- // Safety: `ordinal` is not zero.
- unsafe {
- Self::__from_ordinal_date_unchecked(year + 1, ordinal as u16 - days_in_year(year))
- }
+ // Safety: the year is in range and `ordinal` is not zero.
+ unsafe { Self::__from_ordinal_date_unchecked(year + 1, ordinal - days_in_year) }
} else {
- // Safety: `ordinal` is not zero.
- unsafe { Self::__from_ordinal_date_unchecked(year, ordinal as u16) }
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
+ unsafe { Self::from_parts(year, is_leap_year, ordinal) }
})
}
/// Create a `Date` from the Julian day.
///
- /// The algorithm to perform this conversion is derived from one provided by Peter Baum; it is
- /// freely available [here](https://www.researchgate.net/publication/316558298_Date_Algorithms).
- ///
/// ```rust
/// # use time::Date;
/// # use time_macros::date;
- /// assert_eq!(Date::from_julian_day(0), Ok(date!(-4713 - 11 - 24)));
+ /// assert_eq!(Date::from_julian_day(0), Ok(date!(-4713-11-24)));
/// assert_eq!(Date::from_julian_day(2_451_545), Ok(date!(2000-01-01)));
/// assert_eq!(Date::from_julian_day(2_458_485), Ok(date!(2019-01-01)));
/// assert_eq!(Date::from_julian_day(2_458_849), Ok(date!(2019-12-31)));
/// ```
#[doc(alias = "from_julian_date")]
#[inline]
pub const fn from_julian_day(julian_day: i32) -> Result<Self, error::ComponentRange> {
- type JulianDay = RangedI32<{ Date::MIN.to_julian_day() }, { Date::MAX.to_julian_day() }>;
+ type JulianDay = ri32<{ Date::MIN.to_julian_day() }, { Date::MAX.to_julian_day() }>;
ensure_ranged!(JulianDay: julian_day);
// Safety: The Julian day number is in range.
Ok(unsafe { Self::from_julian_day_unchecked(julian_day) })
@@ -306,44 +303,41 @@ impl Date {
debug_assert!(julian_day >= Self::MIN.to_julian_day());
debug_assert!(julian_day <= Self::MAX.to_julian_day());
- const S: i32 = 2_500;
- const K: i32 = 719_468 + 146_097 * S;
- const L: i32 = 400 * S;
-
- let julian_day = julian_day - 2_440_588;
- let n = (julian_day + K) as u32;
-
- let n_1 = 4 * n + 3;
- let c = n_1 / 146_097;
- let n_c = n_1 % 146_097 / 4;
-
- let n_2 = 4 * n_c + 3;
- let p_2 = 2_939_745 * n_2 as u64;
- let z = (p_2 >> 32) as u32;
- let n_y = p_2 as u32 / 2_939_745 / 4;
- let y = 100 * c + z;
-
- let j = n_y >= 306;
- let y_g = y as i32 - L + j as i32;
-
- let is_leap_year = is_leap_year(y_g);
- let ordinal = if j {
- n_y - 305
- } else {
- n_y + 60 + is_leap_year as u32
- };
+ const ERAS: u32 = 5_949;
+ // Rata Die shift:
+ const D_SHIFT: u32 = 146097 * ERAS - 1_721_060;
+ // Year shift:
+ const Y_SHIFT: u32 = 400 * ERAS;
+
+ const CEN_MUL: u32 = ((4u64 << 47) / 146_097) as u32;
+ const JUL_MUL: u32 = ((4u64 << 40) / 1_461 + 1) as u32;
+ const CEN_CUT: u32 = ((365u64 << 32) / 36_525) as u32;
+
+ let day = julian_day.cast_unsigned().wrapping_add(D_SHIFT);
+ let c_n = (day as u64 * CEN_MUL as u64) >> 15;
+ let cen = (c_n >> 32) as u32;
+ let cpt = c_n as u32;
+ let ijy = cpt > CEN_CUT || cen.is_multiple_of(4);
+ let jul = day - cen / 4 + cen;
+ let y_n = (jul as u64 * JUL_MUL as u64) >> 8;
+ let yrs = (y_n >> 32) as u32;
+ let ypt = y_n as u32;
+
+ let year = yrs.wrapping_sub(Y_SHIFT).cast_signed();
+ let ordinal = ((ypt as u64 * 1_461) >> 34) as u32 + ijy as u32;
+ let leap = yrs.is_multiple_of(4) & ijy;
// Safety: `ordinal` is not zero and `is_leap_year` is correct, so long as the Julian day
- // number is in range.
- unsafe { Self::from_parts(y_g, is_leap_year, ordinal as u16) }
+ // number is in range, which is guaranteed by the caller.
+ unsafe { Self::from_parts(year, leap, ordinal as u16) }
}
/// Whether `is_leap_year(self.year())` is `true`.
///
/// This method is optimized to take advantage of the fact that the value is pre-computed upon
/// construction and stored in the bitpacked struct.
#[inline]
- const fn is_in_leap_year(self) -> bool {
+ pub(crate) const fn is_in_leap_year(self) -> bool {
(self.value.get() >> 9) & 1 == 1
}
@@ -473,7 +467,8 @@ impl Date {
/// ```
#[inline]
pub const fn sunday_based_week(self) -> u8 {
- ((self.ordinal() as i16 - self.weekday().number_days_from_sunday() as i16 + 6) / 7) as u8
+ ((self.ordinal().cast_signed() - self.weekday().number_days_from_sunday() as i16 + 6) / 7)
+ as u8
}
/// Get the week number where week 1 begins on the first Monday.
@@ -489,7 +484,8 @@ impl Date {
/// ```
#[inline]
pub const fn monday_based_week(self) -> u8 {
- ((self.ordinal() as i16 - self.weekday().number_days_from_monday() as i16 + 6) / 7) as u8
+ ((self.ordinal().cast_signed() - self.weekday().number_days_from_monday() as i16 + 6) / 7)
+ as u8
}
/// Get the year, month, and day.
@@ -613,18 +609,17 @@ impl Date {
/// ```
#[inline]
pub const fn next_day(self) -> Option<Self> {
- if self.ordinal() == 366 || (self.ordinal() == 365 && !self.is_in_leap_year()) {
+ let is_last_day_of_year = matches!(self.value.get() & 0x3FF, 365 | 878);
+ if hint::unlikely(is_last_day_of_year) {
if self.value.get() == Self::MAX.value.get() {
None
} else {
// Safety: `ordinal` is not zero.
unsafe { Some(Self::__from_ordinal_date_unchecked(self.year() + 1, 1)) }
}
} else {
- Some(Self {
- // Safety: `ordinal` is not zero.
- value: unsafe { NonZero::new_unchecked(self.value.get() + 1) },
- })
+ // Safety: `self` is not the last day of the year.
+ Some(unsafe { self.add_days_unchecked(1) })
}
}
@@ -640,18 +635,17 @@ impl Date {
/// ```
#[inline]
pub const fn previous_day(self) -> Option<Self> {
- if self.ordinal() != 1 {
- Some(Self {
- // Safety: `ordinal` is not zero.
- value: unsafe { NonZero::new_unchecked(self.value.get() - 1) },
- })
+ if hint::likely(self.ordinal() != 1) {
+ // Safety: `self` is not the first day of the year.
+ Some(unsafe { self.add_days_unchecked(-1) })
} else if self.value.get() == Self::MIN.value.get() {
None
} else {
- // Safety: `ordinal` is not zero.
- Some(unsafe {
- Self::__from_ordinal_date_unchecked(self.year() - 1, days_in_year(self.year() - 1))
- })
+ let year = self.year() - 1;
+ let is_leap_year = range_validated::is_leap_year(year);
+ let ordinal = if is_leap_year { 366 } else { 365 };
+ // Safety: `ordinal` is not zero, `is_leap_year` is correct.
+ Some(unsafe { Self::from_parts(year, is_leap_year, ordinal) })
}
}
@@ -676,10 +670,8 @@ impl Date {
#[inline]
#[track_caller]
pub const fn next_occurrence(self, weekday: Weekday) -> Self {
- expect_opt!(
- self.checked_next_occurrence(weekday),
- "overflow calculating the next occurrence of a weekday"
- )
+ self.checked_next_occurrence(weekday)
+ .expect("overflow calculating the next occurrence of a weekday")
}
/// Calculates the first occurrence of a weekday that is strictly earlier than a given `Date`.
@@ -703,10 +695,8 @@ impl Date {
#[inline]
#[track_caller]
pub const fn prev_occurrence(self, weekday: Weekday) -> Self {
- expect_opt!(
- self.checked_prev_occurrence(weekday),
- "overflow calculating the previous occurrence of a weekday"
- )
+ self.checked_prev_occurrence(weekday)
+ .expect("overflow calculating the previous occurrence of a weekday")
}
/// Calculates the `n`th occurrence of a weekday that is strictly later than a given `Date`.
@@ -730,10 +720,8 @@ impl Date {
#[inline]
#[track_caller]
pub const fn nth_next_occurrence(self, weekday: Weekday, n: u8) -> Self {
- expect_opt!(
- self.checked_nth_next_occurrence(weekday, n),
- "overflow calculating the next occurrence of a weekday"
- )
+ self.checked_nth_next_occurrence(weekday, n)
+ .expect("overflow calculating the next occurrence of a weekday")
}
/// Calculates the `n`th occurrence of a weekday that is strictly earlier than a given `Date`.
@@ -757,17 +745,30 @@ impl Date {
#[inline]
#[track_caller]
pub const fn nth_prev_occurrence(self, weekday: Weekday, n: u8) -> Self {
- expect_opt!(
- self.checked_nth_prev_occurrence(weekday, n),
- "overflow calculating the previous occurrence of a weekday"
- )
+ self.checked_nth_prev_occurrence(weekday, n)
+ .expect("overflow calculating the previous occurrence of a weekday")
+ }
+
+ /// Create an iterator of dates from `self` to `end` inclusive.
+ ///
+ /// ```rust
+ /// # use time_macros::date;
+ /// let mut iter = date!(2019-01-01).iter_to(date!(2019-01-03));
+ /// assert_eq!(iter.next(), Some(date!(2019-01-01)));
+ /// assert_eq!(iter.next(), Some(date!(2019-01-02)));
+ /// assert_eq!(iter.next(), Some(date!(2019-01-03)));
+ /// assert_eq!(iter.next(), None);
+ /// ```
+ #[inline]
+ pub const fn iter_to(self, end: Self) -> DateIter {
+ DateIter::new(self, end)
}
/// Get the Julian day for the date.
///
/// ```rust
/// # use time_macros::date;
- /// assert_eq!(date!(-4713 - 11 - 24).to_julian_day(), 0);
+ /// assert_eq!(date!(-4713-11-24).to_julian_day(), 0);
/// assert_eq!(date!(2000-01-01).to_julian_day(), 2_451_545);
/// assert_eq!(date!(2019-01-01).to_julian_day(), 2_458_485);
/// assert_eq!(date!(2019-12-31).to_julian_day(), 2_458_849);
@@ -785,6 +786,19 @@ impl Date {
days_before_year + ordinal as i32 - 363_521_075
}
+ /// Add a number of days to the date without checking for overflow.
+ ///
+ /// # Safety
+ ///
+ /// `self.ordinal() + days` must be in the range `1..=366` for leap years and `1..=365` for
+ /// common years.
+ #[inline]
+ pub(crate) const unsafe fn add_days_unchecked(mut self, days: i32) -> Self {
+ // Safety: asserted by caller
+ self.value = unsafe { NonZero::new_unchecked(self.value.get() + days) };
+ self
+ }
+
/// Computes `self + duration`, returning `None` if an overflow occurred.
///
/// ```rust
@@ -817,13 +831,29 @@ impl Date {
/// );
/// ```
#[inline]
- pub const fn checked_add(self, duration: Duration) -> Option<Self> {
+ pub const fn checked_add(self, duration: SignedDuration) -> Option<Self> {
let whole_days = duration.whole_days();
if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
return None;
}
- let julian_day = const_try_opt!(self.to_julian_day().checked_add(whole_days as i32));
+ let year = self.year();
+ let is_leap_year = self.is_in_leap_year();
+ let ordinal = self.ordinal() as i32;
+
+ let days_in_year = if is_leap_year { 366 } else { 365 };
+ let whole_days = whole_days as i32;
+
+ // Fast path for when the result is in the same year.
+ if let Some(new_ordinal) = ordinal.checked_add(whole_days)
+ && new_ordinal >= 1
+ && new_ordinal <= days_in_year
+ {
+ // Safety: `new_ordinal` is in range and `is_leap_year` is correct
+ return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
+ }
+
+ let julian_day = const_try_opt!(self.to_julian_day().checked_add(whole_days));
if let Ok(date) = Self::from_julian_day(julian_day) {
Some(date)
} else {
@@ -867,7 +897,23 @@ impl Date {
return None;
}
- let julian_day = const_try_opt!(self.to_julian_day().checked_add(whole_days as i32));
+ let year = self.year();
+ let is_leap_year = self.is_in_leap_year();
+ let ordinal = self.ordinal() as i32;
+
+ let days_in_year = if is_leap_year { 366 } else { 365 };
+ let whole_days = whole_days as i32;
+
+ // Fast path for when the result is in the same year.
+ if let Some(new_ordinal) = ordinal.checked_add(whole_days)
+ && new_ordinal >= 1
+ && new_ordinal <= days_in_year
+ {
+ // Safety: `new_ordinal` is in range and `is_leap_year` is correct
+ return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
+ }
+
+ let julian_day = const_try_opt!(self.to_julian_day().checked_add(whole_days));
if let Ok(date) = Self::from_julian_day(julian_day) {
Some(date)
} else {
@@ -907,13 +953,29 @@ impl Date {
/// );
/// ```
#[inline]
- pub const fn checked_sub(self, duration: Duration) -> Option<Self> {
+ pub const fn checked_sub(self, duration: SignedDuration) -> Option<Self> {
let whole_days = duration.whole_days();
if whole_days < i32::MIN as i64 || whole_days > i32::MAX as i64 {
return None;
}
- let julian_day = const_try_opt!(self.to_julian_day().checked_sub(whole_days as i32));
+ let year = self.year();
+ let is_leap_year = self.is_in_leap_year();
+ let ordinal = self.ordinal() as i32;
+
+ let days_in_year = if is_leap_year { 366 } else { 365 };
+ let whole_days = whole_days as i32;
+
+ // Fast path for when the result is in the same year.
+ if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
+ && new_ordinal >= 1
+ && new_ordinal <= days_in_year
+ {
+ // Safety: `new_ordinal` is in range and `is_leap_year` is correct
+ return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
+ }
+
+ let julian_day = const_try_opt!(self.to_julian_day().checked_sub(whole_days));
if let Ok(date) = Self::from_julian_day(julian_day) {
Some(date)
} else {
@@ -957,7 +1019,23 @@ impl Date {
return None;
}
- let julian_day = const_try_opt!(self.to_julian_day().checked_sub(whole_days as i32));
+ let year = self.year();
+ let is_leap_year = self.is_in_leap_year();
+ let ordinal = self.ordinal() as i32;
+
+ let days_in_year = if is_leap_year { 366 } else { 365 };
+ let whole_days = whole_days as i32;
+
+ // Fast path for when the result is in the same year.
+ if let Some(new_ordinal) = ordinal.checked_sub(whole_days)
+ && new_ordinal >= 1
+ && new_ordinal <= days_in_year
+ {
+ // Safety: `new_ordinal` is in range and `is_leap_year` is correct
+ return Some(unsafe { Self::from_parts(year, is_leap_year, new_ordinal as u16) });
+ }
+
+ let julian_day = const_try_opt!(self.to_julian_day().checked_sub(whole_days));
if let Ok(date) = Self::from_julian_day(julian_day) {
Some(date)
} else {
@@ -982,7 +1060,7 @@ impl Date {
}
};
- self.checked_add(Duration::days(day_diff))
+ self.checked_add(SignedDuration::days(day_diff))
}
/// Calculates the first occurrence of a weekday that is strictly earlier than a given `Date`.
@@ -1002,7 +1080,7 @@ impl Date {
}
};
- self.checked_sub(Duration::days(day_diff))
+ self.checked_sub(SignedDuration::days(day_diff))
}
/// Calculates the `n`th occurrence of a weekday that is strictly later than a given `Date`.
@@ -1014,7 +1092,7 @@ impl Date {
}
const_try_opt!(self.checked_next_occurrence(weekday))
- .checked_add(Duration::weeks(n as i64 - 1))
+ .checked_add(SignedDuration::weeks(n as i64 - 1))
}
/// Calculates the `n`th occurrence of a weekday that is strictly earlier than a given `Date`.
@@ -1026,7 +1104,7 @@ impl Date {
}
const_try_opt!(self.checked_prev_occurrence(weekday))
- .checked_sub(Duration::weeks(n as i64 - 1))
+ .checked_sub(SignedDuration::weeks(n as i64 - 1))
}
/// Computes `self + duration`, saturating value on overflow.
@@ -1059,7 +1137,7 @@ impl Date {
/// );
/// ```
#[inline]
- pub const fn saturating_add(self, duration: Duration) -> Self {
+ pub const fn saturating_add(self, duration: SignedDuration) -> Self {
if let Some(datetime) = self.checked_add(duration) {
datetime
} else if duration.is_negative() {
@@ -1100,7 +1178,7 @@ impl Date {
/// );
/// ```
#[inline]
- pub const fn saturating_sub(self, duration: Duration) -> Self {
+ pub const fn saturating_sub(self, duration: SignedDuration) -> Self {
if let Some(datetime) = self.checked_sub(duration) {
datetime
} else if duration.is_negative() {
@@ -1127,35 +1205,35 @@ impl Date {
pub const fn replace_year(self, year: i32) -> Result<Self, error::ComponentRange> {
ensure_ranged!(Year: year);
+ let new_is_leap_year = range_validated::is_leap_year(year);
let ordinal = self.ordinal();
// Dates in January and February are unaffected by leap years.
if ordinal <= 59 {
- // Safety: `ordinal` is not zero.
- return Ok(unsafe { Self::__from_ordinal_date_unchecked(year, ordinal) });
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
+ return Ok(unsafe { Self::from_parts(year, new_is_leap_year, ordinal) });
}
- match (self.is_in_leap_year(), is_leap_year(year)) {
+ match (self.is_in_leap_year(), new_is_leap_year) {
(false, false) | (true, true) => {
- // Safety: `ordinal` is not zero.
- Ok(unsafe { Self::__from_ordinal_date_unchecked(year, ordinal) })
+ Ok(Self {
+ // Safety: Whether the year is leap or common, the ordinal are unchanged, with
+ // only the year being replaced.
+ value: unsafe {
+ NonZero::new_unchecked((year << 10) | (self.value.get() & 0x3FF))
+ },
+ })
}
// February 29 does not exist in common years.
- (true, false) if ordinal == 60 => Err(error::ComponentRange {
- name: "day",
- value: 29,
- minimum: 1,
- maximum: 28,
- conditional_message: Some("for the given month and year"),
- }),
+ (true, false) if ordinal == 60 => Err(error::ComponentRange::conditional("day")),
// We're going from a common year to a leap year. Shift dates in March and later by
// one day.
- // Safety: `ordinal` is not zero.
- (false, true) => Ok(unsafe { Self::__from_ordinal_date_unchecked(year, ordinal + 1) }),
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
+ (false, true) => Ok(unsafe { Self::from_parts(year, true, ordinal + 1) }),
// We're going from a leap year to a common year. Shift dates in January and
// February by one day.
- // Safety: `ordinal` is not zero.
- (true, false) => Ok(unsafe { Self::__from_ordinal_date_unchecked(year, ordinal - 1) }),
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
+ (true, false) => Ok(unsafe { Self::from_parts(year, false, ordinal - 1) }),
}
}
@@ -1175,8 +1253,41 @@ impl Date {
#[inline]
#[must_use = "This method does not mutate the original `Date`."]
pub const fn replace_month(self, month: Month) -> Result<Self, error::ComponentRange> {
- let (year, _, day) = self.to_calendar_date();
- Self::from_calendar_date(year, month, day)
+ /// Cumulative days through the beginning of a month in both common and leap years.
+ const DAYS_CUMULATIVE_COMMON_LEAP: [[u16; 12]; 2] = [
+ [0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334],
+ [0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335],
+ ];
+
+ let (year, ordinal) = self.to_ordinal_date();
+ let mut ordinal = ordinal as u32;
+ let is_leap_year = self.is_in_leap_year();
+ let jan_feb_len = 59 + is_leap_year as u32;
+
+ if ordinal > jan_feb_len {
+ ordinal -= jan_feb_len;
+ }
+ let current_month = (ordinal * 268 + 8031) >> 13;
+ let days_in_preceding_months = (current_month * 3917 - 3866) >> 7;
+ let day = (ordinal - days_in_preceding_months) as u8;
+
+ match day {
+ 1..=28 => {}
+ 29..=31 if day <= days_in_month_leap(month as u8, is_leap_year) => hint::cold_path(),
+ _ => {
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("day"));
+ }
+ }
+
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
+ Ok(unsafe {
+ Self::from_parts(
+ year,
+ is_leap_year,
+ DAYS_CUMULATIVE_COMMON_LEAP[is_leap_year as usize][month as usize - 1] + day as u16,
+ )
+ })
}
/// Replace the day of the month.
@@ -1190,25 +1301,24 @@ impl Date {
#[inline]
#[must_use = "This method does not mutate the original `Date`."]
pub const fn replace_day(self, day: u8) -> Result<Self, error::ComponentRange> {
+ let is_leap_year = self.is_in_leap_year();
match day {
1..=28 => {}
- 29..=31 if day <= self.month().length(self.year()) => {}
+ 29..=31 if day <= days_in_month_leap(self.month() as u8, is_leap_year) => {
+ hint::cold_path()
+ }
_ => {
- return Err(error::ComponentRange {
- name: "day",
- minimum: 1,
- maximum: self.month().length(self.year()) as i64,
- value: day as i64,
- conditional_message: Some("for the given month and year"),
- });
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("day"));
}
}
- // Safety: `ordinal` is not zero.
+ // Safety: `ordinal` is not zero and `is_leap_year` is correct.
Ok(unsafe {
- Self::__from_ordinal_date_unchecked(
+ Self::from_parts(
self.year(),
- (self.ordinal() as i16 - self.day() as i16 + day as i16) as u16,
+ is_leap_year,
+ (self.ordinal().cast_signed() - self.day() as i16 + day as i16).cast_unsigned(),
)
})
}
@@ -1220,44 +1330,40 @@ impl Date {
/// assert_eq!(date!(2022-049).replace_ordinal(1), Ok(date!(2022-001)));
/// assert!(date!(2022-049).replace_ordinal(0).is_err()); // 0 isn't a valid ordinal
/// assert!(date!(2022-049).replace_ordinal(366).is_err()); // 2022 isn't a leap year
- /// ````
+ /// ```
#[inline]
#[must_use = "This method does not mutate the original `Date`."]
pub const fn replace_ordinal(self, ordinal: u16) -> Result<Self, error::ComponentRange> {
+ let is_leap_year = self.is_in_leap_year();
match ordinal {
1..=365 => {}
- 366 if self.is_in_leap_year() => {}
+ 366 if is_leap_year => hint::cold_path(),
_ => {
- return Err(error::ComponentRange {
- name: "ordinal",
- minimum: 1,
- maximum: days_in_year(self.year()) as i64,
- value: ordinal as i64,
- conditional_message: Some("for the given year"),
- });
+ hint::cold_path();
+ return Err(error::ComponentRange::conditional("ordinal"));
}
}
- // Safety: `ordinal` is in range.
- Ok(unsafe { Self::__from_ordinal_date_unchecked(self.year(), ordinal) })
+ // Safety: `ordinal` is in range and `is_leap_year` is correct.
+ Ok(unsafe { Self::from_parts(self.year(), is_leap_year, ordinal) })
}
}
-/// Methods to add a [`Time`] component, resulting in a [`PrimitiveDateTime`].
+/// Methods to add a [`Time`] component, resulting in a [`PlainDateTime`].
impl Date {
- /// Create a [`PrimitiveDateTime`] using the existing date. The [`Time`] component will be set
- /// to midnight.
+ /// Create a [`PlainDateTime`] using the existing date. The [`Time`] component will be set to
+ /// midnight.
///
/// ```rust
/// # use time_macros::{date, datetime};
/// assert_eq!(date!(1970-01-01).midnight(), datetime!(1970-01-01 0:00));
/// ```
#[inline]
- pub const fn midnight(self) -> PrimitiveDateTime {
- PrimitiveDateTime::new(self, Time::MIDNIGHT)
+ pub const fn midnight(self) -> PlainDateTime {
+ PlainDateTime::new(self, Time::MIDNIGHT)
}
- /// Create a [`PrimitiveDateTime`] using the existing date and the provided [`Time`].
+ /// Create a [`PlainDateTime`] using the existing date and the provided [`Time`].
///
/// ```rust
/// # use time_macros::{date, datetime, time};
@@ -1267,11 +1373,11 @@ impl Date {
/// );
/// ```
#[inline]
- pub const fn with_time(self, time: Time) -> PrimitiveDateTime {
- PrimitiveDateTime::new(self, time)
+ pub const fn with_time(self, time: Time) -> PlainDateTime {
+ PlainDateTime::new(self, time)
}
- /// Attempt to create a [`PrimitiveDateTime`] using the existing date and the provided time.
+ /// Attempt to create a [`PlainDateTime`] using the existing date and the provided time.
///
/// ```rust
/// # use time_macros::date;
@@ -1284,14 +1390,14 @@ impl Date {
hour: u8,
minute: u8,
second: u8,
- ) -> Result<PrimitiveDateTime, error::ComponentRange> {
- Ok(PrimitiveDateTime::new(
+ ) -> Result<PlainDateTime, error::ComponentRange> {
+ Ok(PlainDateTime::new(
self,
const_try!(Time::from_hms(hour, minute, second)),
))
}
- /// Attempt to create a [`PrimitiveDateTime`] using the existing date and the provided time.
+ /// Attempt to create a [`PlainDateTime`] using the existing date and the provided time.
///
/// ```rust
/// # use time_macros::date;
@@ -1305,14 +1411,14 @@ impl Date {
minute: u8,
second: u8,
millisecond: u16,
- ) -> Result<PrimitiveDateTime, error::ComponentRange> {
- Ok(PrimitiveDateTime::new(
+ ) -> Result<PlainDateTime, error::ComponentRange> {
+ Ok(PlainDateTime::new(
self,
const_try!(Time::from_hms_milli(hour, minute, second, millisecond)),
))
}
- /// Attempt to create a [`PrimitiveDateTime`] using the existing date and the provided time.
+ /// Attempt to create a [`PlainDateTime`] using the existing date and the provided time.
///
/// ```rust
/// # use time_macros::date;
@@ -1326,14 +1432,14 @@ impl Date {
minute: u8,
second: u8,
microsecond: u32,
- ) -> Result<PrimitiveDateTime, error::ComponentRange> {
- Ok(PrimitiveDateTime::new(
+ ) -> Result<PlainDateTime, error::ComponentRange> {
+ Ok(PlainDateTime::new(
self,
const_try!(Time::from_hms_micro(hour, minute, second, microsecond)),
))
}
- /// Attempt to create a [`PrimitiveDateTime`] using the existing date and the provided time.
+ /// Attempt to create a [`PlainDateTime`] using the existing date and the provided time.
///
/// ```rust
/// # use time_macros::date;
@@ -1347,8 +1453,8 @@ impl Date {
minute: u8,
second: u8,
nanosecond: u32,
- ) -> Result<PrimitiveDateTime, error::ComponentRange> {
- Ok(PrimitiveDateTime::new(
+ ) -> Result<PlainDateTime, error::ComponentRange> {
+ Ok(PlainDateTime::new(
self,
const_try!(Time::from_hms_nano(hour, minute, second, nanosecond)),
))
@@ -1364,21 +1470,21 @@ impl Date {
output: &mut (impl io::Write + ?Sized),
format: &(impl Formattable + ?Sized),
) -> Result<usize, error::Format> {
- format.format_into(output, Some(self), None, None)
+ format.format_into(output, &self, &mut Default::default(), PrivateMethod)
}
/// Format the `Date` using the provided [format description](crate::format_description).
///
/// ```rust
- /// # use time::{format_description};
+ /// # use time::format_description;
/// # use time_macros::date;
- /// let format = format_description::parse("[year]-[month]-[day]")?;
+ /// let format = format_description::parse_borrowed::<3>("[year]-[month]-[day]")?;
/// assert_eq!(date!(2020-01-02).format(&format)?, "2020-01-02");
/// # Ok::<_, time::Error>(())
/// ```
#[inline]
pub fn format(self, format: &(impl Formattable + ?Sized)) -> Result<String, error::Format> {
- format.format(Some(self), None, None)
+ format.format(&self, &mut Default::default(), PrivateMethod)
}
}
@@ -1399,96 +1505,149 @@ impl Date {
input: &str,
description: &(impl Parsable + ?Sized),
) -> Result<Self, error::Parse> {
- description.parse_date(input.as_bytes())
+ description.parse_date(input.as_bytes(), None, PrivateMethod)
}
-}
-mod private {
- #[non_exhaustive]
- #[derive(Debug, Clone, Copy)]
- pub struct DateMetadata {
- /// The width of the year component, including the sign.
- pub(super) year_width: u8,
- /// Whether the sign should be displayed.
- pub(super) display_sign: bool,
- pub(super) year: i32,
- pub(super) month: u8,
- pub(super) day: u8,
+ /// Parse a `Date` from the input using the provided [format
+ /// description](crate::format_description) and default values.
+ ///
+ /// ```rust
+ /// # use time::Date;
+ /// # use time::parsing::Parsed;
+ /// # use time_macros::{date, format_description};
+ /// let format = format_description!("[month]-[day]");
+ /// let defaults = Parsed::new().with_year(2020).expect("2020 is a valid year");
+ /// assert_eq!(
+ /// Date::parse_with_defaults(b"01-15", &format, defaults)?,
+ /// date!(2020-01-15)
+ /// );
+ /// # Ok::<_, time::Error>(())
+ /// ```
+ #[inline]
+ pub fn parse_with_defaults(
+ input: &[u8],
+ description: &(impl Parsable + ?Sized),
+ defaults: Parsed,
+ ) -> Result<Self, error::Parse> {
+ description.parse_date(input, Some(defaults), PrivateMethod)
}
}
-use private::DateMetadata;
+// This no longer needs special handling, as the format is fixed and doesn't require anything
+// advanced. Trait impls can't be deprecated and the info is still useful for other types
+// implementing `SmartDisplay`, so leave it as-is for now.
impl SmartDisplay for Date {
- type Metadata = DateMetadata;
+ type Metadata = ();
#[inline]
fn metadata(&self, _: FormatterOptions) -> Metadata<'_, Self> {
- let (year, month, day) = self.to_calendar_date();
+ use crate::ext::DigitCount as _;
- // There is a minimum of four digits for any year.
- let mut year_width = cmp::max(year.unsigned_abs().num_digits(), 4);
- let display_sign = if !(0..10_000).contains(&year) {
- // An extra character is required for the sign.
- year_width += 1;
- true
- } else {
- false
- };
+ let year_sign_width =
+ if self.year() < 0 || (cfg!(feature = "large-dates") && self.year() >= 10_000) {
+ 1
+ } else {
+ 0
+ };
+ let year_width = self.year().unsigned_abs().num_digits().clamp(4, 6);
+ let formatted_width = year_sign_width + year_width + 6; // include two dashes and two digits each for month and day
- let formatted_width = year_width.extend::<usize>()
- + smart_display::padded_width_of!(
- "-",
- u8::from(month) => width(2),
- "-",
- day => width(2),
- );
+ Metadata::new(formatted_width as usize, self, ())
+ }
- Metadata::new(
- formatted_width,
- self,
- DateMetadata {
- year_width,
- display_sign,
- year,
- month: u8::from(month),
- day,
- },
- )
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ fmt::Display::fmt(self, f)
}
+}
+impl Date {
+ /// The maximum number of bytes that the `fmt_into_buffer` method will write, which is also used
+ /// for the `Display` implementation.
+ pub(crate) const DISPLAY_BUFFER_SIZE: usize = 13;
+
+ /// Format the `Date` into the provided buffer, returning the number of bytes written.
#[inline]
- fn fmt_with_metadata(
- &self,
- f: &mut fmt::Formatter<'_>,
- metadata: Metadata<Self>,
- ) -> fmt::Result {
- let DateMetadata {
- year_width,
- display_sign,
- year,
- month,
- day,
- } = *metadata;
- let year_width = year_width.extend();
-
- if display_sign {
- f.pad_with_width(
- metadata.unpadded_width(),
- format_args!("{year:+0year_width$}-{month:02}-{day:02}"),
- )
- } else {
- f.pad_with_width(
- metadata.unpadded_width(),
- format_args!("{year:0year_width$}-{month:02}-{day:02}"),
- )
+ pub(crate) fn fmt_into_buffer(
+ self,
+ buf: &mut [MaybeUninit<u8>; Self::DISPLAY_BUFFER_SIZE],
+ ) -> usize {
+ let mut idx = 0;
+ let (year, month, day) = self.to_calendar_date();
+
+ // Compute the sign of the integer, if any. Doing this in a branchless manner gives a
+ // significant performance improvement.
+ let neg = year.is_negative() as u8;
+ let pos = (cfg!(feature = "large-dates") && year - 10_000 >= 0) as u8;
+ let sign = b'+' + 2 * neg; // b'-' if `neg` is true, b'+' otherwise
+ // Always write the computed byte, even if it's later overwritten by the first digit of the
+ // year.
+ buf[idx] = MaybeUninit::new(sign);
+ idx += (neg | pos) as usize;
+
+ // Safety: `year.unsigned_abs()` is less than 1,000,000.
+ let [first_two, second_two, third_two] =
+ four_to_six_digits(unsafe { ru32::new_unchecked(year.unsigned_abs()) });
+ // Safety:
+ // - both `first_two` and `buf` are valid for reads and writes of up to 2 bytes.
+ // - `u8` is 1-aligned, so that is not a concern.
+ // - `first_two` points to static memory, while `buf` is a local variable, so they do not
+ // overlap.
+ unsafe {
+ first_two
+ .as_ptr()
+ .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), first_two.len());
+ }
+ idx += first_two.len();
+ // Safety: See above.
+ unsafe {
+ second_two
+ .as_ptr()
+ .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
+ }
+ idx += 2;
+ // Safety: See above.
+ unsafe {
+ third_two
+ .as_ptr()
+ .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
+ }
+ idx += 2;
+
+ buf[idx] = MaybeUninit::new(b'-');
+ idx += 1;
+
+ // Safety: See above for `copy_to_nonoverlapping`. `month` is in the range 1..=12.
+ unsafe {
+ two_digits_zero_padded(ru8::new_unchecked(u8::from(month)))
+ .as_ptr()
+ .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
}
+ idx += 2;
+
+ buf[idx] = MaybeUninit::new(b'-');
+ idx += 1;
+
+ // Safety: See above for `copy_to_nonoverlapping`. `day` is in the range 1..=31.
+ unsafe {
+ two_digits_zero_padded(ru8::new_unchecked(day))
+ .as_ptr()
+ .copy_to_nonoverlapping(buf.as_mut_ptr().add(idx).cast(), 2);
+ }
+ idx += 2;
+
+ idx
}
}
impl fmt::Display for Date {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- SmartDisplay::fmt(self, f)
+ let mut buf = [MaybeUninit::uninit(); 13];
+ let len = self.fmt_into_buffer(&mut buf);
+ // Safety: All bytes up to `len` have been initialized with ASCII characters.
+ let s = unsafe { str_from_raw_parts((&raw const buf).cast(), len) };
+ f.pad(s)
}
}
@@ -1499,15 +1658,15 @@ impl fmt::Debug for Date {
}
}
-impl Add<Duration> for Date {
+impl Add<SignedDuration> for Date {
type Output = Self;
/// # Panics
///
/// This may panic if an overflow occurs.
#[inline]
#[track_caller]
- fn add(self, duration: Duration) -> Self::Output {
+ fn add(self, duration: SignedDuration) -> Self::Output {
self.checked_add(duration)
.expect("overflow adding duration to date")
}
@@ -1527,17 +1686,37 @@ impl Add<StdDuration> for Date {
}
}
-impl_add_assign!(Date: Duration, StdDuration);
+impl AddAssign<SignedDuration> for Date {
+ /// # Panics
+ ///
+ /// This may panic if an overflow occurs.
+ #[inline]
+ #[track_caller]
+ fn add_assign(&mut self, rhs: SignedDuration) {
+ *self = *self + rhs;
+ }
+}
+
+impl AddAssign<StdDuration> for Date {
+ /// # Panics
+ ///
+ /// This may panic if an overflow occurs.
+ #[inline]
+ #[track_caller]
+ fn add_assign(&mut self, rhs: StdDuration) {
+ *self = *self + rhs;
+ }
+}
-impl Sub<Duration> for Date {
+impl Sub<SignedDuration> for Date {
type Output = Self;
/// # Panics
///
/// This may panic if an overflow occurs.
#[inline]
#[track_caller]
- fn sub(self, duration: Duration) -> Self::Output {
+ fn sub(self, duration: SignedDuration) -> Self::Output {
self.checked_sub(duration)
.expect("overflow subtracting duration from date")
}
@@ -1557,13 +1736,33 @@ impl Sub<StdDuration> for Date {
}
}
-impl_sub_assign!(Date: Duration, StdDuration);
+impl SubAssign<SignedDuration> for Date {
+ /// # Panics
+ ///
+ /// This may panic if an overflow occurs.
+ #[inline]
+ #[track_caller]
+ fn sub_assign(&mut self, rhs: SignedDuration) {
+ *self = *self - rhs;
+ }
+}
+
+impl SubAssign<StdDuration> for Date {
+ /// # Panics
+ ///
+ /// This may panic if an overflow occurs.
+ #[inline]
+ #[track_caller]
+ fn sub_assign(&mut self, rhs: StdDuration) {
+ *self = *self - rhs;
+ }
+}
impl Sub for Date {
- type Output = Duration;
+ type Output = SignedDuration;
#[inline]
fn sub(self, other: Self) -> Self::Output {
- Duration::days((self.to_julian_day() - other.to_julian_day()).extend())
+ SignedDuration::days((self.to_julian_day() - other.to_julian_day()).widen())
}
}
### external/vendor/time/src/error/component_range.rs
@@ -1,80 +1,58 @@
//! Component range error
-use core::{fmt, hash};
+use core::fmt;
use crate::error;
/// An error type indicating that a component provided to a method was out of range, causing a
/// failure.
// i64 is the narrowest type fitting all use cases. This eliminates the need for a type parameter.
-#[derive(Debug, Clone, Copy, Eq)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct ComponentRange {
/// Name of the component.
pub(crate) name: &'static str,
- /// Minimum allowed value, inclusive.
- pub(crate) minimum: i64,
- /// Maximum allowed value, inclusive.
- pub(crate) maximum: i64,
- /// Value that was provided.
- pub(crate) value: i64,
- /// The minimum and/or maximum value is conditional on the value of other
- /// parameters.
- pub(crate) conditional_message: Option<&'static str>,
+ /// Whether an input with the same value could have succeeded if the values of other components
+ /// were different.
+ pub(crate) is_conditional: bool,
}
impl ComponentRange {
- /// Obtain the name of the component whose value was out of range.
+ /// Create a new `ComponentRange` error that is not conditional.
#[inline]
- pub const fn name(self) -> &'static str {
- self.name
+ pub(crate) const fn unconditional(name: &'static str) -> Self {
+ Self {
+ name,
+ is_conditional: false,
+ }
}
- /// Whether the value's permitted range is conditional, i.e. whether an input with this
- /// value could have succeeded if the values of other components were different.
+ /// Create a new `ComponentRange` error that is conditional.
#[inline]
- pub const fn is_conditional(self) -> bool {
- self.conditional_message.is_some()
+ pub(crate) const fn conditional(name: &'static str) -> Self {
+ Self {
+ name,
+ is_conditional: true,
+ }
}
-}
-impl PartialEq for ComponentRange {
+ /// Obtain the name of the component whose value was out of range.
#[inline]
- fn eq(&self, other: &Self) -> bool {
- self.name == other.name
- && self.minimum == other.minimum
- && self.maximum == other.maximum
- && self.value == other.value
- // Skip the contents of the message when comparing for equality.
- && self.conditional_message.is_some() == other.conditional_message.is_some()
+ pub const fn name(self) -> &'static str {
+ self.name
}
-}
-impl hash::Hash for ComponentRange {
+ /// Whether the value's permitted range is conditional, i.e. whether an input with this
+ /// value could have succeeded if the values of other components were different.
#[inline]
- fn hash<H: hash::Hasher>(&self, state: &mut H) {
- self.name.hash(state);
- self.minimum.hash(state);
- self.maximum.hash(state);
- self.value.hash(state);
- // Skip the contents of the message when comparing for equality.
- self.conditional_message.is_some().hash(state);
+ pub const fn is_conditional(self) -> bool {
+ self.is_conditional
}
}
impl fmt::Display for ComponentRange {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "{} must be in the range {}..={}",
- self.name, self.minimum, self.maximum
- )?;
-
- if let Some(message) = self.conditional_message {
- write!(f, " {message}")?;
- }
-
- Ok(())
+ write!(f, "{} was not in range", self.name)
}
}
@@ -99,23 +77,25 @@ impl TryFrom<crate::Error> for ComponentRange {
/// **This trait implementation is deprecated and will be removed in a future breaking release.**
#[cfg(feature = "serde")]
-impl serde::de::Expected for ComponentRange {
+impl serde_core::de::Expected for ComponentRange {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(
- f,
- "a value in the range {}..={}",
- self.minimum, self.maximum
- )
+ f.write_str("an in-range value")
}
}
#[cfg(feature = "serde")]
impl ComponentRange {
/// Convert the error to a deserialization error.
#[inline]
- pub(crate) fn into_de_error<E: serde::de::Error>(self) -> E {
- E::invalid_value(serde::de::Unexpected::Signed(self.value), &self)
+ pub(crate) fn into_de_error<E>(self) -> E
+ where
+ E: serde_core::de::Error,
+ {
+ serde_core::de::Error::custom(format_args!(
+ "invalid {}, expected an in-range value",
+ self.name
+ ))
}
}
### external/vendor/time/src/error/format.rs
@@ -114,8 +114,11 @@ impl Format {
/// Obtain an error type for the serializer.
#[doc(hidden)] // Exposed only for the `declare_format_string` macro
#[inline]
- pub fn into_invalid_serde_value<S: serde::Serializer>(self) -> S::Error {
- use serde::ser::Error;
+ pub fn into_invalid_serde_value<S>(self) -> S::Error
+ where
+ S: serde_core::Serializer,
+ {
+ use serde_core::ser::Error;
S::Error::custom(self)
}
}
### external/vendor/time/src/error/invalid_format_description.rs
@@ -63,6 +63,24 @@ pub enum InvalidFormatDescription {
/// The zero-based index the error occurred at.
index: usize,
},
+ /// A modifier was present more than once.
+ #[non_exhaustive]
+ DuplicateModifier {
+ /// The name of the modifier that is duplicated.
+ name: &'static str,
+ /// The zero-based index of the second occurrence of the modifier.
+ index: usize,
+ },
+ /// A combination of modifiers is not valid.
+ #[non_exhaustive]
+ InvalidModifierCombination {
+ /// The modifier that is not valid in combination with the other modifiers.
+ modifier: &'static str,
+ /// The context in which the modifier is not valid.
+ context: &'static str,
+ /// The zero-based index the error occurred at.
+ index: usize,
+ },
}
impl From<InvalidFormatDescription> for crate::Error {
@@ -127,6 +145,17 @@ impl fmt::Display for InvalidFormatDescription {
)
}
}
+ DuplicateModifier { name, index } => {
+ write!(f, "duplicate modifier `{name}` at byte index {index}")
+ }
+ InvalidModifierCombination {
+ modifier,
+ context,
+ index,
+ } => write!(
+ f,
+ "the `{modifier}` modifier is not valid at byte index {index} {context}"
+ ),
}
}
}
### external/vendor/time/src/ext/instant.rs
@@ -1,6 +1,6 @@
use std::time::Instant as StdInstant;
-use crate::Duration;
+use crate::SignedDuration;
/// Sealed trait to prevent downstream implementations.
mod sealed {
@@ -10,7 +10,7 @@ mod sealed {
}
/// An extension trait for [`std::time::Instant`] that adds methods for
-/// [`time::Duration`](Duration)s.
+/// [`time::SignedDuration`](SignedDuration)s.
pub trait InstantExt: sealed::Sealed {
/// # Panics
///
@@ -19,7 +19,7 @@ pub trait InstantExt: sealed::Sealed {
/// version.
#[inline]
#[track_caller]
- fn add_signed(self, duration: Duration) -> Self {
+ fn add_signed(self, duration: SignedDuration) -> Self {
self.checked_add_signed(duration)
.expect("overflow when adding duration to instant")
}
@@ -31,20 +31,20 @@ pub trait InstantExt: sealed::Sealed {
/// version.
#[inline]
#[track_caller]
- fn sub_signed(self, duration: Duration) -> Self {
+ fn sub_signed(self, duration: SignedDuration) -> Self {
self.checked_sub_signed(duration)
.expect("overflow when subtracting duration from instant")
}
/// Returns `Some(t)` where `t` is the time `self.checked_add_signed(duration)` if `t` can be
/// represented as `Instant` (which means it's inside the bounds of the underlying data
/// structure), `None` otherwise.
- fn checked_add_signed(&self, duration: Duration) -> Option<Self>;
+ fn checked_add_signed(&self, duration: SignedDuration) -> Option<Self>;
/// Returns `Some(t)` where `t` is the time `self.checked_sub_signed(duration)` if `t` can be
/// represented as `Instant` (which means it's inside the bounds of the underlying data
/// structure), `None` otherwise.
- fn checked_sub_signed(&self, duration: Duration) -> Option<Self>;
+ fn checked_sub_signed(&self, duration: SignedDuration) -> Option<Self>;
/// Returns the amount of time elapsed from another instant to this one. This will be negative
/// if `earlier` is later than `self`.
@@ -61,12 +61,12 @@ pub trait InstantExt: sealed::Sealed {
/// println!("{:?}", new_now.signed_duration_since(now)); // positive
/// println!("{:?}", now.signed_duration_since(new_now)); // negative
/// ```
- fn signed_duration_since(&self, earlier: Self) -> Duration;
+ fn signed_duration_since(&self, earlier: Self) -> SignedDuration;
}
impl InstantExt for StdInstant {
#[inline]
- fn checked_add_signed(&self, duration: Duration) -> Option<Self> {
+ fn checked_add_signed(&self, duration: SignedDuration) -> Option<Self> {
if duration.is_positive() {
self.checked_add(duration.unsigned_abs())
} else if duration.is_negative() {
@@ -78,7 +78,7 @@ impl InstantExt for StdInstant {
}
#[inline]
- fn checked_sub_signed(&self, duration: Duration) -> Option<Self> {
+ fn checked_sub_signed(&self, duration: SignedDuration) -> Option<Self> {
if duration.is_positive() {
self.checked_sub(duration.unsigned_abs())
} else if duration.is_negative() {
@@ -90,16 +90,16 @@ impl InstantExt for StdInstant {
}
#[inline]
- fn signed_duration_since(&self, earlier: Self) -> Duration {
+ fn signed_duration_since(&self, earlier: Self) -> SignedDuration {
if *self > earlier {
self.saturating_duration_since(earlier)
.try_into()
- .unwrap_or(Duration::MAX)
+ .unwrap_or(SignedDuration::MAX)
} else {
earlier
.saturating_duration_since(*self)
.try_into()
- .map_or(Duration::MIN, |d: Duration| -d)
+ .map_or(SignedDuration::MIN, |d: SignedDuration| -d)
}
}
}
### external/vendor/time/src/ext/numerical_duration.rs
@@ -1,5 +1,5 @@
-use crate::convert::*;
-use crate::Duration;
+use crate::SignedDuration;
+use crate::unit::*;
/// Sealed trait to prevent downstream implementations.
mod sealed {
@@ -9,39 +9,39 @@ mod sealed {
impl Sealed for f64 {}
}
-/// Create [`Duration`]s from numeric literals.
+/// Create [`SignedDuration`]s from numeric literals.
///
/// # Examples
///
-/// Basic construction of [`Duration`]s.
+/// Basic construction of [`SignedDuration`]s.
///
/// ```rust
-/// # use time::{Duration, ext::NumericalDuration};
-/// assert_eq!(5.nanoseconds(), Duration::nanoseconds(5));
-/// assert_eq!(5.microseconds(), Duration::microseconds(5));
-/// assert_eq!(5.milliseconds(), Duration::milliseconds(5));
-/// assert_eq!(5.seconds(), Duration::seconds(5));
-/// assert_eq!(5.minutes(), Duration::minutes(5));
-/// assert_eq!(5.hours(), Duration::hours(5));
-/// assert_eq!(5.days(), Duration::days(5));
-/// assert_eq!(5.weeks(), Duration::weeks(5));
+/// # use time::{SignedDuration, ext::NumericalDuration};
+/// assert_eq!(5.nanoseconds(), SignedDuration::nanoseconds(5));
+/// assert_eq!(5.microseconds(), SignedDuration::microseconds(5));
+/// assert_eq!(5.milliseconds(), SignedDuration::milliseconds(5));
+/// assert_eq!(5.seconds(), SignedDuration::seconds(5));
+/// assert_eq!(5.minutes(), SignedDuration::minutes(5));
+/// assert_eq!(5.hours(), SignedDuration::hours(5));
+/// assert_eq!(5.days(), SignedDuration::days(5));
+/// assert_eq!(5.weeks(), SignedDuration::weeks(5));
/// ```
///
/// Signed integers work as well!
///
/// ```rust
-/// # use time::{Duration, ext::NumericalDuration};
-/// assert_eq!((-5).nanoseconds(), Duration::nanoseconds(-5));
-/// assert_eq!((-5).microseconds(), Duration::microseconds(-5));
-/// assert_eq!((-5).milliseconds(), Duration::milliseconds(-5));
-/// assert_eq!((-5).seconds(), Duration::seconds(-5));
-/// assert_eq!((-5).minutes(), Duration::minutes(-5));
-/// assert_eq!((-5).hours(), Duration::hours(-5));
-/// assert_eq!((-5).days(), Duration::days(-5));
-/// assert_eq!((-5).weeks(), Duration::weeks(-5));
+/// # use time::{SignedDuration, ext::NumericalDuration};
+/// assert_eq!((-5).nanoseconds(), SignedDuration::nanoseconds(-5));
+/// assert_eq!((-5).microseconds(), SignedDuration::microseconds(-5));
+/// assert_eq!((-5).milliseconds(), SignedDuration::milliseconds(-5));
+/// assert_eq!((-5).seconds(), SignedDuration::seconds(-5));
+/// assert_eq!((-5).minutes(), SignedDuration::minutes(-5));
+/// assert_eq!((-5).hours(), SignedDuration::hours(-5));
+/// assert_eq!((-5).days(), SignedDuration::days(-5));
+/// assert_eq!((-5).weeks(), SignedDuration::weeks(-5));
/// ```
///
-/// Just like any other [`Duration`], they can be added, subtracted, etc.
+/// Just like any other [`SignedDuration`], they can be added, subtracted, etc.
///
/// ```rust
/// # use time::ext::NumericalDuration;
@@ -55,112 +55,112 @@ mod sealed {
#[diagnostic::on_unimplemented(note = "this extension trait is intended to be used with numeric \
literals, such as `5.seconds()`")]
pub trait NumericalDuration: sealed::Sealed {
- /// Create a [`Duration`] from the number of nanoseconds.
- fn nanoseconds(self) -> Duration;
- /// Create a [`Duration`] from the number of microseconds.
- fn microseconds(self) -> Duration;
- /// Create a [`Duration`] from the number of milliseconds.
- fn milliseconds(self) -> Duration;
- /// Create a [`Duration`] from the number of seconds.
- fn seconds(self) -> Duration;
- /// Create a [`Duration`] from the number of minutes.
- fn minutes(self) -> Duration;
- /// Create a [`Duration`] from the number of hours.
- fn hours(self) -> Duration;
- /// Create a [`Duration`] from the number of days.
- fn days(self) -> Duration;
- /// Create a [`Duration`] from the number of weeks.
- fn weeks(self) -> Duration;
+ /// Create a [`SignedDuration`] from the number of nanoseconds.
+ fn nanoseconds(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of microseconds.
+ fn microseconds(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of milliseconds.
+ fn milliseconds(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of seconds.
+ fn seconds(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of minutes.
+ fn minutes(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of hours.
+ fn hours(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of days.
+ fn days(self) -> SignedDuration;
+ /// Create a [`SignedDuration`] from the number of weeks.
+ fn weeks(self) -> SignedDuration;
}
impl NumericalDuration for i64 {
#[inline]
- fn nanoseconds(self) -> Duration {
- Duration::nanoseconds(self)
+ fn nanoseconds(self) -> SignedDuration {
+ SignedDuration::nanoseconds(self)
}
#[inline]
- fn microseconds(self) -> Duration {
- Duration::microseconds(self)
+ fn microseconds(self) -> SignedDuration {
+ SignedDuration::microseconds(self)
}
#[inline]
- fn milliseconds(self) -> Duration {
- Duration::milliseconds(self)
+ fn milliseconds(self) -> SignedDuration {
+ SignedDuration::milliseconds(self)
}
#[inline]
- fn seconds(self) -> Duration {
- Duration::seconds(self)
+ fn seconds(self) -> SignedDuration {
+ SignedDuration::seconds(self)
}
#[inline]
#[track_caller]
- fn minutes(self) -> Duration {
- Duration::minutes(self)
+ fn minutes(self) -> SignedDuration {
+ SignedDuration::minutes(self)
}
#[inline]
#[track_caller]
- fn hours(self) -> Duration {
- Duration::hours(self)
+ fn hours(self) -> SignedDuration {
+ SignedDuration::hours(self)
}
#[inline]
#[track_caller]
- fn days(self) -> Duration {
- Duration::days(self)
+ fn days(self) -> SignedDuration {
+ SignedDuration::days(self)
}
#[inline]
#[track_caller]
- fn weeks(self) -> Duration {
- Duration::weeks(self)
+ fn weeks(self) -> SignedDuration {
+ SignedDuration::weeks(self)
}
}
impl NumericalDuration for f64 {
#[inline]
- fn nanoseconds(self) -> Duration {
- Duration::nanoseconds(self as i64)
+ fn nanoseconds(self) -> SignedDuration {
+ SignedDuration::nanoseconds(self as i64)
}
#[inline]
- fn microseconds(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Microsecond)) as i64)
+ fn microseconds(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Microsecond)) as i64)
}
#[inline]
- fn milliseconds(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Millisecond)) as i64)
+ fn milliseconds(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Millisecond)) as i64)
}
#[inline]
- fn seconds(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Second)) as i64)
+ fn seconds(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Second)) as i64)
}
#[inline]
#[track_caller]
- fn minutes(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Minute)) as i64)
+ fn minutes(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Minute)) as i64)
}
#[inline]
#[track_caller]
- fn hours(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Hour)) as i64)
+ fn hours(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Hour)) as i64)
}
#[inline]
#[track_caller]
- fn days(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Day)) as i64)
+ fn days(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Day)) as i64)
}
#[inline]
#[track_caller]
- fn weeks(self) -> Duration {
- Duration::nanoseconds((self * Nanosecond::per_t::<Self>(Week)) as i64)
+ fn weeks(self) -> SignedDuration {
+ SignedDuration::nanoseconds((self * Nanosecond::per_t::<Self>(Week)) as i64)
}
}
### external/vendor/time/src/ext/numerical_std_duration.rs
@@ -1,6 +1,6 @@
use core::time::Duration as StdDuration;
-use crate::convert::*;
+use crate::unit::*;
/// Sealed trait to prevent downstream implementations.
mod sealed {
@@ -96,7 +96,7 @@ impl NumericalStdDuration for u64 {
fn std_minutes(self) -> StdDuration {
StdDuration::from_secs(
self.checked_mul(Second::per_t(Minute))
- .expect("overflow constructing `time::Duration`"),
+ .expect("overflow constructing `time::SignedDuration`"),
)
}
@@ -108,7 +108,7 @@ impl NumericalStdDuration for u64 {
fn std_hours(self) -> StdDuration {
StdDuration::from_secs(
self.checked_mul(Second::per_t(Hour))
- .expect("overflow constructing `time::Duration`"),
+ .expect("overflow constructing `time::SignedDuration`"),
)
}
@@ -120,7 +120,7 @@ impl NumericalStdDuration for u64 {
fn std_days(self) -> StdDuration {
StdDuration::from_secs(
self.checked_mul(Second::per_t(Day))
- .expect("overflow constructing `time::Duration`"),
+ .expect("overflow constructing `time::SignedDuration`"),
)
}
@@ -132,7 +132,7 @@ impl NumericalStdDuration for u64 {
fn std_weeks(self) -> StdDuration {
StdDuration::from_secs(
self.checked_mul(Second::per_t(Week))
- .expect("overflow constructing `time::Duration`"),
+ .expect("overflow constructing `time::SignedDuration`"),
)
}
}
### external/vendor/time/src/ext/systemtime.rs
@@ -1,9 +1,6 @@
use std::time::SystemTime;
-#[allow(unused_imports, reason = "MSRV of 1.87")]
-use num_conv::prelude::*;
-
-use crate::Duration;
+use crate::SignedDuration;
/// Sealed trait to prevent downstream implementations.
mod sealed {
@@ -13,21 +10,21 @@ mod sealed {
}
/// An extension trait for [`std::time::SystemTime`] that adds methods for
-/// [`time::Duration`](Duration)s.
+/// [`time::SignedDuration`](SignedDuration)s.
pub trait SystemTimeExt: sealed::Sealed {
- /// Adds the given [`Duration`] to the [`SystemTime`], returning `None` is the result cannot be
- /// represented by the underlying data structure.
- fn checked_add_signed(&self, duration: Duration) -> Option<Self>;
-
- /// Subtracts the given [`Duration`] from the [`SystemTime`], returning `None` is the result
+ /// Adds the given [`SignedDuration`] to the [`SystemTime`], returning `None` is the result
/// cannot be represented by the underlying data structure.
- fn checked_sub_signed(&self, duration: Duration) -> Option<Self>;
+ fn checked_add_signed(&self, duration: SignedDuration) -> Option<Self>;
+
+ /// Subtracts the given [`SignedDuration`] from the [`SystemTime`], returning `None` is the
+ /// result cannot be represented by the underlying data structure.
+ fn checked_sub_signed(&self, duration: SignedDuration) -> Option<Self>;
/// Returns the amount of time elapsed from another [`SystemTime`] to this one. This will be
/// negative if `earlier` is later than `self.`
///
- /// If the duration cannot be stored by [`Duration`], the value will be saturated to
- /// [`Duration::MIN`] or [`Duration::MAX`] as appropriate.
+ /// If the duration cannot be stored by [`SignedDuration`], the value will be saturated to
+ /// [`SignedDuration::MIN`] or [`SignedDuration::MAX`] as appropriate.
///
/// # Example
///
@@ -39,12 +36,12 @@ pub trait SystemTimeExt: sealed::Sealed {
/// assert_eq!(other.signed_duration_since(epoch), 1.seconds());
/// assert_eq!(epoch.signed_duration_since(other), (-1).seconds());
/// ```
- fn signed_duration_since(&self, earlier: Self) -> Duration;
+ fn signed_duration_since(&self, earlier: Self) -> SignedDuration;
}
impl SystemTimeExt for SystemTime {
#[inline]
- fn checked_add_signed(&self, duration: Duration) -> Option<Self> {
+ fn checked_add_signed(&self, duration: SignedDuration) -> Option<Self> {
if duration.is_positive() {
self.checked_add(duration.unsigned_abs())
} else if duration.is_negative() {
@@ -55,7 +52,7 @@ impl SystemTimeExt for SystemTime {
}
#[inline]
- fn checked_sub_signed(&self, duration: Duration) -> Option<Self> {
+ fn checked_sub_signed(&self, duration: SignedDuration) -> Option<Self> {
if duration.is_positive() {
self.checked_sub(duration.unsigned_abs())
} else if duration.is_negative() {
@@ -66,19 +63,19 @@ impl SystemTimeExt for SystemTime {
}
#[inline]
- fn signed_duration_since(&self, earlier: Self) -> Duration {
+ fn signed_duration_since(&self, earlier: Self) -> SignedDuration {
match self.duration_since(earlier) {
- Ok(duration) => duration.try_into().unwrap_or(Duration::MAX),
+ Ok(duration) => duration.try_into().unwrap_or(SignedDuration::MAX),
Err(err) => {
let seconds = match i64::try_from(err.duration().as_secs()) {
Ok(seconds) => -seconds,
- Err(_) => return Duration::MIN,
+ Err(_) => return SignedDuration::MIN,
};
let nanoseconds = -err.duration().subsec_nanos().cast_signed();
// Safety: `nanoseconds` is guaranteed to be between -999_999_999 and 0
// inclusive.
- unsafe { Duration::new_unchecked(seconds, nanoseconds) }
+ unsafe { SignedDuration::new_unchecked(seconds, nanoseconds) }
}
}
}
### external/vendor/time/src/format_description/borrowed_format_item.rs
@@ -11,13 +11,19 @@ use crate::format_description::Component;
/// A complete description of how to format and parse a type.
#[non_exhaustive]
#[cfg_attr(not(feature = "alloc"), derive(Debug))]
-#[derive(Clone, PartialEq, Eq)]
+#[derive(Clone, Eq)]
pub enum BorrowedFormatItem<'a> {
/// Bytes that are formatted as-is.
///
/// **Note**: These bytes **should** be UTF-8, but are not required to be. The value is passed
/// through `String::from_utf8_lossy` when necessary.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `StringLiteral` instead; raw bytes are not recommended"
+ )]
Literal(&'a [u8]),
+ /// A string that is formatted as-is.
+ StringLiteral(&'a str),
/// A minimal representation of a single non-literal item.
Component(Component),
/// A series of literals or components that collectively form a partial or complete
@@ -39,7 +45,9 @@ impl fmt::Debug for BorrowedFormatItem<'_> {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
+ #[expect(deprecated)]
Self::Literal(literal) => f.write_str(&String::from_utf8_lossy(literal)),
+ Self::StringLiteral(literal) => f.write_str(literal),
Self::Component(component) => component.fmt(f),
Self::Compound(compound) => compound.fmt(f),
Self::Optional(item) => f.debug_tuple("Optional").field(item).finish(),
@@ -48,6 +56,27 @@ impl fmt::Debug for BorrowedFormatItem<'_> {
}
}
+impl PartialEq for BorrowedFormatItem<'_> {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ // trivial equality checks
+ #[expect(deprecated)]
+ (Self::Literal(a), Self::Literal(b)) => a == b,
+ (Self::StringLiteral(a), Self::StringLiteral(b)) => a == b,
+ (Self::Component(a), Self::Component(b)) => a == b,
+ (Self::Compound(a), Self::Compound(b)) => a == b,
+ (Self::Optional(a), Self::Optional(b)) => a == b,
+ (Self::First(a), Self::First(b)) => a == b,
+ // bytes vs string (back-compatibility)
+ #[expect(deprecated)]
+ (Self::Literal(a), Self::StringLiteral(b)) => *a == b.as_bytes(),
+ #[expect(deprecated)]
+ (Self::StringLiteral(a), Self::Literal(b)) => a.as_bytes() == *b,
+ _ => false,
+ }
+ }
+}
+
impl From<Component> for BorrowedFormatItem<'_> {
#[inline]
fn from(component: Component) -> Self {
### external/vendor/time/src/format_description/component.rs
@@ -4,22 +4,58 @@ use crate::format_description::modifier;
/// A component of a larger format description.
#[non_exhaustive]
+#[allow(deprecated)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Component {
/// Day of the month.
Day(modifier::Day),
- /// Month of the year.
- Month(modifier::Month),
+ /// Month of the year in the abbreviated form (e.g. "Jan").
+ MonthShort(modifier::MonthShort),
+ /// Month of the year in the full form (e.g. "January").
+ MonthLong(modifier::MonthLong),
+ /// Month of the year in the numerical form (e.g. "1" for January).
+ MonthNumerical(modifier::MonthNumerical),
/// Ordinal day of the year.
Ordinal(modifier::Ordinal),
- /// Day of the week.
- Weekday(modifier::Weekday),
- /// Week within the year.
- WeekNumber(modifier::WeekNumber),
- /// Year of the date.
- Year(modifier::Year),
- /// Hour of the day.
- Hour(modifier::Hour),
+ /// Weekday in the abbreviated form (e.g. "Mon").
+ WeekdayShort(modifier::WeekdayShort),
+ /// Weekday in the full form (e.g. "Monday").
+ WeekdayLong(modifier::WeekdayLong),
+ /// Weekday number where Sunday is either 0 or 1 depending on the modifier.
+ WeekdaySunday(modifier::WeekdaySunday),
+ /// Weekday number where Monday is either 0 or 1 depending on the modifier.
+ WeekdayMonday(modifier::WeekdayMonday),
+ /// Week number of the year, where week 1 starts is the week beginning on Monday that contains
+ /// January 4.
+ WeekNumberIso(modifier::WeekNumberIso),
+ /// Week number of the year, where week 1 starts on the first Sunday of the calendar year.
+ WeekNumberSunday(modifier::WeekNumberSunday),
+ /// Week number of the year, where week 1 starts on the first Monday of the calendar year.
+ WeekNumberMonday(modifier::WeekNumberMonday),
+ /// The calendar year. Supports the extended range.
+ CalendarYearFullExtendedRange(modifier::CalendarYearFullExtendedRange),
+ /// The calendar year. Does not support the extended range.
+ CalendarYearFullStandardRange(modifier::CalendarYearFullStandardRange),
+ /// The ISO week-based year. Supports the extended range.
+ IsoYearFullExtendedRange(modifier::IsoYearFullExtendedRange),
+ /// The ISO week-based year. Does not support the extended range.
+ IsoYearFullStandardRange(modifier::IsoYearFullStandardRange),
+ /// The century of the calendar year. Supports the extended range.
+ CalendarYearCenturyExtendedRange(modifier::CalendarYearCenturyExtendedRange),
+ /// The century of the calendar year. Does not support the extended range.
+ CalendarYearCenturyStandardRange(modifier::CalendarYearCenturyStandardRange),
+ /// The century of the ISO week-based year. Supports the extended range.
+ IsoYearCenturyExtendedRange(modifier::IsoYearCenturyExtendedRange),
+ /// The century of the ISO week-based year. Does not support the extended range.
+ IsoYearCenturyStandardRange(modifier::IsoYearCenturyStandardRange),
+ /// The last two digits of the calendar year.
+ CalendarYearLastTwo(modifier::CalendarYearLastTwo),
+ /// The last two digits of the ISO week-based year.
+ IsoYearLastTwo(modifier::IsoYearLastTwo),
+ /// Hour of the day using the 12-hour clock.
+ Hour12(modifier::Hour12),
+ /// Hour of the day using the 24-hour clock.
+ Hour24(modifier::Hour24),
/// Minute within the hour.
Minute(modifier::Minute),
/// AM/PM part of the time.
@@ -36,9 +72,267 @@ pub enum Component {
OffsetSecond(modifier::OffsetSecond),
/// A number of bytes to ignore when parsing. This has no effect on formatting.
Ignore(modifier::Ignore),
- /// A Unix timestamp.
- UnixTimestamp(modifier::UnixTimestamp),
+ /// A Unix timestamp in seconds.
+ UnixTimestampSecond(modifier::UnixTimestampSecond),
+ /// A Unix timestamp in milliseconds.
+ UnixTimestampMillisecond(modifier::UnixTimestampMillisecond),
+ /// A Unix timestamp in microseconds.
+ UnixTimestampMicrosecond(modifier::UnixTimestampMicrosecond),
+ /// A Unix timestamp in nanoseconds.
+ UnixTimestampNanosecond(modifier::UnixTimestampNanosecond),
/// The end of input. Parsing this component will fail if there is any input remaining. This
/// component neither affects formatting nor consumes any input when parsing.
End(modifier::End),
+
+ // Start of deprecated components that are no longer emitted by macros or parsers. They must
+ // be maintained for backward compatibility, as downstream users could have constructed them
+ // manually.
+ /// Month of the year.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `MonthShort`, `MonthLong`, or `MonthNumeric` instead"
+ )]
+ Month(modifier::Month),
+ /// Day of the week.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `WeekdayShort`, `WeekdayLong`, or `WeekdaySunday`, or `WeekdayMonday` instead"
+ )]
+ Weekday(modifier::Weekday),
+ /// Week within the year.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `WeekNumberIso`, `WeekNumberSunday`, or `WeekNumberMonday` instead"
+ )]
+ WeekNumber(modifier::WeekNumber),
+ /// Hour of the day.
+ #[deprecated(since = "0.3.48", note = "use `Hour12` or `Hour24` instead")]
+ Hour(modifier::Hour),
+ /// A Unix timestamp.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `UnixTimestampSeconds`, `UnixTimestampMilliseconds`, \
+ `UnixTimestampMicroseconds`, or `UnixTimestampNanoseconds` instead"
+ )]
+ UnixTimestamp(modifier::UnixTimestamp),
+ /// Year of the date.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use one of the various `Year*` components instead"
+ )]
+ Year(modifier::Year),
+}
+
+impl From<Component> for super::format_description_v3::FormatDescriptionV3Inner<'_> {
+ #[inline]
+ fn from(component: Component) -> Self {
+ match component {
+ Component::Day(modifier) => Self::Day(modifier),
+ Component::MonthShort(modifier) => Self::MonthShort(modifier),
+ Component::MonthLong(modifier) => Self::MonthLong(modifier),
+ Component::MonthNumerical(modifier) => Self::MonthNumerical(modifier),
+ Component::Ordinal(modifier) => Self::Ordinal(modifier),
+ Component::WeekdayShort(modifier) => Self::WeekdayShort(modifier),
+ Component::WeekdayLong(modifier) => Self::WeekdayLong(modifier),
+ Component::WeekdaySunday(modifier) => Self::WeekdaySunday(modifier),
+ Component::WeekdayMonday(modifier) => Self::WeekdayMonday(modifier),
+ Component::WeekNumberIso(modifier) => Self::WeekNumberIso(modifier),
+ Component::WeekNumberSunday(modifier) => Self::WeekNumberSunday(modifier),
+ Component::WeekNumberMonday(modifier) => Self::WeekNumberMonday(modifier),
+ Component::CalendarYearFullExtendedRange(modifier) => {
+ Self::CalendarYearFullExtendedRange(modifier)
+ }
+ Component::CalendarYearFullStandardRange(modifier) => {
+ Self::CalendarYearFullStandardRange(modifier)
+ }
+ Component::IsoYearFullExtendedRange(modifier) => {
+ Self::IsoYearFullExtendedRange(modifier)
+ }
+ Component::IsoYearFullStandardRange(modifier) => {
+ Self::IsoYearFullStandardRange(modifier)
+ }
+ Component::CalendarYearCenturyExtendedRange(modifier) => {
+ Self::CalendarYearCenturyExtendedRange(modifier)
+ }
+ Component::CalendarYearCenturyStandardRange(modifier) => {
+ Self::CalendarYearCenturyStandardRange(modifier)
+ }
+ Component::IsoYearCenturyExtendedRange(modifier) => {
+ Self::IsoYearCenturyExtendedRange(modifier)
+ }
+ Component::IsoYearCenturyStandardRange(modifier) => {
+ Self::IsoYearCenturyStandardRange(modifier)
+ }
+ Component::CalendarYearLastTwo(modifier) => Self::CalendarYearLastTwo(modifier),
+ Component::IsoYearLastTwo(modifier) => Self::IsoYearLastTwo(modifier),
+ Component::Hour12(modifier) => Self::Hour12(modifier),
+ Component::Hour24(modifier) => Self::Hour24(modifier),
+ Component::Minute(modifier) => Self::Minute(modifier),
+ Component::Period(modifier) => Self::Period(modifier),
+ Component::Second(modifier) => Self::Second(modifier),
+ Component::Subsecond(modifier) => Self::Subsecond(modifier),
+ Component::OffsetHour(modifier) => Self::OffsetHour(modifier),
+ Component::OffsetMinute(modifier) => Self::OffsetMinute(modifier),
+ Component::OffsetSecond(modifier) => Self::OffsetSecond(modifier),
+ Component::Ignore(modifier) => Self::Ignore(modifier),
+ Component::UnixTimestampSecond(modifier) => Self::UnixTimestampSecond(modifier),
+ Component::UnixTimestampMillisecond(modifier) => {
+ Self::UnixTimestampMillisecond(modifier)
+ }
+ Component::UnixTimestampMicrosecond(modifier) => {
+ Self::UnixTimestampMicrosecond(modifier)
+ }
+ Component::UnixTimestampNanosecond(modifier) => Self::UnixTimestampNanosecond(modifier),
+ Component::End(modifier) => Self::End(modifier),
+
+ // Start of deprecated components.
+ #[expect(deprecated)]
+ Component::Month(modifier) => match modifier.repr {
+ modifier::MonthRepr::Short => Self::MonthShort(
+ modifier::MonthShort::default().with_case_sensitive(modifier.case_sensitive),
+ ),
+ modifier::MonthRepr::Long => Self::MonthLong(
+ modifier::MonthLong::default().with_case_sensitive(modifier.case_sensitive),
+ ),
+ modifier::MonthRepr::Numerical => Self::MonthNumerical(
+ modifier::MonthNumerical::default().with_padding(modifier.padding),
+ ),
+ },
+ #[expect(deprecated)]
+ Component::Weekday(modifier) => match modifier.repr {
+ modifier::WeekdayRepr::Short => Self::WeekdayShort(
+ modifier::WeekdayShort::default().with_case_sensitive(modifier.case_sensitive),
+ ),
+ modifier::WeekdayRepr::Long => Self::WeekdayLong(
+ modifier::WeekdayLong::default().with_case_sensitive(modifier.case_sensitive),
+ ),
+ modifier::WeekdayRepr::Sunday => Self::WeekdaySunday(
+ modifier::WeekdaySunday::default().with_one_indexed(modifier.one_indexed),
+ ),
+ modifier::WeekdayRepr::Monday => Self::WeekdayMonday(
+ modifier::WeekdayMonday::default().with_one_indexed(modifier.one_indexed),
+ ),
+ },
+ #[expect(deprecated)]
+ Component::WeekNumber(modifier) => match modifier.repr {
+ modifier::WeekNumberRepr::Iso => Self::WeekNumberIso(
+ modifier::WeekNumberIso::default().with_padding(modifier.padding),
+ ),
+ modifier::WeekNumberRepr::Sunday => Self::WeekNumberSunday(
+ modifier::WeekNumberSunday::default().with_padding(modifier.padding),
+ ),
+ modifier::WeekNumberRepr::Monday => Self::WeekNumberMonday(
+ modifier::WeekNumberMonday::default().with_padding(modifier.padding),
+ ),
+ },
+ #[expect(deprecated)]
+ Component::Hour(modifier) => {
+ if modifier.is_12_hour_clock {
+ Self::Hour12(modifier::Hour12::default().with_padding(modifier.padding))
+ } else {
+ Self::Hour24(modifier::Hour24::default().with_padding(modifier.padding))
+ }
+ }
+ #[expect(deprecated)]
+ Component::UnixTimestamp(modifier) => match modifier.precision {
+ modifier::UnixTimestampPrecision::Second => Self::UnixTimestampSecond(
+ modifier::UnixTimestampSecond::default()
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ ),
+ modifier::UnixTimestampPrecision::Millisecond => Self::UnixTimestampMillisecond(
+ modifier::UnixTimestampMillisecond::default()
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ ),
+ modifier::UnixTimestampPrecision::Microsecond => Self::UnixTimestampMicrosecond(
+ modifier::UnixTimestampMicrosecond::default()
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ ),
+ modifier::UnixTimestampPrecision::Nanosecond => Self::UnixTimestampNanosecond(
+ modifier::UnixTimestampNanosecond::default()
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ ),
+ },
+ #[expect(deprecated)]
+ Component::Year(modifier) => {
+ match (modifier.iso_week_based, modifier.repr, modifier.range) {
+ (true, modifier::YearRepr::Full, modifier::YearRange::Standard) => {
+ Self::IsoYearFullStandardRange(
+ modifier::IsoYearFullStandardRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (true, modifier::YearRepr::Full, modifier::YearRange::Extended) => {
+ Self::IsoYearFullExtendedRange(
+ modifier::IsoYearFullExtendedRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (false, modifier::YearRepr::Full, modifier::YearRange::Standard) => {
+ Self::CalendarYearFullStandardRange(
+ modifier::CalendarYearFullStandardRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (false, modifier::YearRepr::Full, modifier::YearRange::Extended) => {
+ Self::CalendarYearFullExtendedRange(
+ modifier::CalendarYearFullExtendedRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (true, modifier::YearRepr::Century, modifier::YearRange::Standard) => {
+ Self::IsoYearCenturyStandardRange(
+ modifier::IsoYearCenturyStandardRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (true, modifier::YearRepr::Century, modifier::YearRange::Extended) => {
+ Self::IsoYearCenturyExtendedRange(
+ modifier::IsoYearCenturyExtendedRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (false, modifier::YearRepr::Century, modifier::YearRange::Standard) => {
+ Self::CalendarYearCenturyStandardRange(
+ modifier::CalendarYearCenturyStandardRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (false, modifier::YearRepr::Century, modifier::YearRange::Extended) => {
+ Self::CalendarYearCenturyExtendedRange(
+ modifier::CalendarYearCenturyExtendedRange::default()
+ .with_padding(modifier.padding)
+ .with_sign_is_mandatory(modifier.sign_is_mandatory),
+ )
+ }
+ (true, modifier::YearRepr::LastTwo, modifier::YearRange::Standard) => {
+ Self::IsoYearLastTwo(
+ modifier::IsoYearLastTwo::default().with_padding(modifier.padding),
+ )
+ }
+ (true, modifier::YearRepr::LastTwo, modifier::YearRange::Extended) => {
+ Self::IsoYearLastTwo(
+ modifier::IsoYearLastTwo::default().with_padding(modifier.padding),
+ )
+ }
+ (false, modifier::YearRepr::LastTwo, modifier::YearRange::Standard) => {
+ Self::CalendarYearLastTwo(
+ modifier::CalendarYearLastTwo::default().with_padding(modifier.padding),
+ )
+ }
+ (false, modifier::YearRepr::LastTwo, modifier::YearRange::Extended) => {
+ Self::CalendarYearLastTwo(
+ modifier::CalendarYearLastTwo::default().with_padding(modifier.padding),
+ )
+ }
+ }
+ }
+ }
+ }
}
### external/vendor/time/src/format_description/format_description_v3.rs
@@ -0,0 +1,544 @@
+//! A version 3 format description.
+//!
+//! Unlike versions 1 and 2, this is opaque so as to permit any changes necessary without breaking
+//! downstream users. Other than `FormatDescriptionV3`, all items are internal.
+
+#[cfg(feature = "alloc")]
+use alloc::boxed::Box;
+use core::fmt;
+
+use crate::format_description::modifier;
+
+/// A complete description of how to format and parse a type.
+///
+/// Both for forwards compatibility and to enable optimizations, this type is deliberately opaque
+/// and cannot be constructed by users of the crate. Instead, it is returned by the
+/// `format_description!` macro (when `version=3` is used) as well as the `parse_borrowed` and
+/// `parse_owned` methods.
+#[derive(Clone)]
+pub struct FormatDescriptionV3<'a> {
+ /// The inner `enum` that controls all business logic.
+ pub(crate) inner: FormatDescriptionV3Inner<'a>,
+ /// The maximum number of bytes that are needed to format any value using this format
+ /// description.
+ #[cfg(feature = "formatting")]
+ pub(crate) max_bytes_needed: usize,
+}
+
+impl fmt::Debug for FormatDescriptionV3<'_> {
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ self.inner.fmt(f)
+ }
+}
+
+impl FormatDescriptionV3<'_> {
+ /// Convert the format description to an owned version, enabling it to be stored without regard
+ /// for lifetime.
+ #[cfg(feature = "alloc")]
+ #[inline]
+ pub fn to_owned(self) -> FormatDescriptionV3<'static> {
+ FormatDescriptionV3 {
+ inner: self.inner.into_owned(),
+ #[cfg(feature = "formatting")]
+ max_bytes_needed: self.max_bytes_needed,
+ }
+ }
+}
+
+/// The inner `enum` of a version 3 format description. Controls all business logic.
+// public via `crate::format_description::__private` for macro use
+#[non_exhaustive]
+#[derive(Clone)]
+pub enum FormatDescriptionV3Inner<'a> {
+ /// Day of the month.
+ Day(modifier::Day),
+ /// Month of the year in the abbreviated form (e.g. "Jan").
+ MonthShort(modifier::MonthShort),
+ /// Month of the year in the full form (e.g. "January").
+ MonthLong(modifier::MonthLong),
+ /// Month of the year in the numerical form (e.g. "1" for January).
+ MonthNumerical(modifier::MonthNumerical),
+ /// Ordinal day of the year.
+ Ordinal(modifier::Ordinal),
+ /// Weekday in the abbreviated form (e.g. "Mon").
+ WeekdayShort(modifier::WeekdayShort),
+ /// Weekday in the full form (e.g. "Monday").
+ WeekdayLong(modifier::WeekdayLong),
+ /// Weekday number where Sunday is either 0 or 1 depending on the modifier.
+ WeekdaySunday(modifier::WeekdaySunday),
+ /// Weekday number where Monday is either 0 or 1 depending on the modifier.
+ WeekdayMonday(modifier::WeekdayMonday),
+ /// Week number of the year, where week 1 starts is the week beginning on Monday that contains
+ /// January 4.
+ WeekNumberIso(modifier::WeekNumberIso),
+ /// Week number of the year, where week 1 starts on the first Sunday of the calendar year.
+ WeekNumberSunday(modifier::WeekNumberSunday),
+ /// Week number of the year, where week 1 starts on the first Monday of the calendar year.
+ WeekNumberMonday(modifier::WeekNumberMonday),
+ /// The calendar year. Supports the extended range.
+ CalendarYearFullExtendedRange(modifier::CalendarYearFullExtendedRange),
+ /// The calendar year. Does not support the extended range.
+ CalendarYearFullStandardRange(modifier::CalendarYearFullStandardRange),
+ /// The ISO week-based year. Supports the extended range.
+ IsoYearFullExtendedRange(modifier::IsoYearFullExtendedRange),
+ /// The ISO week-based year. Does not support the extended range.
+ IsoYearFullStandardRange(modifier::IsoYearFullStandardRange),
+ /// The century of the calendar year. Supports the extended range.
+ CalendarYearCenturyExtendedRange(modifier::CalendarYearCenturyExtendedRange),
+ /// The century of the calendar year. Does not support the extended range.
+ CalendarYearCenturyStandardRange(modifier::CalendarYearCenturyStandardRange),
+ /// The century of the ISO week-based year. Supports the extended range.
+ IsoYearCenturyExtendedRange(modifier::IsoYearCenturyExtendedRange),
+ /// The century of the ISO week-based year. Does not support the extended range.
+ IsoYearCenturyStandardRange(modifier::IsoYearCenturyStandardRange),
+ /// The last two digits of the calendar year.
+ CalendarYearLastTwo(modifier::CalendarYearLastTwo),
+ /// The last two digits of the ISO week-based year.
+ IsoYearLastTwo(modifier::IsoYearLastTwo),
+ /// Hour of the day using the 12-hour clock.
+ Hour12(modifier::Hour12),
+ /// Hour of the day using the 24-hour clock.
+ Hour24(modifier::Hour24),
+ /// Minute within the hour.
+ Minute(modifier::Minute),
+ /// AM/PM part of the time.
+ Period(modifier::Period),
+ /// Second within the minute.
+ Second(modifier::Second),
+ /// Subsecond within the second.
+ Subsecond(modifier::Subsecond),
+ /// Hour of the UTC offset.
+ OffsetHour(modifier::OffsetHour),
+ /// Minute within the hour of the UTC offset.
+ OffsetMinute(modifier::OffsetMinute),
+ /// Second within the minute of the UTC offset.
+ OffsetSecond(modifier::OffsetSecond),
+ /// A number of bytes to ignore when parsing. This has no effect on formatting.
+ Ignore(modifier::Ignore),
+ /// A Unix timestamp in seconds.
+ UnixTimestampSecond(modifier::UnixTimestampSecond),
+ /// A Unix timestamp in milliseconds.
+ UnixTimestampMillisecond(modifier::UnixTimestampMillisecond),
+ /// A Unix timestamp in microseconds.
+ UnixTimestampMicrosecond(modifier::UnixTimestampMicrosecond),
+ /// A Unix timestamp in nanoseconds.
+ UnixTimestampNanosecond(modifier::UnixTimestampNanosecond),
+ /// The end of input. Parsing this component will fail if there is any input remaining. This
+ /// component neither affects formatting nor consumes any input when parsing.
+ End(modifier::End),
+ /// A string that is formatted as-is.
+ BorrowedLiteral(&'a str),
+ /// A series of literals or components that collectively form a partial or complete description.
+ BorrowedCompound(&'a [Self]),
+ /// An item that may or may not be present when parsing. If parsing fails, there will be no
+ /// effect on the resulting `struct`.
+ BorrowedOptional {
+ /// Whether the item should be formatted.
+ format: bool,
+ /// The item in question.
+ item: &'a Self,
+ },
+ /// A series of items where, when parsing, the first successful parse is used. When formatting,
+ /// the first item is used. If no items are present, both formatting and parsing are no-ops.
+ BorrowedFirst(&'a [Self]),
+ /// A string that is formatted as-is.
+ #[cfg(feature = "alloc")]
+ OwnedLiteral(Box<str>),
+ /// A series of literals or components that collectively form a partial or complete description.
+ #[cfg(feature = "alloc")]
+ OwnedCompound(Box<[Self]>),
+ /// An item that may or may not be present when parsing. If parsing fails, there will be no
+ /// effect on the resulting `struct`.
+ #[cfg(feature = "alloc")]
+ OwnedOptional {
+ /// Whether the item should be formatted.
+ format: bool,
+ /// The item in question.
+ item: Box<Self>,
+ },
+ /// A series of items where, when parsing, the first successful parse is used. When formatting,
+ /// the first item is used. If no items are present, both formatting and parsing are no-ops.
+ #[cfg(feature = "alloc")]
+ OwnedFirst(Box<[Self]>),
+}
+
+impl fmt::Debug for FormatDescriptionV3Inner<'_> {
+ #[inline]
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::Day(modifier) => modifier.fmt(f),
+ Self::MonthShort(modifier) => modifier.fmt(f),
+ Self::MonthLong(modifier) => modifier.fmt(f),
+ Self::MonthNumerical(modifier) => modifier.fmt(f),
+ Self::Ordinal(modifier) => modifier.fmt(f),
+ Self::WeekdayShort(modifier) => modifier.fmt(f),
+ Self::WeekdayLong(modifier) => modifier.fmt(f),
+ Self::WeekdaySunday(modifier) => modifier.fmt(f),
+ Self::WeekdayMonday(modifier) => modifier.fmt(f),
+ Self::WeekNumberIso(modifier) => modifier.fmt(f),
+ Self::WeekNumberSunday(modifier) => modifier.fmt(f),
+ Self::WeekNumberMonday(modifier) => modifier.fmt(f),
+ Self::CalendarYearFullExtendedRange(modifier) => modifier.fmt(f),
+ Self::CalendarYearFullStandardRange(modifier) => modifier.fmt(f),
+ Self::IsoYearFullExtendedRange(modifier) => modifier.fmt(f),
+ Self::IsoYearFullStandardRange(modifier) => modifier.fmt(f),
+ Self::CalendarYearCenturyExtendedRange(modifier) => modifier.fmt(f),
+ Self::CalendarYearCenturyStandardRange(modifier) => modifier.fmt(f),
+ Self::IsoYearCenturyExtendedRange(modifier) => modifier.fmt(f),
+ Self::IsoYearCenturyStandardRange(modifier) => modifier.fmt(f),
+ Self::CalendarYearLastTwo(modifier) => modifier.fmt(f),
+ Self::IsoYearLastTwo(modifier) => modifier.fmt(f),
+ Self::Hour12(modifier) => modifier.fmt(f),
+ Self::Hour24(modifier) => modifier.fmt(f),
+ Self::Minute(modifier) => modifier.fmt(f),
+ Self::Period(modifier) => modifier.fmt(f),
+ Self::Second(modifier) => modifier.fmt(f),
+ Self::Subsecond(modifier) => modifier.fmt(f),
+ Self::OffsetHour(modifier) => modifier.fmt(f),
+ Self::OffsetMinute(modifier) => modifier.fmt(f),
+ Self::OffsetSecond(modifier) => modifier.fmt(f),
+ Self::Ignore(modifier) => modifier.fmt(f),
+ Self::UnixTimestampSecond(modifier) => modifier.fmt(f),
+ Self::UnixTimestampMillisecond(modifier) => modifier.fmt(f),
+ Self::UnixTimestampMicrosecond(modifier) => modifier.fmt(f),
+ Self::UnixTimestampNanosecond(modifier) => modifier.fmt(f),
+ Self::End(modifier) => modifier.fmt(f),
+ Self::BorrowedLiteral(literal) => f.debug_tuple("Literal").field(literal).finish(),
+ Self::BorrowedCompound(compound) => f.debug_tuple("Compound").field(compound).finish(),
+ Self::BorrowedOptional {
+ format: should_format,
+ item,
+ } => f
+ .debug_struct("Optional")
+ .field("should_format", should_format)
+ .field("item", item)
+ .finish(),
+ Self::BorrowedFirst(items) => f.debug_tuple("First").field(items).finish(),
+ #[cfg(feature = "alloc")]
+ Self::OwnedLiteral(literal) => f.debug_tuple("Literal").field(literal).finish(),
+ #[cfg(feature = "alloc")]
+ Self::OwnedCompound(compound) => f.debug_tuple("Compound").field(compound).finish(),
+ #[cfg(feature = "alloc")]
+ Self::OwnedOptional {
+ format: should_format,
+ item,
+ } => f
+ .debug_struct("Optional")
+ .field("should_format", should_format)
+ .field("item", item)
+ .finish(),
+ #[cfg(feature = "alloc")]
+ Self::OwnedFirst(items) => f.debug_tuple("First").field(items).finish(),
+ }
+ }
+}
+
+impl<'a> FormatDescriptionV3Inner<'a> {
+ /// Recursively convert to an owned version, doing so in-place when possible.
+ #[cfg(feature = "alloc")]
+ fn make_owned_in_place(&mut self) {
+ use alloc::borrow::ToOwned as _;
+ use alloc::boxed::Box;
+
+ match self {
+ Self::BorrowedLiteral(literal) => {
+ *self = Self::OwnedLiteral(literal.to_owned().into_boxed_str());
+ }
+ Self::BorrowedCompound(compound) => {
+ *self = Self::OwnedCompound(
+ compound
+ .iter()
+ .cloned()
+ .map(|item| item.into_owned())
+ .collect(),
+ );
+ }
+ Self::BorrowedOptional { format, item } => {
+ *self = Self::OwnedOptional {
+ format: *format,
+ item: Box::new(item.clone().into_owned()),
+ };
+ }
+ Self::BorrowedFirst(items) => {
+ *self = Self::OwnedFirst(
+ items
+ .iter()
+ .cloned()
+ .map(|item| item.into_owned())
+ .collect(),
+ );
+ }
+ Self::OwnedCompound(compound) => {
+ for item in compound {
+ item.make_owned_in_place();
+ }
+ }
+ Self::OwnedOptional { format: _, item } => {
+ item.make_owned_in_place();
+ }
+ Self::OwnedFirst(items) => {
+ for item in items {
+ item.make_owned_in_place();
+ }
+ }
+ FormatDescriptionV3Inner::Day(_)
+ | FormatDescriptionV3Inner::MonthShort(_)
+ | FormatDescriptionV3Inner::MonthLong(_)
+ | FormatDescriptionV3Inner::MonthNumerical(_)
+ | FormatDescriptionV3Inner::Ordinal(_)
+ | FormatDescriptionV3Inner::WeekdayShort(_)
+ | FormatDescriptionV3Inner::WeekdayLong(_)
+ | FormatDescriptionV3Inner::WeekdaySunday(_)
+ | FormatDescriptionV3Inner::WeekdayMonday(_)
+ | FormatDescriptionV3Inner::WeekNumberIso(_)
+ | FormatDescriptionV3Inner::WeekNumberSunday(_)
+ | FormatDescriptionV3Inner::WeekNumberMonday(_)
+ | FormatDescriptionV3Inner::CalendarYearFullExtendedRange(_)
+ | FormatDescriptionV3Inner::CalendarYearFullStandardRange(_)
+ | FormatDescriptionV3Inner::IsoYearFullExtendedRange(_)
+ | FormatDescriptionV3Inner::IsoYearFullStandardRange(_)
+ | FormatDescriptionV3Inner::CalendarYearCenturyExtendedRange(_)
+ | FormatDescriptionV3Inner::CalendarYearCenturyStandardRange(_)
+ | FormatDescriptionV3Inner::IsoYearCenturyExtendedRange(_)
+ | FormatDescriptionV3Inner::IsoYearCenturyStandardRange(_)
+ | FormatDescriptionV3Inner::CalendarYearLastTwo(_)
+ | FormatDescriptionV3Inner::IsoYearLastTwo(_)
+ | FormatDescriptionV3Inner::Hour12(_)
+ | FormatDescriptionV3Inner::Hour24(_)
+ | FormatDescriptionV3Inner::Minute(_)
+ | FormatDescriptionV3Inner::Period(_)
+ | FormatDescriptionV3Inner::Second(_)
+ | FormatDescriptionV3Inner::Subsecond(_)
+ | FormatDescriptionV3Inner::OffsetHour(_)
+ | FormatDescriptionV3Inner::OffsetMinute(_)
+ | FormatDescriptionV3Inner::OffsetSecond(_)
+ | FormatDescriptionV3Inner::Ignore(_)
+ | FormatDescriptionV3Inner::UnixTimestampSecond(_)
+ | FormatDescriptionV3Inner::UnixTimestampMillisecond(_)
+ | FormatDescriptionV3Inner::UnixTimestampMicrosecond(_)
+ | FormatDescriptionV3Inner::UnixTimestampNanosecond(_)
+ | FormatDescriptionV3Inner::End(_)
+ | FormatDescriptionV3Inner::OwnedLiteral(_) => {
+ // no-op, as these variants do not contain any references
+ }
+ }
+ }
+
+ /// Convert the format description to an owned version in place, replacing borrowed
+ /// components with their owned equivalents.
+ #[cfg(feature = "alloc")]
+ pub(super) fn into_owned(mut self) -> FormatDescriptionV3Inner<'static> {
+ self.make_owned_in_place();
+
+ // Safety: `make_owned_in_place` recursively eliminates all variants that contain
+ // references, so we can transmute between lifetimes freely. ADTs do not vary in layout when
+ // only the lifetime differs.
+ unsafe {
+ core::mem::transmute::<FormatDescriptionV3Inner<'a>, FormatDescriptionV3Inner<'static>>(
+ self,
+ )
+ }
+ }
+
+ /// Convert the inner `enum` to a `FormatDescriptionV3`.
+ #[inline]
+ pub const fn into_opaque(self) -> FormatDescriptionV3<'a> {
+ FormatDescriptionV3 {
+ #[cfg(feature = "formatting")]
+ max_bytes_needed: self.max_bytes_needed(),
+ inner: self,
+ }
+ }
+
+ /// Obtain the maximum number of bytes that are needed to format any value using this format
+ /// description.
+ #[cfg(feature = "formatting")]
+ const fn max_bytes_needed(&self) -> usize {
+ match self {
+ Self::Day(_) => 2,
+ Self::MonthShort(_) => 3,
+ Self::MonthLong(_) => 9,
+ Self::MonthNumerical(_) => 2,
+ Self::Ordinal(_) => 3,
+ Self::WeekdayShort(_) => 3,
+ Self::WeekdayLong(_) => 9,
+ Self::WeekdaySunday(_) | Self::WeekdayMonday(_) => 1,
+ Self::WeekNumberIso(_) | Self::WeekNumberSunday(_) | Self::WeekNumberMonday(_) => 2,
+ Self::CalendarYearFullExtendedRange(_) => 7,
+ Self::CalendarYearFullStandardRange(_) => 5,
+ Self::IsoYearFullExtendedRange(_) => 7,
+ Self::IsoYearFullStandardRange(_) => 5,
+ Self::CalendarYearCenturyExtendedRange(_) => 5,
+ Self::CalendarYearCenturyStandardRange(_) => 3,
+ Self::IsoYearCenturyExtendedRange(_) => 5,
+ Self::IsoYearCenturyStandardRange(_) => 3,
+ Self::CalendarYearLastTwo(_) => 2,
+ Self::IsoYearLastTwo(_) => 2,
+ Self::Hour12(_) | Self::Hour24(_) => 2,
+ Self::Minute(_) | Self::Period(_) | Self::Second(_) => 2,
+ Self::Subsecond(modifier) => match modifier.digits {
+ modifier::SubsecondDigits::One => 1,
+ modifier::SubsecondDigits::Two => 2,
+ modifier::SubsecondDigits::Three => 3,
+ modifier::SubsecondDigits::Four => 4,
+ modifier::SubsecondDigits::Five => 5,
+ modifier::SubsecondDigits::Six => 6,
+ modifier::SubsecondDigits::Seven => 7,
+ modifier::SubsecondDigits::Eight => 8,
+ modifier::SubsecondDigits::Nine => 9,
+ modifier::SubsecondDigits::OneOrMore => 9,
+ },
+ Self::OffsetHour(_) => 3,
+ Self::OffsetMinute(_) | Self::OffsetSecond(_) => 2,
+ #[cfg(feature = "large-dates")]
+ Self::UnixTimestampSecond(_) => 15,
+ #[cfg(not(feature = "large-dates"))]
+ Self::UnixTimestampSecond(_) => 13,
+ #[cfg(feature = "large-dates")]
+ Self::UnixTimestampMillisecond(_) => 18,
+ #[cfg(not(feature = "large-dates"))]
+ Self::UnixTimestampMillisecond(_) => 16,
+ #[cfg(feature = "large-dates")]
+ Self::UnixTimestampMicrosecond(_) => 21,
+ #[cfg(not(feature = "large-dates"))]
+ Self::UnixTimestampMicrosecond(_) => 19,
+ #[cfg(feature = "large-dates")]
+ Self::UnixTimestampNanosecond(_) => 24,
+ #[cfg(not(feature = "large-dates"))]
+ Self::UnixTimestampNanosecond(_) => 22,
+ Self::Ignore(_) | Self::End(_) => 0,
+ FormatDescriptionV3Inner::BorrowedLiteral(s) => s.len(),
+ FormatDescriptionV3Inner::BorrowedCompound(items) => {
+ let mut max_bytes_needed = 0;
+ let mut idx = 0;
+ while idx < items.len() {
+ max_bytes_needed += items[idx].max_bytes_needed();
+ idx += 1;
+ }
+ max_bytes_needed
+ }
+ FormatDescriptionV3Inner::BorrowedOptional { format, item } => {
+ if *format {
+ item.max_bytes_needed()
+ } else {
+ 0
+ }
+ }
+ FormatDescriptionV3Inner::BorrowedFirst(items) => {
+ if items.is_empty() {
+ 0
+ } else {
+ items[0].max_bytes_needed()
+ }
+ }
+ FormatDescriptionV3Inner::OwnedLiteral(s) => s.len(),
+ FormatDescriptionV3Inner::OwnedCompound(items) => {
+ let mut max_bytes_needed = 0;
+ let mut idx = 0;
+ while idx < items.len() {
+ max_bytes_needed += items[idx].max_bytes_needed();
+ idx += 1;
+ }
+ max_bytes_needed
+ }
+ FormatDescriptionV3Inner::OwnedOptional { format, item } => {
+ if *format {
+ item.max_bytes_needed()
+ } else {
+ 0
+ }
+ }
+ FormatDescriptionV3Inner::OwnedFirst(items) => {
+ if items.is_empty() {
+ 0
+ } else {
+ items[0].max_bytes_needed()
+ }
+ }
+ }
+ }
+}
+
+/// A component of a larger format description.
+// public via `crate::format_description::__private` for macro use
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy)]
+pub enum Component {
+ /// Day of the month.
+ Day(modifier::Day),
+ /// Month of the year in the abbreviated form (e.g. "Jan").
+ MonthShort(modifier::MonthShort),
+ /// Month of the year in the full form (e.g. "January").
+ MonthLong(modifier::MonthLong),
+ /// Month of the year in the numerical form (e.g. "1" for January).
+ MonthNumerical(modifier::MonthNumerical),
+ /// Ordinal day of the year.
+ Ordinal(modifier::Ordinal),
+ /// Weekday in the abbreviated form (e.g. "Mon").
+ WeekdayShort(modifier::WeekdayShort),
+ /// Weekday in the full form (e.g. "Monday").
+ WeekdayLong(modifier::WeekdayLong),
+ /// Weekday number where Sunday is either 0 or 1 depending on the modifier.
+ WeekdaySunday(modifier::WeekdaySunday),
+ /// Weekday number where Monday is either 0 or 1 depending on the modifier.
+ WeekdayMonday(modifier::WeekdayMonday),
+ /// Week number of the year, where week 1 starts is the week beginning on Monday that contains
+ /// January 4.
+ WeekNumberIso(modifier::WeekNumberIso),
+ /// Week number of the year, where week 1 starts on the first Sunday of the calendar year.
+ WeekNumberSunday(modifier::WeekNumberSunday),
+ /// Week number of the year, where week 1 starts on the first Monday of the calendar year.
+ WeekNumberMonday(modifier::WeekNumberMonday),
+ /// The calendar year. Supports the extended range.
+ CalendarYearFullExtendedRange(modifier::CalendarYearFullExtendedRange),
+ /// The calendar year. Does not support the extended range.
+ CalendarYearFullStandardRange(modifier::CalendarYearFullStandardRange),
+ /// The ISO week-based year. Supports the extended range.
+ IsoYearFullExtendedRange(modifier::IsoYearFullExtendedRange),
+ /// The ISO week-based year. Does not support the extended range.
+ IsoYearFullStandardRange(modifier::IsoYearFullStandardRange),
+ /// The century of the calendar year. Supports the extended range.
+ CalendarYearCenturyExtendedRange(modifier::CalendarYearCenturyExtendedRange),
+ /// The century of the calendar year. Does not support the extended range.
+ CalendarYearCenturyStandardRange(modifier::CalendarYearCenturyStandardRange),
+ /// The century of the ISO week-based year. Supports the extended range.
+ IsoYearCenturyExtendedRange(modifier::IsoYearCenturyExtendedRange),
+ /// The century of the ISO week-based year. Does not support the extended range.
+ IsoYearCenturyStandardRange(modifier::IsoYearCenturyStandardRange),
+ /// The last two digits of the calendar year.
+ CalendarYearLastTwo(modifier::CalendarYearLastTwo),
+ /// The last two digits of the ISO week-based year.
+ IsoYearLastTwo(modifier::IsoYearLastTwo),
+ /// Hour of the day using the 12-hour clock.
+ Hour12(modifier::Hour12),
+ /// Hour of the day using the 24-hour clock.
+ Hour24(modifier::Hour24),
+ /// Minute within the hour.
+ Minute(modifier::Minute),
+ /// AM/PM part of the time.
+ Period(modifier::Period),
+ /// Second within the minute.
+ Second(modifier::Second),
+ /// Subsecond within the second.
+ Subsecond(modifier::Subsecond),
+ /// Hour of the UTC offset.
+ OffsetHour(modifier::OffsetHour),
+ /// Minute within the hour of the UTC offset.
+ OffsetMinute(modifier::OffsetMinute),
+ /// Second within the minute of the UTC offset.
+ OffsetSecond(modifier::OffsetSecond),
+ /// A number of bytes to ignore when parsing. This has no effect on formatting.
+ Ignore(modifier::Ignore),
+ /// A Unix timestamp in seconds.
+ UnixTimestampSecond(modifier::UnixTimestampSecond),
+ /// A Unix timestamp in milliseconds.
+ UnixTimestampMillisecond(modifier::UnixTimestampMillisecond),
+ /// A Unix timestamp in microseconds.
+ UnixTimestampMicrosecond(modifier::UnixTimestampMicrosecond),
+ /// A Unix timestamp in nanoseconds.
+ UnixTimestampNanosecond(modifier::UnixTimestampNanosecond),
+ /// The end of input. Parsing this component will fail if there is any input remaining. This
+ /// component neither affects formatting nor consumes any input when parsing.
+ End(modifier::End),
+}
### external/vendor/time/src/format_description/mod.rs
@@ -9,12 +9,35 @@
mod borrowed_format_item;
mod component;
+pub(crate) mod format_description_v3;
pub mod modifier;
#[cfg(feature = "alloc")]
mod owned_format_item;
#[cfg(feature = "alloc")]
mod parse;
+/// Well-known formats, typically standards.
+pub mod well_known {
+ pub mod iso8601;
+ mod rfc2822;
+ mod rfc3339;
+
+ #[doc(inline)]
+ pub use iso8601::Iso8601;
+ pub use rfc2822::Rfc2822;
+ pub use rfc3339::Rfc3339;
+}
+
+/// Re-exports of internal types for use in macros.
+///
+/// Do not rely on the existence of this module for any reason. It, in its entirety, is not
+/// considered public API, is not subject to semantic versioning, and may be changed or removed at
+/// any point.
+#[doc(hidden)]
+pub mod __private {
+ pub use super::format_description_v3::{Component, FormatDescriptionV3Inner};
+}
+
pub use borrowed_format_item::BorrowedFormatItem;
#[doc(hidden)]
#[deprecated(since = "0.3.37", note = "use `BorrowedFormatItem` for clarity")]
@@ -23,19 +46,21 @@ pub use borrowed_format_item::BorrowedFormatItem as FormatItem;
pub use owned_format_item::OwnedFormatItem;
pub use self::component::Component;
+pub use self::format_description_v3::FormatDescriptionV3;
+#[cfg(feature = "alloc")]
+#[expect(deprecated, reason = "backwards compatibility")]
+pub use self::parse::parse;
#[cfg(feature = "alloc")]
-pub use self::parse::{
- parse, parse_borrowed, parse_owned, parse_strftime_borrowed, parse_strftime_owned,
-};
+pub use self::parse::{parse_borrowed, parse_owned, parse_strftime_borrowed, parse_strftime_owned};
-/// Well-known formats, typically standards.
-pub mod well_known {
- pub mod iso8601;
- mod rfc2822;
- mod rfc3339;
+/// The type output by the [`format_description!`](crate::macros::format_description) macro.
+pub type StaticFormatDescription = &'static [BorrowedFormatItem<'static>];
- #[doc(inline)]
- pub use iso8601::Iso8601;
- pub use rfc2822::Rfc2822;
- pub use rfc3339::Rfc3339;
+/// Indicate whether the hour is "am" or "pm".
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Period {
+ #[allow(clippy::missing_docs_in_private_items)]
+ Am,
+ #[allow(clippy::missing_docs_in_private_items)]
+ Pm,
}
### external/vendor/time/src/format_description/modifier.rs
@@ -2,6 +2,240 @@
use core::num::NonZero;
+/// Generate the provided code if and only if `pub` is present.
+macro_rules! if_pub {
+ (pub $(#[$attr:meta])*; $($x:tt)*) => {
+ $(#[$attr])*
+ ///
+ /// This function exists since [`Default::default()`] cannot be used in a `const` context.
+ /// It may be removed once that becomes possible. As the [`Default`] trait is in the
+ /// prelude, removing this function in the future will not cause any resolution failures for
+ /// the overwhelming majority of users; only users who use `#![no_implicit_prelude]` will be
+ /// affected. As such it will not be considered a breaking change.
+ $($x)*
+ };
+ ($($_:tt)*) => {};
+}
+
+/// Implement `Default` for the given type. This also generates an inherent implementation of a
+/// `default` method that is `const fn`, permitting the default value to be used in const contexts.
+// Every modifier should use this macro rather than a derived `Default`.
+macro_rules! impl_const_default {
+ ($($(
+ #[doc = $doc:expr])*
+ $(#[cfg($($cfg:tt)+)])?
+ $(#[expect($($expected:tt)+)])?
+ $(@$pub:ident)? $type:ty => $default:expr;
+ )*) => {$(
+ $(#[cfg($($cfg)+)])?
+ $(#[expect($($expected)+)])?
+ impl $type {
+ if_pub! {
+ $($pub)?
+ $(#[doc = $doc])*;
+ #[inline]
+ pub const fn default() -> Self {
+ $default
+ }
+ }
+ }
+
+ $(#[doc = $doc])*
+ $(#[cfg($($cfg)+)])?
+ $(#[expect($($expected)+)])?
+ impl Default for $type {
+ #[inline]
+ fn default() -> Self {
+ $default
+ }
+ }
+ )*};
+}
+
+// Keep this first so that it's shown at the top of documentation.
+impl_const_default! {
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub Day => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value uses the
+ /// [`Numerical`](Self::Numerical) representation.
+ #[expect(deprecated)]
+ MonthRepr => Self::Numerical;
+ @pub MonthShort => Self { case_sensitive: true };
+ @pub MonthLong => Self { case_sensitive: true };
+ @pub MonthNumerical => Self { padding: Padding::Zero };
+ /// Creates an instance of this type that indicates the value uses the
+ /// [`Numerical`](MonthRepr::Numerical) representation, is [padded with zeroes](Padding::Zero),
+ /// and is case-sensitive when parsing.
+ #[expect(deprecated)]
+ @pub Month => Self {
+ padding: Padding::Zero,
+ repr: MonthRepr::Numerical,
+ case_sensitive: true,
+ };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub Ordinal => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value uses the [`Long`](Self::Long) representation.
+ #[expect(deprecated)]
+ WeekdayRepr => Self::Long;
+ @pub WeekdayShort => Self { case_sensitive: true };
+ @pub WeekdayLong => Self { case_sensitive: true };
+ @pub WeekdaySunday => Self { one_indexed: true };
+ @pub WeekdayMonday => Self { one_indexed: true };
+ /// Creates a modifier that indicates the value uses the [`Long`](WeekdayRepr::Long)
+ /// representation and is case-sensitive when parsing. If the representation is changed to a
+ /// numerical one, the instance defaults to one-based indexing.
+ #[expect(deprecated)]
+ @pub Weekday => Self {
+ repr: WeekdayRepr::Long,
+ one_indexed: true,
+ case_sensitive: true,
+ };
+ /// Creates a modifier that indicates that the value uses the [`Iso`](Self::Iso) representation.
+ #[expect(deprecated)]
+ WeekNumberRepr => Self::Iso;
+ @pub WeekNumberIso => Self { padding: Padding::Zero };
+ @pub WeekNumberSunday => Self { padding: Padding::Zero };
+ @pub WeekNumberMonday => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates that the value is [padded with zeroes](Padding::Zero)
+ /// and uses the [`Iso`](WeekNumberRepr::Iso) representation.
+ #[expect(deprecated)]
+ @pub WeekNumber => Self {
+ padding: Padding::Zero,
+ repr: WeekNumberRepr::Iso,
+ };
+ /// Creates a modifier that indicates the value uses the [`Full`](Self::Full) representation.
+ #[expect(deprecated)]
+ YearRepr => Self::Full;
+ /// Creates a modifier that indicates the value uses the [`Extended`](Self::Extended) range.
+ ///
+ /// Note that this is the default modifier for version 1 and 2 format descriptions. Version 3
+ /// format descriptions (which cannot be manually constructed) use `Standard` as the default.
+ #[expect(deprecated)]
+ YearRange => Self::Extended;
+ @pub CalendarYearFullExtendedRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub CalendarYearFullStandardRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub IsoYearFullExtendedRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub IsoYearFullStandardRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub CalendarYearCenturyExtendedRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub CalendarYearCenturyStandardRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub IsoYearCenturyExtendedRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub IsoYearCenturyStandardRange => Self {
+ padding: Padding::Zero,
+ sign_is_mandatory: false,
+ };
+ @pub CalendarYearLastTwo => Self {
+ padding: Padding::Zero,
+ };
+ @pub IsoYearLastTwo => Self {
+ padding: Padding::Zero,
+ };
+ /// Creates a modifier that indicates the value uses the [`Full`](YearRepr::Full)
+ /// representation, is [padded with zeroes](Padding::Zero), uses the Gregorian calendar as its
+ /// base, and only includes the year's sign if necessary.
+ #[expect(deprecated)]
+ @pub Year => Self {
+ padding: Padding::Zero,
+ repr: YearRepr::Full,
+ range: YearRange::Extended,
+ iso_week_based: false,
+ sign_is_mandatory: false,
+ };
+ @pub Hour12 => Self { padding: Padding::Zero };
+ @pub Hour24 => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero) and
+ /// has the 24-hour representation.
+ #[expect(deprecated)]
+ @pub Hour => Self {
+ padding: Padding::Zero,
+ is_12_hour_clock: false,
+ };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub Minute => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value uses the upper-case representation and is
+ /// case-sensitive when parsing.
+ @pub Period => Self {
+ is_uppercase: true,
+ case_sensitive: true,
+ };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub Second => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the stringified value contains [one or more
+ /// digits](Self::OneOrMore).
+ SubsecondDigits => Self::OneOrMore;
+ /// Creates a modifier that indicates the stringified value contains [one or more
+ /// digits](SubsecondDigits::OneOrMore).
+ @pub Subsecond => Self { digits: SubsecondDigits::OneOrMore };
+ /// Creates a modifier that indicates the value only uses a sign for negative values and is
+ /// [padded with zeroes](Padding::Zero).
+ @pub OffsetHour => Self {
+ sign_is_mandatory: false,
+ padding: Padding::Zero,
+ };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub OffsetMinute => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
+ @pub OffsetSecond => Self { padding: Padding::Zero };
+ /// Creates a modifier that indicates the value is [padded with zeroes](Self::Zero).
+ Padding => Self::Zero;
+ /// Creates a modifier that indicates the value represents the [number of seconds](Self::Second)
+ /// since the Unix epoch.
+ #[expect(deprecated)]
+ UnixTimestampPrecision => Self::Second;
+ @pub UnixTimestampSecond => Self { sign_is_mandatory: false };
+ @pub UnixTimestampMillisecond => Self { sign_is_mandatory: false };
+ @pub UnixTimestampMicrosecond => Self { sign_is_mandatory: false };
+ @pub UnixTimestampNanosecond => Self { sign_is_mandatory: false };
+ /// Creates a modifier that indicates the value represents the [number of
+ /// seconds](UnixTimestampPrecision::Second) since the Unix epoch. The sign is not mandatory.
+ #[expect(deprecated)]
+ @pub UnixTimestamp => Self {
+ precision: UnixTimestampPrecision::Second,
+ sign_is_mandatory: false,
+ };
+ /// Indicate that any trailing characters after the end of input are prohibited and will cause
+ /// an error when used with `parse`.
+ TrailingInput => Self::Prohibit;
+ /// Creates a modifier used to represent the end of input, not allowing any trailing input (i.e.
+ /// the input must be fully consumed).
+ @pub End => Self { trailing_input: TrailingInput::Prohibit };
+}
+
+macro_rules! builder_methods {
+ ($(
+ $(#[$fn_attr:meta])*
+ fn $method:ident($field:ident : $field_ty:ty);
+ )+) => {$(
+ $(#[$fn_attr])*
+ #[allow(clippy::needless_update, reason = "needed for types with multiple fields")]
+ #[inline]
+ #[must_use = "this returns the result of the operation, without modifying the original"]
+ pub const fn $method(self, $field: $field_ty) -> Self {
+ Self { $field, ..self }
+ }
+ )+ };
+}
+
/// Day of the month.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -10,8 +244,19 @@ pub struct Day {
pub padding: Padding,
}
+impl Day {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// The representation of a month.
#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "used only in the deprecated `Month` component"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum MonthRepr {
/// The number of the month (January is 1, December is 12).
@@ -22,8 +267,55 @@ pub enum MonthRepr {
Short,
}
+/// Month of the year using the short form of the month name (e.g. "Jan").
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MonthShort {
+ /// Is the value case sensitive when parsing?
+ pub(crate) case_sensitive: bool,
+}
+
+impl MonthShort {
+ builder_methods! {
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
+/// Month of the year using the long form of the month name (e.g. "January").
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MonthLong {
+ /// Is the value case sensitive when parsing?
+ pub(crate) case_sensitive: bool,
+}
+
+impl MonthLong {
+ builder_methods! {
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
+/// Month of the year using a numerical representation (e.g. "1" for January).
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct MonthNumerical {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+}
+
+impl MonthNumerical {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// Month of the year.
#[non_exhaustive]
+#[allow(deprecated)]
+#[deprecated(
+ since = "0.3.48",
+ note = "use `MonthShort`, `MonthLong`, or `MonthNumeric` instead"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Month {
/// The padding to obtain the minimum width.
@@ -34,6 +326,18 @@ pub struct Month {
pub case_sensitive: bool,
}
+#[expect(deprecated)]
+impl Month {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set the manner in which the month is represented.
+ fn with_repr(repr: MonthRepr);
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
/// Ordinal day of the year.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -42,8 +346,19 @@ pub struct Ordinal {
pub padding: Padding,
}
+impl Ordinal {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// The representation used for the day of the week.
#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "used only in the deprecated `Weekday` component"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WeekdayRepr {
/// The short form of the weekday (e.g. "Mon").
@@ -60,8 +375,69 @@ pub enum WeekdayRepr {
Monday,
}
+/// Day of the week using the short form of the weekday (e.g. "Mon").
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekdayShort {
+ /// Is the value case sensitive when parsing?
+ pub(crate) case_sensitive: bool,
+}
+
+impl WeekdayShort {
+ builder_methods! {
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
+/// Day of the week using the long form of the weekday (e.g. "Monday").
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekdayLong {
+ /// Is the value case sensitive when parsing?
+ pub(crate) case_sensitive: bool,
+}
+
+impl WeekdayLong {
+ builder_methods! {
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
+/// Day of the week using a numerical representation with Sunday as the first day of the week.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekdaySunday {
+ /// Is the value zero or one-indexed?
+ pub(crate) one_indexed: bool,
+}
+
+impl WeekdaySunday {
+ builder_methods! {
+ /// Set whether the value is one-indexed.
+ fn with_one_indexed(one_indexed: bool);
+ }
+}
+
+/// Day of the week using a numerical representation with Monday as the first day of the week.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekdayMonday {
+ /// Is the value zero or one-indexed?
+ pub(crate) one_indexed: bool,
+}
+
+impl WeekdayMonday {
+ builder_methods! {
+ /// Set whether the value is one-indexed.
+ fn with_one_indexed(one_indexed: bool);
+ }
+}
+
/// Day of the week.
#[non_exhaustive]
+#[allow(deprecated)]
+#[deprecated(
+ since = "0.3.48",
+ note = "use `WeekdayShort`, `WeekdayLong`, `WeekdaySunday`, or `WeekdayMonday` instead"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Weekday {
/// What form of representation should be used?
@@ -72,57 +448,340 @@ pub struct Weekday {
pub case_sensitive: bool,
}
-/// The representation used for the week number.
-#[non_exhaustive]
+#[expect(deprecated)]
+impl Weekday {
+ builder_methods! {
+ /// Set the manner in which the weekday is represented.
+ fn with_repr(repr: WeekdayRepr);
+ /// Set whether the value is one-indexed when using a numerical representation.
+ fn with_one_indexed(one_indexed: bool);
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
+/// The representation used for the week number.
+#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "used only in the deprecated `WeekNumber` component"
+)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum WeekNumberRepr {
+ /// Week 1 is the week that contains January 4.
+ Iso,
+ /// Week 1 begins on the first Sunday of the calendar year.
+ Sunday,
+ /// Week 1 begins on the first Monday of the calendar year.
+ Monday,
+}
+
+/// Week within the year using the ISO week calendar.
+///
+/// Week 1 is the week that contains January 4. All weeks begin on a Monday.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekNumberIso {
+ /// The padding to obtain the minimum width.
+ pub padding: Padding,
+}
+
+impl WeekNumberIso {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
+/// Week within the calendar year.
+///
+/// Week 1 begins on the first Sunday of the calendar year.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekNumberSunday {
+ /// The padding to obtain the minimum width.
+ pub padding: Padding,
+}
+
+impl WeekNumberSunday {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
+/// Week within the calendar year.
+///
+/// Week 1 begins on the first Monday of the calendar year.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekNumberMonday {
+ /// The padding to obtain the minimum width.
+ pub padding: Padding,
+}
+
+impl WeekNumberMonday {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
+/// Week within the year.
+#[non_exhaustive]
+#[allow(deprecated)]
+#[deprecated(
+ since = "0.3.48",
+ note = "use `WeekNumberIso`, `WeekNumberSunday`, or `WeekNumberMonday` instead"
+)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct WeekNumber {
+ /// The padding to obtain the minimum width.
+ pub padding: Padding,
+ /// What kind of representation should be used?
+ pub repr: WeekNumberRepr,
+}
+
+#[expect(deprecated)]
+impl WeekNumber {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set the manner in which the week number is represented.
+ fn with_repr(repr: WeekNumberRepr);
+ }
+}
+
+/// The representation used for a year value.
+#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "used only in the deprecated `Year` component"
+)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum YearRepr {
+ /// The full value of the year.
+ Full,
+ /// All digits except the last two. Includes the sign, if any.
+ Century,
+ /// Only the last two digits of the year.
+ LastTwo,
+}
+
+/// The range of years that are supported.
+///
+/// This modifier has no effect when the year repr is [`LastTwo`](YearRepr::LastTwo).
+#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "used only in the deprecated `Year` component"
+)]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum YearRange {
+ /// Years between -9999 and 9999 are supported.
+ Standard,
+ /// Years between -999_999 and 999_999 are supported, with the sign being required if the year
+ /// contains more than four digits.
+ ///
+ /// If the `large-dates` feature is not enabled, this variant is equivalent to `Standard`.
+ Extended,
+}
+
+/// Year of the date. All digits are included, the calendar year is used, and the range of years
+/// supported is ±999,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CalendarYearFullExtendedRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl CalendarYearFullExtendedRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is mandatory for non-negative years with more than four digits.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. All digits are included, the calendar year is used, and the range of years
+/// supported is ±9,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CalendarYearFullStandardRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl CalendarYearFullStandardRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is present on non-negative years.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. All digits are included, the ISO week-numbering year is used, and the range of
+/// years supported is ±999,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct IsoYearFullExtendedRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl IsoYearFullExtendedRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is mandatory for non-negative years with more than four digits.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. All digits are included, the ISO week-numbering year is used, and the range of
+/// supported is ±9,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct IsoYearFullStandardRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl IsoYearFullStandardRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is present on non-negative years.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. Only the century is included (i.e. all digits except the last two), the
+/// calendar year is used, and the range of years supported is ±999,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CalendarYearCenturyExtendedRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl CalendarYearCenturyExtendedRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is mandatory for non-negative years with more than four digits.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. Only the century is included (i.e. all digits except the last two), the
+/// calendar year is used, and the range of years supported is ±9,999.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct CalendarYearCenturyStandardRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl CalendarYearCenturyStandardRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is present on non-negative years.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. Only the century is included (i.e. all digits except the last two), the ISO
+/// week-numbering year is used, and the range of years supported is ±999,999.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum WeekNumberRepr {
- /// Week 1 is the week that contains January 4.
- Iso,
- /// Week 1 begins on the first Sunday of the calendar year.
- Sunday,
- /// Week 1 begins on the first Monday of the calendar year.
- Monday,
+pub struct IsoYearCenturyExtendedRange {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
}
-/// Week within the year.
-#[non_exhaustive]
+impl IsoYearCenturyExtendedRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is mandatory for non-negative years with more than four digits.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. Only the century is included (i.e. all digits except the last two), the ISO
+/// week-numbering year is used, and the range of years supported is ±9,999.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct WeekNumber {
+pub struct IsoYearCenturyStandardRange {
/// The padding to obtain the minimum width.
- pub padding: Padding,
- /// What kind of representation should be used?
- pub repr: WeekNumberRepr,
+ pub(crate) padding: Padding,
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
+ pub(crate) sign_is_mandatory: bool,
}
-/// The representation used for a year value.
+impl IsoYearCenturyStandardRange {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the `+` sign is present on non-negative years.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Year of the date. Only the last two digits are included, and the calendar year is used.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum YearRepr {
- /// The full value of the year.
- Full,
- /// All digits except the last two. Includes the sign, if any.
- Century,
- /// Only the last two digits of the year.
- LastTwo,
+pub struct CalendarYearLastTwo {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
}
-/// The range of years that are supported.
-///
-/// This modifier has no effect when the year repr is [`LastTwo`](YearRepr::LastTwo).
+impl CalendarYearLastTwo {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
+/// Year of the date. Only the last two digits are included, and the ISO week-numbering year is
+/// used.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub enum YearRange {
- /// Years between -9999 and 9999 are supported.
- Standard,
- /// Years between -999_999 and 999_999 are supported, with the sign being required if the year
- /// contains more than four digits.
- ///
- /// If the `large-dates` feature is not enabled, this variant is equivalent to `Standard`.
- Extended,
+pub struct IsoYearLastTwo {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+}
+
+impl IsoYearLastTwo {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
}
/// Year of the date.
#[non_exhaustive]
+#[allow(deprecated)]
+#[deprecated(
+ since = "0.3.48",
+ note = "use one of the various `Year*` components instead"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Year {
/// The padding to obtain the minimum width.
@@ -133,12 +792,58 @@ pub struct Year {
pub range: YearRange,
/// Whether the value is based on the ISO week number or the Gregorian calendar.
pub iso_week_based: bool,
- /// Whether the `+` sign is present when a positive year contains fewer than five digits.
+ /// Whether the `+` sign is present when a non-negative year contains fewer digits than
+ /// necessary.
pub sign_is_mandatory: bool,
}
+#[expect(deprecated)]
+impl Year {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set the manner in which the year is represented.
+ fn with_repr(repr: YearRepr);
+ /// Set the range of years that are supported.
+ fn with_range(range: YearRange);
+ /// Set whether the year is based on the ISO week number.
+ fn with_iso_week_based(iso_week_based: bool);
+ /// Set whether the `+` sign is mandatory for positive years with fewer than five digits.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// Hour of the day using a 12-hour clock.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Hour12 {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+}
+
+impl Hour12 {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
+/// Hour of the day using a 24-hour clock.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct Hour24 {
+ /// The padding to obtain the minimum width.
+ pub(crate) padding: Padding,
+}
+
+impl Hour24 {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// Hour of the day.
#[non_exhaustive]
+#[deprecated(since = "0.3.48", note = "use `Hour12` or `Hour24` instead")]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Hour {
/// The padding to obtain the minimum width.
@@ -147,6 +852,16 @@ pub struct Hour {
pub is_12_hour_clock: bool,
}
+#[expect(deprecated)]
+impl Hour {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ /// Set whether the hour uses a 12-hour clock.
+ fn with_is_12_hour_clock(is_12_hour_clock: bool);
+ }
+}
+
/// Minute within the hour.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -155,6 +870,13 @@ pub struct Minute {
pub padding: Padding,
}
+impl Minute {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// AM/PM part of the time.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -167,6 +889,15 @@ pub struct Period {
pub case_sensitive: bool,
}
+impl Period {
+ builder_methods! {
+ /// Set whether the period is uppercase.
+ fn with_is_uppercase(is_uppercase: bool);
+ /// Set whether the value is case sensitive when parsing.
+ fn with_case_sensitive(case_sensitive: bool);
+ }
+}
+
/// Second within the minute.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -175,6 +906,13 @@ pub struct Second {
pub padding: Padding,
}
+impl Second {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// The number of digits present in a subsecond representation.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -210,6 +948,13 @@ pub struct Subsecond {
pub digits: SubsecondDigits,
}
+impl Subsecond {
+ builder_methods! {
+ /// Set the number of digits present in the subsecond representation.
+ fn with_digits(digits: SubsecondDigits);
+ }
+}
+
/// Hour of the UTC offset.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -220,6 +965,15 @@ pub struct OffsetHour {
pub padding: Padding,
}
+impl OffsetHour {
+ builder_methods! {
+ /// Set whether the `+` sign is mandatory for positive values.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// Minute within the hour of the UTC offset.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -228,6 +982,13 @@ pub struct OffsetMinute {
pub padding: Padding,
}
+impl OffsetMinute {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// Second within the minute of the UTC offset.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -236,6 +997,13 @@ pub struct OffsetSecond {
pub padding: Padding,
}
+impl OffsetSecond {
+ builder_methods! {
+ /// Set the padding type.
+ fn with_padding(padding: Padding);
+ }
+}
+
/// Type of padding to ensure a minimum width.
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
@@ -267,10 +1035,19 @@ impl Ignore {
pub const fn count(count: NonZero<u16>) -> Self {
Self { count }
}
+
+ builder_methods! {
+ /// Set the number of bytes to ignore.
+ fn with_count(count: NonZero<u16>);
+ }
}
/// The precision of a Unix timestamp.
#[non_exhaustive]
+#[deprecated(
+ since = "0.3.48",
+ note = "only used in the deprecated `UnixTimestamp` component"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum UnixTimestampPrecision {
/// Seconds since the Unix epoch.
@@ -283,8 +1060,70 @@ pub enum UnixTimestampPrecision {
Nanosecond,
}
+/// A Unix timestamp in seconds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct UnixTimestampSecond {
+ /// Whether the `+` sign must be present for a non-negative timestamp.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl UnixTimestampSecond {
+ builder_methods! {
+ /// Set whether the `+` sign is mandatory for non-negative timestamps.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// A Unix timestamp in milliseconds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct UnixTimestampMillisecond {
+ /// Whether the `+` sign must be present for a non-negative timestamp.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl UnixTimestampMillisecond {
+ builder_methods! {
+ /// Set whether the `+` sign is mandatory for non-negative timestamps.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// A Unix timestamp in microseconds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct UnixTimestampMicrosecond {
+ /// Whether the `+` sign must be present for a non-negative timestamp.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl UnixTimestampMicrosecond {
+ builder_methods! {
+ /// Set whether the `+` sign is mandatory for non-negative timestamps.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
+/// A Unix timestamp in nanoseconds.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct UnixTimestampNanosecond {
+ /// Whether the `+` sign must be present for a non-negative timestamp.
+ pub(crate) sign_is_mandatory: bool,
+}
+
+impl UnixTimestampNanosecond {
+ builder_methods! {
+ /// Set whether the `+` sign is mandatory for non-negative timestamps.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
+}
+
/// A Unix timestamp.
#[non_exhaustive]
+#[allow(deprecated)]
+#[deprecated(
+ since = "0.3.48",
+ note = "use `UnixTimestampSeconds`, `UnixTimestampMilliseconds`, `UnixTimestampMicroseconds`, \
+ or `UnixTimestampNanoseconds` instead"
+)]
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct UnixTimestamp {
/// The precision of the timestamp.
@@ -293,145 +1132,36 @@ pub struct UnixTimestamp {
pub sign_is_mandatory: bool,
}
-/// The end of input.
-///
-/// There is currently not customization for this modifier.
-#[non_exhaustive]
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-pub struct End;
-
-/// Generate the provided code if and only if `pub` is present.
-macro_rules! if_pub {
- (pub $(#[$attr:meta])*; $($x:tt)*) => {
- $(#[$attr])*
- ///
- /// This function exists since [`Default::default()`] cannot be used in a `const` context.
- /// It may be removed once that becomes possible. As the [`Default`] trait is in the
- /// prelude, removing this function in the future will not cause any resolution failures for
- /// the overwhelming majority of users; only users who use `#![no_implicit_prelude]` will be
- /// affected. As such it will not be considered a breaking change.
- $($x)*
- };
- ($($_:tt)*) => {};
+#[expect(deprecated)]
+impl UnixTimestamp {
+ builder_methods! {
+ /// Set the precision of the timestamp.
+ fn with_precision(precision: UnixTimestampPrecision);
+ /// Set whether the `+` sign is mandatory for non-negative timestamps.
+ fn with_sign_is_mandatory(sign_is_mandatory: bool);
+ }
}
-/// Implement `Default` for the given type. This also generates an inherent implementation of a
-/// `default` method that is `const fn`, permitting the default value to be used in const contexts.
-// Every modifier should use this macro rather than a derived `Default`.
-macro_rules! impl_const_default {
- ($($(#[$doc:meta])* $(@$pub:ident)? $type:ty => $default:expr;)*) => {$(
- impl $type {
- if_pub! {
- $($pub)?
- $(#[$doc])*;
- #[inline]
- pub const fn default() -> Self {
- $default
- }
- }
- }
+/// Whether trailing input after the declared end is permitted.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum TrailingInput {
+ /// Trailing input is not permitted and will cause an error.
+ Prohibit,
+ /// Trailing input is permitted but discarded.
+ Discard,
+}
- $(#[$doc])*
- impl Default for $type {
- #[inline]
- fn default() -> Self {
- $default
- }
- }
- )*};
+/// The end of input.
+#[non_exhaustive]
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub struct End {
+ /// How to handle any input after this component.
+ pub(crate) trailing_input: TrailingInput,
}
-impl_const_default! {
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub Day => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the value uses the
- /// [`Numerical`](Self::Numerical) representation.
- MonthRepr => Self::Numerical;
- /// Creates an instance of this type that indicates the value uses the
- /// [`Numerical`](MonthRepr::Numerical) representation, is [padded with zeroes](Padding::Zero),
- /// and is case-sensitive when parsing.
- @pub Month => Self {
- padding: Padding::Zero,
- repr: MonthRepr::Numerical,
- case_sensitive: true,
- };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub Ordinal => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the value uses the [`Long`](Self::Long) representation.
- WeekdayRepr => Self::Long;
- /// Creates a modifier that indicates the value uses the [`Long`](WeekdayRepr::Long)
- /// representation and is case-sensitive when parsing. If the representation is changed to a
- /// numerical one, the instance defaults to one-based indexing.
- @pub Weekday => Self {
- repr: WeekdayRepr::Long,
- one_indexed: true,
- case_sensitive: true,
- };
- /// Creates a modifier that indicates that the value uses the [`Iso`](Self::Iso) representation.
- WeekNumberRepr => Self::Iso;
- /// Creates a modifier that indicates that the value is [padded with zeroes](Padding::Zero)
- /// and uses the [`Iso`](WeekNumberRepr::Iso) representation.
- @pub WeekNumber => Self {
- padding: Padding::Zero,
- repr: WeekNumberRepr::Iso,
- };
- /// Creates a modifier that indicates the value uses the [`Full`](Self::Full) representation.
- YearRepr => Self::Full;
- /// Creates a modifier that indicates the value uses the [`Extended`](Self::Extended) range.
- YearRange => Self::Extended;
- /// Creates a modifier that indicates the value uses the [`Full`](YearRepr::Full)
- /// representation, is [padded with zeroes](Padding::Zero), uses the Gregorian calendar as its
- /// base, and only includes the year's sign if necessary.
- @pub Year => Self {
- padding: Padding::Zero,
- repr: YearRepr::Full,
- range: YearRange::Extended,
- iso_week_based: false,
- sign_is_mandatory: false,
- };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero) and
- /// has the 24-hour representation.
- @pub Hour => Self {
- padding: Padding::Zero,
- is_12_hour_clock: false,
- };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub Minute => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the value uses the upper-case representation and is
- /// case-sensitive when parsing.
- @pub Period => Self {
- is_uppercase: true,
- case_sensitive: true,
- };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub Second => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the stringified value contains [one or more
- /// digits](Self::OneOrMore).
- SubsecondDigits => Self::OneOrMore;
- /// Creates a modifier that indicates the stringified value contains [one or more
- /// digits](SubsecondDigits::OneOrMore).
- @pub Subsecond => Self { digits: SubsecondDigits::OneOrMore };
- /// Creates a modifier that indicates the value only uses a sign for negative values and is
- /// [padded with zeroes](Padding::Zero).
- @pub OffsetHour => Self {
- sign_is_mandatory: false,
- padding: Padding::Zero,
- };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub OffsetMinute => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the value is [padded with zeroes](Padding::Zero).
- @pub OffsetSecond => Self { padding: Padding::Zero };
- /// Creates a modifier that indicates the value is [padded with zeroes](Self::Zero).
- Padding => Self::Zero;
- /// Creates a modifier that indicates the value represents the [number of seconds](Self::Second)
- /// since the Unix epoch.
- UnixTimestampPrecision => Self::Second;
- /// Creates a modifier that indicates the value represents the [number of
- /// seconds](UnixTimestampPrecision::Second) since the Unix epoch. The sign is not mandatory.
- @pub UnixTimestamp => Self {
- precision: UnixTimestampPrecision::Second,
- sign_is_mandatory: false,
- };
- /// Creates a modifier used to represent the end of input.
- @pub End => End;
+impl End {
+ builder_methods! {
+ /// Set how to handle any input after this component.
+ fn with_trailing_input(trailing_input: TrailingInput);
+ }
}
### external/vendor/time/src/format_description/owned_format_item.rs
@@ -10,13 +10,19 @@ use crate::format_description::{BorrowedFormatItem, Component};
/// A complete description of how to format and parse a type.
#[non_exhaustive]
-#[derive(Clone, PartialEq, Eq)]
+#[derive(Clone, Eq)]
pub enum OwnedFormatItem {
/// Bytes that are formatted as-is.
///
/// **Note**: These bytes **should** be UTF-8, but are not required to be. The value is passed
/// through `String::from_utf8_lossy` when necessary.
+ #[deprecated(
+ since = "0.3.48",
+ note = "use `StringLiteral` instead; raw bytes are not recommended"
+ )]
Literal(Box<[u8]>),
+ /// A string that is formatted as-is.
+ StringLiteral(Box<str>),
/// A minimal representation of a single non-literal item.
Component(Component),
/// A series of literals or components that collectively form a partial or complete
@@ -37,7 +43,9 @@ impl fmt::Debug for OwnedFormatItem {
#[inline]
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
+ #[expect(deprecated)]
Self::Literal(literal) => f.write_str(&String::from_utf8_lossy(literal)),
+ Self::StringLiteral(literal) => f.write_str(literal),
Self::Component(component) => component.fmt(f),
Self::Compound(compound) => compound.fmt(f),
Self::Optional(item) => f.debug_tuple("Optional").field(item).finish(),
@@ -46,6 +54,27 @@ impl fmt::Debug for OwnedFormatItem {
}
}
+impl PartialEq for OwnedFormatItem {
+ fn eq(&self, other: &Self) -> bool {
+ match (self, other) {
+ // trivial equality checks
+ #[expect(deprecated)]
+ (Self::Literal(a), Self::Literal(b)) => a == b,
+ (Self::StringLiteral(a), Self::StringLiteral(b)) => a == b,
+ (Self::Component(a), Self::Component(b)) => a == b,
+ (Self::Compound(a), Self::Compound(b)) => a == b,
+ (Self::Optional(a), Self::Optional(b)) => a == b,
+ (Self::First(a), Self::First(b)) => a == b,
+ // bytes vs string (back-compatibility)
+ #[expect(deprecated)]
+ (Self::Literal(a), Self::StringLiteral(b)) => &**a == b.as_bytes(),
+ #[expect(deprecated)]
+ (Self::StringLiteral(a), Self::Literal(b)) => a.as_bytes() == &**b,
+ _ => false,
+ }
+ }
+}
+
impl From<BorrowedFormatItem<'_>> for OwnedFormatItem {
#[inline]
fn from(item: BorrowedFormatItem<'_>) -> Self {
@@ -57,27 +86,22 @@ impl From<&BorrowedFormatItem<'_>> for OwnedFormatItem {
#[inline]
fn from(item: &BorrowedFormatItem<'_>) -> Self {
match item {
+ #[expect(deprecated)]
BorrowedFormatItem::Literal(literal) => {
Self::Literal(literal.to_vec().into_boxed_slice())
}
+ BorrowedFormatItem::StringLiteral(literal) => {
+ use alloc::borrow::ToOwned as _;
+ Self::StringLiteral((*literal).to_owned().into_boxed_str())
+ }
BorrowedFormatItem::Component(component) => Self::Component(*component),
- BorrowedFormatItem::Compound(compound) => Self::Compound(
- compound
- .iter()
- .cloned()
- .map(Into::into)
- .collect::<Vec<_>>()
- .into_boxed_slice(),
- ),
+ BorrowedFormatItem::Compound(compound) => {
+ Self::Compound(compound.iter().cloned().map(Into::into).collect())
+ }
BorrowedFormatItem::Optional(item) => Self::Optional(Box::new((*item).into())),
- BorrowedFormatItem::First(items) => Self::First(
- items
- .iter()
- .cloned()
- .map(Into::into)
- .collect::<Vec<_>>()
- .into_boxed_slice(),
- ),
+ BorrowedFormatItem::First(items) => {
+ Self::First(items.iter().cloned().map(Into::into).collect())
+ }
}
}
}
@@ -89,18 +113,13 @@ impl From<Vec<BorrowedFormatItem<'_>>> for OwnedFormatItem {
}
}
-impl<'a, T: AsRef<[BorrowedFormatItem<'a>]> + ?Sized> From<&T> for OwnedFormatItem {
+impl<'a, T> From<&T> for OwnedFormatItem
+where
+ T: AsRef<[BorrowedFormatItem<'a>]> + ?Sized,
+{
#[inline]
fn from(items: &T) -> Self {
- Self::Compound(
- items
- .as_ref()
- .iter()
- .cloned()
- .map(Into::into)
- .collect::<Vec<_>>()
- .into_boxed_slice(),
- )
+ Self::Compound(items.as_ref().iter().cloned().map(Into::into).collect())
}
}
### external/vendor/time/src/format_description/parse/ast.rs
@@ -1,387 +0,0 @@
-//! AST for parsing format descriptions.
-
-use alloc::boxed::Box;
-use alloc::string::String;
-use alloc::vec::Vec;
-use core::iter;
-
-use super::{lexer, unused, Error, Location, Spanned, SpannedValue, Unused};
-use crate::internal_macros::bug;
-
-/// One part of a complete format description.
-pub(super) enum Item<'a> {
- /// A literal string, formatted and parsed as-is.
- ///
- /// This should never be present inside a nested format description.
- Literal(Spanned<&'a [u8]>),
- /// A sequence of brackets. The first acts as the escape character.
- ///
- /// This should never be present if the lexer has `BACKSLASH_ESCAPE` set to `true`.
- EscapedBracket {
- /// The first bracket.
- _first: Unused<Location>,
- /// The second bracket.
- _second: Unused<Location>,
- },
- /// Part of a type, along with its modifiers.
- Component {
- /// Where the opening bracket was in the format string.
- _opening_bracket: Unused<Location>,
- /// Whitespace between the opening bracket and name.
- _leading_whitespace: Unused<Option<Spanned<&'a [u8]>>>,
- /// The name of the component.
- name: Spanned<&'a [u8]>,
- /// The modifiers for the component.
- modifiers: Box<[Modifier<'a>]>,
- /// Whitespace between the modifiers and closing bracket.
- _trailing_whitespace: Unused<Option<Spanned<&'a [u8]>>>,
- /// Where the closing bracket was in the format string.
- _closing_bracket: Unused<Location>,
- },
- /// An optional sequence of items.
- Optional {
- /// Where the opening bracket was in the format string.
- opening_bracket: Location,
- /// Whitespace between the opening bracket and "optional".
- _leading_whitespace: Unused<Option<Spanned<&'a [u8]>>>,
- /// The "optional" keyword.
- _optional_kw: Unused<Spanned<&'a [u8]>>,
- /// Whitespace between the "optional" keyword and the opening bracket.
- _whitespace: Unused<Spanned<&'a [u8]>>,
- /// The items within the optional sequence.
- nested_format_description: NestedFormatDescription<'a>,
- /// Where the closing bracket was in the format string.
- closing_bracket: Location,
- },
- /// The first matching parse of a sequence of items.
- First {
- /// Where the opening bracket was in the format string.
- opening_bracket: Location,
- /// Whitespace between the opening bracket and "first".
- _leading_whitespace: Unused<Option<Spanned<&'a [u8]>>>,
- /// The "first" keyword.
- _first_kw: Unused<Spanned<&'a [u8]>>,
- /// Whitespace between the "first" keyword and the opening bracket.
- _whitespace: Unused<Spanned<&'a [u8]>>,
- /// The sequences of items to try.
- nested_format_descriptions: Box<[NestedFormatDescription<'a>]>,
- /// Where the closing bracket was in the format string.
- closing_bracket: Location,
- },
-}
-
-/// A format description that is nested within another format description.
-pub(super) struct NestedFormatDescription<'a> {
- /// Where the opening bracket was in the format string.
- pub(super) _opening_bracket: Unused<Location>,
- /// The items within the nested format description.
- pub(super) items: Box<[Item<'a>]>,
- /// Where the closing bracket was in the format string.
- pub(super) _closing_bracket: Unused<Location>,
- /// Whitespace between the closing bracket and the next item.
- pub(super) _trailing_whitespace: Unused<Option<Spanned<&'a [u8]>>>,
-}
-
-/// A modifier for a component.
-pub(super) struct Modifier<'a> {
- /// Whitespace preceding the modifier.
- pub(super) _leading_whitespace: Unused<Spanned<&'a [u8]>>,
- /// The key of the modifier.
- pub(super) key: Spanned<&'a [u8]>,
- /// Where the colon of the modifier was in the format string.
- pub(super) _colon: Unused<Location>,
- /// The value of the modifier.
- pub(super) value: Spanned<&'a [u8]>,
-}
-
-/// Parse the provided tokens into an AST.
-#[inline]
-pub(super) fn parse<
- 'item: 'iter,
- 'iter,
- I: Iterator<Item = Result<lexer::Token<'item>, Error>>,
- const VERSION: usize,
->(
- tokens: &'iter mut lexer::Lexed<I>,
-) -> impl Iterator<Item = Result<Item<'item>, Error>> + 'iter {
- validate_version!(VERSION);
- parse_inner::<_, false, VERSION>(tokens)
-}
-
-/// Parse the provided tokens into an AST. The const generic indicates whether the resulting
-/// [`Item`] will be used directly or as part of a [`NestedFormatDescription`].
-#[inline]
-fn parse_inner<
- 'item,
- I: Iterator<Item = Result<lexer::Token<'item>, Error>>,
- const NESTED: bool,
- const VERSION: usize,
->(
- tokens: &mut lexer::Lexed<I>,
-) -> impl Iterator<Item = Result<Item<'item>, Error>> + '_ {
- validate_version!(VERSION);
- iter::from_fn(move || {
- if NESTED && tokens.peek_closing_bracket().is_some() {
- return None;
- }
-
- let next = match tokens.next()? {
- Ok(token) => token,
- Err(err) => return Some(Err(err)),
- };
-
- Some(match next {
- lexer::Token::Literal(Spanned { value: _, span: _ }) if NESTED => {
- bug!("literal should not be present in nested description")
- }
- lexer::Token::Literal(value) => Ok(Item::Literal(value)),
- lexer::Token::Bracket {
- kind: lexer::BracketKind::Opening,
- location,
- } => {
- if version!(..=1) {
- if let Some(second_location) = tokens.next_if_opening_bracket() {
- Ok(Item::EscapedBracket {
- _first: unused(location),
- _second: unused(second_location),
- })
- } else {
- parse_component::<_, VERSION>(location, tokens)
- }
- } else {
- parse_component::<_, VERSION>(location, tokens)
- }
- }
- lexer::Token::Bracket {
- kind: lexer::BracketKind::Closing,
- location: _,
- } if NESTED => {
- bug!("closing bracket should be caught by the `if` statement")
- }
- lexer::Token::Bracket {
- kind: lexer::BracketKind::Closing,
- location: _,
- } => {
- bug!("closing bracket should have been consumed by `parse_component`")
- }
- lexer::Token::ComponentPart {
- kind: _, // whitespace is significant in nested components
- value,
- } if NESTED => Ok(Item::Literal(value)),
- lexer::Token::ComponentPart { kind: _, value: _ } => {
- bug!("component part should have been consumed by `parse_component`")
- }
- })
- })
-}
-
-/// Parse a component. This assumes that the opening bracket has already been consumed.
-fn parse_component<
- 'a,
- I: Iterator<Item = Result<lexer::Token<'a>, Error>>,
- const VERSION: usize,
->(
- opening_bracket: Location,
- tokens: &mut lexer::Lexed<I>,
-) -> Result<Item<'a>, Error> {
- validate_version!(VERSION);
- let leading_whitespace = tokens.next_if_whitespace();
-
- let Some(name) = tokens.next_if_not_whitespace() else {
- let span = match leading_whitespace {
- Some(Spanned { value: _, span }) => span,
- None => opening_bracket.to_self(),
- };
- return Err(Error {
- _inner: unused(span.error("expected component name")),
- public: crate::error::InvalidFormatDescription::MissingComponentName {
- index: span.start.byte as usize,
- },
- });
- };
-
- if *name == b"optional" {
- let Some(whitespace) = tokens.next_if_whitespace() else {
- return Err(Error {
- _inner: unused(name.span.error("expected whitespace after `optional`")),
- public: crate::error::InvalidFormatDescription::Expected {
- what: "whitespace after `optional`",
- index: name.span.end.byte as usize,
- },
- });
- };
-
- let nested = parse_nested::<_, VERSION>(whitespace.span.end, tokens)?;
-
- let Some(closing_bracket) = tokens.next_if_closing_bracket() else {
- return Err(Error {
- _inner: unused(opening_bracket.error("unclosed bracket")),
- public: crate::error::InvalidFormatDescription::UnclosedOpeningBracket {
- index: opening_bracket.byte as usize,
- },
- });
- };
-
- return Ok(Item::Optional {
- opening_bracket,
- _leading_whitespace: unused(leading_whitespace),
- _optional_kw: unused(name),
- _whitespace: unused(whitespace),
- nested_format_description: nested,
- closing_bracket,
- });
- }
-
- if *name == b"first" {
- let Some(whitespace) = tokens.next_if_whitespace() else {
- return Err(Error {
- _inner: unused(name.span.error("expected whitespace after `first`")),
- public: crate::error::InvalidFormatDescription::Expected {
- what: "whitespace after `first`",
- index: name.span.end.byte as usize,
- },
- });
- };
-
- let mut nested_format_descriptions = Vec::new();
- while let Ok(description) = parse_nested::<_, VERSION>(whitespace.span.end, tokens) {
- nested_format_descriptions.push(description);
- }
-
- let Some(closing_bracket) = tokens.next_if_closing_bracket() else {
- return Err(Error {
- _inner: unused(opening_bracket.error("unclosed bracket")),
- public: crate::error::InvalidFormatDescription::UnclosedOpeningBracket {
- index: opening_bracket.byte as usize,
- },
- });
- };
-
- return Ok(Item::First {
- opening_bracket,
- _leading_whitespace: unused(leading_whitespace),
- _first_kw: unused(name),
- _whitespace: unused(whitespace),
- nested_format_descriptions: nested_format_descriptions.into_boxed_slice(),
- closing_bracket,
- });
- }
-
- let mut modifiers = Vec::new();
- let trailing_whitespace = loop {
- let Some(whitespace) = tokens.next_if_whitespace() else {
- break None;
- };
-
- // This is not necessary for proper parsing, but provides a much better error when a nested
- // description is used where it's not allowed.
- if let Some(location) = tokens.next_if_opening_bracket() {
- return Err(Error {
- _inner: unused(
- location
- .to_self()
- .error("modifier must be of the form `key:value`"),
- ),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::from("["),
- index: location.byte as usize,
- },
- });
- }
-
- let Some(Spanned { value, span }) = tokens.next_if_not_whitespace() else {
- break Some(whitespace);
- };
-
- let Some(colon_index) = value.iter().position(|&b| b == b':') else {
- return Err(Error {
- _inner: unused(span.error("modifier must be of the form `key:value`")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::from_utf8_lossy(value).into_owned(),
- index: span.start.byte as usize,
- },
- });
- };
- let key = &value[..colon_index];
- let value = &value[colon_index + 1..];
-
- if key.is_empty() {
- return Err(Error {
- _inner: unused(span.shrink_to_start().error("expected modifier key")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::new(),
- index: span.start.byte as usize,
- },
- });
- }
- if value.is_empty() {
- return Err(Error {
- _inner: unused(span.shrink_to_end().error("expected modifier value")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::new(),
- index: span.shrink_to_end().start.byte as usize,
- },
- });
- }
-
- modifiers.push(Modifier {
- _leading_whitespace: unused(whitespace),
- key: key.spanned(span.shrink_to_before(colon_index as u32)),
- _colon: unused(span.start.offset(colon_index as u32)),
- value: value.spanned(span.shrink_to_after(colon_index as u32)),
- });
- };
-
- let Some(closing_bracket) = tokens.next_if_closing_bracket() else {
- return Err(Error {
- _inner: unused(opening_bracket.error("unclosed bracket")),
- public: crate::error::InvalidFormatDescription::UnclosedOpeningBracket {
- index: opening_bracket.byte as usize,
- },
- });
- };
-
- Ok(Item::Component {
- _opening_bracket: unused(opening_bracket),
- _leading_whitespace: unused(leading_whitespace),
- name,
- modifiers: modifiers.into_boxed_slice(),
- _trailing_whitespace: unused(trailing_whitespace),
- _closing_bracket: unused(closing_bracket),
- })
-}
-
-/// Parse a nested format description. The location provided is the most recent one consumed.
-#[inline]
-fn parse_nested<'a, I: Iterator<Item = Result<lexer::Token<'a>, Error>>, const VERSION: usize>(
- last_location: Location,
- tokens: &mut lexer::Lexed<I>,
-) -> Result<NestedFormatDescription<'a>, Error> {
- validate_version!(VERSION);
- let Some(opening_bracket) = tokens.next_if_opening_bracket() else {
- return Err(Error {
- _inner: unused(last_location.error("expected opening bracket")),
- public: crate::error::InvalidFormatDescription::Expected {
- what: "opening bracket",
- index: last_location.byte as usize,
- },
- });
- };
- let items = parse_inner::<_, true, VERSION>(tokens).collect::<Result<_, _>>()?;
- let Some(closing_bracket) = tokens.next_if_closing_bracket() else {
- return Err(Error {
- _inner: unused(opening_bracket.error("unclosed bracket")),
- public: crate::error::InvalidFormatDescription::UnclosedOpeningBracket {
- index: opening_bracket.byte as usize,
- },
- });
- };
- let trailing_whitespace = tokens.next_if_whitespace();
-
- Ok(NestedFormatDescription {
- _opening_bracket: unused(opening_bracket),
- items,
- _closing_bracket: unused(closing_bracket),
- _trailing_whitespace: unused(trailing_whitespace),
- })
-}
### external/vendor/time/src/format_description/parse/format_item.rs
@@ -1,163 +1,92 @@
//! Typed, validated representation of a parsed format description.
-use alloc::boxed::Box;
-use alloc::string::String;
+use alloc::borrow::ToOwned as _;
use core::num::NonZero;
use core::str::{self, FromStr};
-use super::{ast, unused, Error, Span, Spanned};
-use crate::internal_macros::bug;
-
-/// Parse an AST iterator into a sequence of format items.
-#[inline]
-pub(super) fn parse<'a>(
- ast_items: impl Iterator<Item = Result<ast::Item<'a>, Error>>,
-) -> impl Iterator<Item = Result<Item<'a>, Error>> {
- ast_items.map(|ast_item| ast_item.and_then(Item::from_ast))
-}
+use super::lexer_ast::Modifier;
+use super::{Error, OptionExt as _, Span, Spanned, SpannedValue as _, unused};
+use crate::error::InvalidFormatDescription;
+use crate::format_description::__private::FormatDescriptionV3Inner;
+use crate::hint;
+use crate::internal_macros::{bug, try_likely_ok};
+
+macro_rules! parse_modifiers {
+ ($version:expr, $modifiers:expr, struct { $($field:ident : $modifier:ident),* $(,)? }) => {
+ 'block: {
+ struct Parsed {
+ $($field: Option<Spanned<<$modifier as ModifierValue>::Type>>),*
+ }
-/// A description of how to format and parse one part of a type.
-pub(super) enum Item<'a> {
- /// A literal string.
- Literal(&'a [u8]),
- /// Part of a type, along with its modifiers.
- Component(Component),
- /// A sequence of optional items.
- Optional {
- /// The items themselves.
- value: Box<[Self]>,
- /// The span of the full sequence.
- span: Span,
- },
- /// The first matching parse of a sequence of format descriptions.
- First {
- /// The sequence of format descriptions.
- value: Box<[Box<[Self]>]>,
- /// The span of the full sequence.
- span: Span,
- },
-}
+ let mut parsed = Parsed {
+ $($field: None),*
+ };
+
+ for modifier in $modifiers {
+ $(if ident_eq::<VERSION>(&modifier.key, stringify!($field)) {
+ hint::cold_path();
+ if version!(3..) && parsed.$field.is_some() {
+ break 'block Err(Error {
+ _inner: unused(modifier.key_span().error("duplicate modifier key")),
+ public: InvalidFormatDescription::DuplicateModifier {
+ name: stringify!($field),
+ index: modifier.key.location.byte as usize,
+ }
+ });
+ }
+ match <$modifier>::from_modifier_value::<VERSION>(
+ || modifier.value_span(),
+ modifier.value,
+ ) {
+ Ok(value) => {
+ parsed.$field = Some(
+ <<$modifier as ModifierValue>::Type>::from(value)
+ .spanned(modifier.value_span())
+ )
+ },
+ Err(err) => {
+ hint::cold_path();
+ break 'block Err(err)
+ },
+ }
+ continue;
+ })*
-impl Item<'_> {
- /// Parse an AST item into a format item.
- pub(super) fn from_ast(ast_item: ast::Item<'_>) -> Result<Item<'_>, Error> {
- Ok(match ast_item {
- ast::Item::Component {
- _opening_bracket: _,
- _leading_whitespace: _,
- name,
- modifiers,
- _trailing_whitespace: _,
- _closing_bracket: _,
- } => Item::Component(component_from_ast(&name, &modifiers)?),
- ast::Item::Literal(Spanned { value, span: _ }) => Item::Literal(value),
- ast::Item::EscapedBracket {
- _first: _,
- _second: _,
- } => Item::Literal(b"["),
- ast::Item::Optional {
- opening_bracket,
- _leading_whitespace: _,
- _optional_kw: _,
- _whitespace: _,
- nested_format_description,
- closing_bracket,
- } => {
- let items = nested_format_description
- .items
- .into_vec()
- .into_iter()
- .map(Item::from_ast)
- .collect::<Result<_, _>>()?;
- Item::Optional {
- value: items,
- span: opening_bracket.to(closing_bracket),
- }
- }
- ast::Item::First {
- opening_bracket,
- _leading_whitespace: _,
- _first_kw: _,
- _whitespace: _,
- nested_format_descriptions,
- closing_bracket,
- } => {
- let items = nested_format_descriptions
- .into_vec()
- .into_iter()
- .map(|nested_format_description| {
- nested_format_description
- .items
- .into_vec()
- .into_iter()
- .map(Item::from_ast)
- .collect()
- })
- .collect::<Result<_, _>>()?;
- Item::First {
- value: items,
- span: opening_bracket.to(closing_bracket),
- }
+ hint::cold_path();
+ break 'block Err(Error {
+ _inner: unused(modifier.key_span().error("invalid modifier key")),
+ public: InvalidFormatDescription::InvalidModifier {
+ value: (*modifier.key).to_owned(),
+ index: modifier.key.location.byte as usize,
+ }
+ });
}
- })
- }
-}
-impl<'a> TryFrom<Item<'a>> for crate::format_description::BorrowedFormatItem<'a> {
- type Error = Error;
-
- #[inline]
- fn try_from(item: Item<'a>) -> Result<Self, Self::Error> {
- match item {
- Item::Literal(literal) => Ok(Self::Literal(literal)),
- Item::Component(component) => Ok(Self::Component(component.into())),
- Item::Optional { value: _, span } => Err(Error {
- _inner: unused(span.error(
- "optional items are not supported in runtime-parsed format descriptions",
- )),
- public: crate::error::InvalidFormatDescription::NotSupported {
- what: "optional item",
- context: "runtime-parsed format descriptions",
- index: span.start.byte as usize,
- },
- }),
- Item::First { value: _, span } => Err(Error {
- _inner: unused(span.error(
- "'first' items are not supported in runtime-parsed format descriptions",
- )),
- public: crate::error::InvalidFormatDescription::NotSupported {
- what: "'first' item",
- context: "runtime-parsed format descriptions",
- index: span.start.byte as usize,
- },
- }),
+ Ok(parsed)
}
- }
+ };
}
-impl From<Item<'_>> for crate::format_description::OwnedFormatItem {
- #[inline]
- fn from(item: Item<'_>) -> Self {
- match item {
- Item::Literal(literal) => Self::Literal(literal.to_vec().into_boxed_slice()),
- Item::Component(component) => Self::Component(component.into()),
- Item::Optional { value, span: _ } => Self::Optional(Box::new(value.into())),
- Item::First { value, span: _ } => {
- Self::First(value.into_vec().into_iter().map(Into::into).collect())
- }
- }
+#[inline]
+pub(super) fn ident_eq<const VERSION: u8>(provided: &str, expected: &str) -> bool {
+ assert_version!();
+ if version!(3..) {
+ provided == expected
+ } else {
+ provided.len() == expected.len()
+ && core::iter::zip(provided.bytes(), expected.bytes())
+ .all(|(p, e)| p.to_ascii_lowercase() == e)
}
}
-impl<'a> From<Box<[Item<'a>]>> for crate::format_description::OwnedFormatItem {
- #[inline]
- fn from(items: Box<[Item<'a>]>) -> Self {
- let items = items.into_vec();
- match <[_; 1]>::try_from(items) {
- Ok([item]) => item.into(),
- Err(vec) => Self::Compound(vec.into_iter().map(Into::into).collect()),
- }
- }
+pub(super) fn parse_optional_format_modifier<const VERSION: u8>(
+ modifiers: &[Modifier<'_>],
+) -> Result<Spanned<bool>, Error> {
+ let modifiers = parse_modifiers!(VERSION, modifiers, struct {
+ format: OptionalFormat,
+ })?;
+
+ Ok(modifiers.format.transpose().map(|val| val.unwrap_or(true)))
}
/// Declare the `Component` struct.
@@ -166,63 +95,87 @@ macro_rules! component_definition {
(@if_required then { $($then:tt)* } $(else { $($else:tt)* })?) => { $($($else)*)? };
(@if_from_str from_str then { $($then:tt)* } $(else { $($else:tt)* })?) => { $($then)* };
(@if_from_str then { $($then:tt)* } $(else { $($else:tt)* })?) => { $($($else)*)? };
+ (@if_year "year" $($then:tt)*) => { $($then)* };
+ (@if_year $lit:tt $($then:tt)*) => {};
- ($vis:vis enum $name:ident {
- $($variant:ident = $parse_variant:literal {$(
+ ($vis:vis enum $name:ident {$(
+ $variant:ident = $parse_variant:tt {$(
$(#[$required:tt])?
$field:ident = $parse_field:literal:
Option<$(#[$from_str:tt])? $field_type:ty>
- => $target_field:ident
- ),* $(,)?}),* $(,)?
- }) => {
+ ),* $(,)?}
+ ),* $(,)?}) => {
$vis enum $name {
$($variant($variant),)*
}
$($vis struct $variant {
- $($field: Option<$field_type>),*
+ $($field: Spanned<Option<$field_type>>),*
})*
$(impl $variant {
/// Parse the component from the AST, given its modifiers.
#[inline]
- fn with_modifiers(
- modifiers: &[ast::Modifier<'_>],
+ fn with_modifiers<const VERSION: u8>(
+ modifiers: &[Modifier<'_>],
_component_span: Span,
) -> Result<Self, Error>
{
+ assert_version!();
+
// rustc will complain if the modifier is empty.
#[allow(unused_mut)]
let mut this = Self {
- $($field: None),*
+ $($field: None.spanned(Span::DUMMY)),*
};
for modifier in modifiers {
- $(#[expect(clippy::string_lit_as_bytes)]
- if modifier.key.eq_ignore_ascii_case($parse_field.as_bytes()) {
- this.$field = component_definition!(@if_from_str $($from_str)?
- then {
- parse_from_modifier_value::<$field_type>(&modifier.value)?
- } else {
- <$field_type>::from_modifier_value(&modifier.value)?
+ $(if ident_eq::<VERSION>(&modifier.key, $parse_field) {
+ if version!(3..) && this.$field.is_some() {
+ hint::cold_path();
+ return Err(Error {
+ _inner: unused(modifier.key_span().error("duplicate modifier key")),
+ public: InvalidFormatDescription::DuplicateModifier {
+ name: stringify!($field),
+ index: modifier.key.location.byte as usize,
+ }
});
+ }
+ this.$field = Some(
+ component_definition!(@if_from_str $($from_str)?
+ then {
+ parse_from_modifier_value::<$field_type>(
+ || modifier.value_span(),
+ modifier.value,
+ )?
+ } else {
+ <$field_type>::from_modifier_value::<VERSION>(
+ || modifier.value_span(),
+ modifier.value,
+ )?
+ }
+ )
+ ).spanned(modifier.key_value_span());
continue;
})*
+
+ hint::cold_path();
return Err(Error {
- _inner: unused(modifier.key.span.error("invalid modifier key")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::from_utf8_lossy(*modifier.key).into_owned(),
- index: modifier.key.span.start.byte as usize,
+ _inner: unused(modifier.key_span().error("invalid modifier key")),
+ public: InvalidFormatDescription::InvalidModifier {
+ value: (*modifier.key).to_owned(),
+ index: modifier.key.location.byte as usize,
}
});
}
$(component_definition! { @if_required $($required)? then {
if this.$field.is_none() {
+ hint::cold_path();
return Err(Error {
_inner: unused(_component_span.error("missing required modifier")),
public:
- crate::error::InvalidFormatDescription::MissingRequiredModifier {
+ InvalidFormatDescription::MissingRequiredModifier {
name: $parse_field,
index: _component_span.start.byte as usize,
}
@@ -234,44 +187,36 @@ macro_rules! component_definition {
}
})*
- impl From<$name> for crate::format_description::Component {
- #[inline]
- fn from(component: $name) -> Self {
- match component {$(
- $name::$variant($variant { $($field),* }) => {
- $crate::format_description::component::Component::$variant(
- $crate::format_description::modifier::$variant {$(
- $target_field: component_definition! { @if_required $($required)?
- then {
- match $field {
- Some(value) => value.into(),
- None => bug!("required modifier was not set"),
- }
- } else {
- $field.unwrap_or_default().into()
- }
- }
- ),*}
- )
- }
- )*}
- }
- }
-
/// Parse a component from the AST, given its name and modifiers.
#[inline]
- fn component_from_ast(
- name: &Spanned<&[u8]>,
- modifiers: &[ast::Modifier<'_>],
- ) -> Result<Component, Error> {
- $(#[expect(clippy::string_lit_as_bytes)]
- if name.eq_ignore_ascii_case($parse_variant.as_bytes()) {
- return Ok(Component::$variant($variant::with_modifiers(&modifiers, name.span)?));
+ pub(super) fn component_from_ast<const VERSION: u8>(
+ name: &Spanned<&str>,
+ modifiers: &[Modifier<'_>],
+ ) -> Result<AstComponent, Error> {
+ assert_version!();
+
+ $(if ident_eq::<VERSION>(&name, $parse_variant) {
+ #[allow(unused_mut)] // only used for some variants
+ let mut component = AstComponent::$variant(
+ try_likely_ok!($variant::with_modifiers::<VERSION>(&modifiers, name.span))
+ );
+ component_definition!(@if_year $parse_variant
+ #[cfg(feature = "large-dates")]
+ if version!(3..)
+ && let AstComponent::Year(y) = &mut component
+ && y.range.value.is_none()
+ {
+ y.range = Some(YearRange::Standard).spanned(Span::DUMMY);
+ }
+ );
+ return Ok(component);
})*
+
+ hint::cold_path();
Err(Error {
_inner: unused(name.span.error("invalid component")),
- public: crate::error::InvalidFormatDescription::InvalidComponentName {
- name: String::from_utf8_lossy(name).into_owned(),
+ public: InvalidFormatDescription::InvalidComponentName {
+ name: (**name).to_owned(),
index: name.span.start.byte as usize,
},
})
@@ -281,73 +226,393 @@ macro_rules! component_definition {
// Keep in alphabetical order.
component_definition! {
- pub(super) enum Component {
+ pub(super) enum AstComponent {
Day = "day" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
+ },
+ End = "end" {
+ trailing_input = "trailing_input": Option<TrailingInput>,
},
- End = "end" {},
Hour = "hour" {
- padding = "padding": Option<Padding> => padding,
- base = "repr": Option<HourBase> => is_12_hour_clock,
+ padding = "padding": Option<Padding>,
+ base = "repr": Option<HourBase>,
},
Ignore = "ignore" {
#[required]
- count = "count": Option<#[from_str] NonZero<u16>> => count,
+ count = "count": Option<#[from_str] NonZero<u16>>,
},
Minute = "minute" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
},
Month = "month" {
- padding = "padding": Option<Padding> => padding,
- repr = "repr": Option<MonthRepr> => repr,
- case_sensitive = "case_sensitive": Option<MonthCaseSensitive> => case_sensitive,
+ padding = "padding": Option<Padding>,
+ repr = "repr": Option<MonthRepr>,
+ case_sensitive = "case_sensitive": Option<MonthCaseSensitive>,
},
OffsetHour = "offset_hour" {
- sign_behavior = "sign": Option<SignBehavior> => sign_is_mandatory,
- padding = "padding": Option<Padding> => padding,
+ sign_behavior = "sign": Option<SignBehavior>,
+ padding = "padding": Option<Padding>,
},
OffsetMinute = "offset_minute" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
},
OffsetSecond = "offset_second" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
},
Ordinal = "ordinal" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
},
Period = "period" {
- case = "case": Option<PeriodCase> => is_uppercase,
- case_sensitive = "case_sensitive": Option<PeriodCaseSensitive> => case_sensitive,
+ case = "case": Option<PeriodCase>,
+ case_sensitive = "case_sensitive": Option<PeriodCaseSensitive>,
},
Second = "second" {
- padding = "padding": Option<Padding> => padding,
+ padding = "padding": Option<Padding>,
},
Subsecond = "subsecond" {
- digits = "digits": Option<SubsecondDigits> => digits,
+ digits = "digits": Option<SubsecondDigits>,
},
UnixTimestamp = "unix_timestamp" {
- precision = "precision": Option<UnixTimestampPrecision> => precision,
- sign_behavior = "sign": Option<SignBehavior> => sign_is_mandatory,
+ precision = "precision": Option<UnixTimestampPrecision>,
+ sign_behavior = "sign": Option<SignBehavior>,
},
Weekday = "weekday" {
- repr = "repr": Option<WeekdayRepr> => repr,
- one_indexed = "one_indexed": Option<WeekdayOneIndexed> => one_indexed,
- case_sensitive = "case_sensitive": Option<WeekdayCaseSensitive> => case_sensitive,
+ repr = "repr": Option<WeekdayRepr>,
+ one_indexed = "one_indexed": Option<WeekdayOneIndexed>,
+ case_sensitive = "case_sensitive": Option<WeekdayCaseSensitive>,
},
WeekNumber = "week_number" {
- padding = "padding": Option<Padding> => padding,
- repr = "repr": Option<WeekNumberRepr> => repr,
+ padding = "padding": Option<Padding>,
+ repr = "repr": Option<WeekNumberRepr>,
},
Year = "year" {
- padding = "padding": Option<Padding> => padding,
- repr = "repr": Option<YearRepr> => repr,
- range = "range": Option<YearRange> => range,
- base = "base": Option<YearBase> => iso_week_based,
- sign_behavior = "sign": Option<SignBehavior> => sign_is_mandatory,
+ padding = "padding": Option<Padding>,
+ repr = "repr": Option<YearRepr>,
+ range = "range": Option<YearRange>,
+ base = "base": Option<YearBase>,
+ sign_behavior = "sign": Option<SignBehavior>,
},
}
}
+macro_rules! impl_from_ast_component_for {
+ ($([$reject_nonsensical:literal] $ty:ty),+ $(,)?) => {$(
+ impl TryFrom<AstComponent> for $ty {
+ type Error = Error;
+
+ #[inline]
+ fn try_from(component: AstComponent) -> Result<Self, Self::Error> {
+ macro_rules! reject_modifier {
+ ($modifier:ident, $modifier_str:literal, $context:literal) => {
+ if $reject_nonsensical && $modifier.value.is_some() {
+ hint::cold_path();
+ return Err(Error {
+ _inner: unused($modifier.span.error(concat!(
+ "the '",
+ $modifier_str,
+ "' modifier is not valid ",
+ $context
+ ))),
+ public: InvalidFormatDescription::InvalidModifierCombination {
+ modifier: $modifier_str,
+ context: $context,
+ index: $modifier.span.start.byte as usize,
+ },
+ });
+ }
+ };
+ }
+
+ use crate::format_description::modifier;
+ Ok(match component {
+ AstComponent::Day(Day { padding }) => Self::Day(modifier::Day {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ AstComponent::End(End { trailing_input }) => Self::End(modifier::End {
+ trailing_input: trailing_input.unwrap_or_default().into(),
+ }),
+ AstComponent::Hour(Hour { padding, base }) => match base.unwrap_or_default() {
+ HourBase::Twelve => Self::Hour12(modifier::Hour12 {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ HourBase::TwentyFour => Self::Hour24(modifier::Hour24 {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ },
+ AstComponent::Ignore(Ignore { count }) => Self::Ignore(modifier::Ignore {
+ count: match *count {
+ Some(value) => value,
+ None => bug!("required modifier was not set"),
+ },
+ }),
+ AstComponent::Minute(Minute { padding }) => Self::Minute(modifier::Minute {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ AstComponent::Month(Month {
+ padding,
+ repr,
+ case_sensitive,
+ }) => match repr.unwrap_or_default() {
+ MonthRepr::Numerical => {
+ reject_modifier!(
+ case_sensitive,
+ "case_sensitive",
+ "for numerical month"
+ );
+ Self::MonthNumerical(modifier::MonthNumerical {
+ padding: padding.unwrap_or_default().into(),
+ })
+ },
+ MonthRepr::Long => {
+ reject_modifier!(padding, "padding", "for long month");
+ Self::MonthLong(modifier::MonthLong {
+ case_sensitive: case_sensitive.unwrap_or_default().into(),
+ })
+ },
+ MonthRepr::Short => {
+ reject_modifier!(padding, "padding", "for short month");
+ Self::MonthShort(modifier::MonthShort {
+ case_sensitive: case_sensitive.unwrap_or_default().into(),
+ })
+ },
+ },
+ AstComponent::OffsetHour(OffsetHour {
+ sign_behavior,
+ padding,
+ }) => Self::OffsetHour(modifier::OffsetHour {
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ padding: padding.unwrap_or_default().into(),
+ }),
+ AstComponent::OffsetMinute(OffsetMinute { padding }) => {
+ Self::OffsetMinute(modifier::OffsetMinute {
+ padding: padding.unwrap_or_default().into(),
+ })
+ }
+ AstComponent::OffsetSecond(OffsetSecond { padding }) => {
+ Self::OffsetSecond(modifier::OffsetSecond {
+ padding: padding.unwrap_or_default().into(),
+ })
+ }
+ AstComponent::Ordinal(Ordinal { padding }) => Self::Ordinal(modifier::Ordinal {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ AstComponent::Period(Period {
+ case,
+ case_sensitive,
+ }) => Self::Period(modifier::Period {
+ is_uppercase: case.unwrap_or_default().into(),
+ case_sensitive: case_sensitive.unwrap_or_default().into(),
+ }),
+ AstComponent::Second(Second { padding }) => Self::Second(modifier::Second {
+ padding: padding.unwrap_or_default().into(),
+ }),
+ AstComponent::Subsecond(Subsecond { digits }) => {
+ Self::Subsecond(modifier::Subsecond {
+ digits: digits.unwrap_or_default().into(),
+ })
+ },
+ AstComponent::UnixTimestamp(UnixTimestamp {
+ precision,
+ sign_behavior,
+ }) => match precision.unwrap_or_default() {
+ UnixTimestampPrecision::Second => {
+ Self::UnixTimestampSecond(modifier::UnixTimestampSecond {
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ UnixTimestampPrecision::Millisecond => {
+ Self::UnixTimestampMillisecond(modifier::UnixTimestampMillisecond {
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ UnixTimestampPrecision::Microsecond => {
+ Self::UnixTimestampMicrosecond(modifier::UnixTimestampMicrosecond {
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ UnixTimestampPrecision::Nanosecond => {
+ Self::UnixTimestampNanosecond(modifier::UnixTimestampNanosecond {
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ },
+ AstComponent::Weekday(Weekday {
+ repr,
+ one_indexed,
+ case_sensitive,
+ }) => match repr.unwrap_or_default() {
+ WeekdayRepr::Short => {
+ reject_modifier!(one_indexed, "one_indexed", "for short weekday");
+ Self::WeekdayShort(modifier::WeekdayShort {
+ case_sensitive: case_sensitive.unwrap_or_default().into(),
+ })
+ },
+ WeekdayRepr::Long => {
+ reject_modifier!(one_indexed, "one_indexed", "for long weekday");
+ Self::WeekdayLong(modifier::WeekdayLong {
+ case_sensitive: case_sensitive.unwrap_or_default().into(),
+ })
+ },
+ WeekdayRepr::Sunday => {
+ reject_modifier!(
+ case_sensitive,
+ "case_sensitive",
+ "for numerical weekday"
+ );
+ Self::WeekdaySunday(modifier::WeekdaySunday {
+ one_indexed: one_indexed.unwrap_or_default().into(),
+ })
+ },
+ WeekdayRepr::Monday => {
+ reject_modifier!(
+ case_sensitive,
+ "case_sensitive",
+ "for numerical weekday"
+ );
+ Self::WeekdayMonday(modifier::WeekdayMonday {
+ one_indexed: one_indexed.unwrap_or_default().into(),
+ })
+ },
+ },
+ AstComponent::WeekNumber(WeekNumber { padding, repr }) => {
+ match repr.unwrap_or_default() {
+ WeekNumberRepr::Iso => {
+ Self::WeekNumberIso(modifier::WeekNumberIso {
+ padding: padding.unwrap_or_default().into(),
+ })
+ },
+ WeekNumberRepr::Sunday => {
+ Self::WeekNumberSunday(modifier::WeekNumberSunday {
+ padding: padding.unwrap_or_default().into(),
+ })
+ },
+ WeekNumberRepr::Monday => {
+ Self::WeekNumberMonday(modifier::WeekNumberMonday {
+ padding: padding.unwrap_or_default().into(),
+ })
+ },
+ }
+ }
+ AstComponent::Year(Year {
+ padding,
+ repr,
+ range,
+ base,
+ sign_behavior,
+ }) => {
+ #[cfg(not(feature = "large-dates"))]
+ reject_modifier!(
+ range,
+ "range",
+ "when the `large-dates` feature is not enabled"
+ );
+
+ match (
+ base.unwrap_or_default(),
+ repr.unwrap_or_default(),
+ range.unwrap_or_default(),
+ ) {
+ #[cfg(feature = "large-dates")]
+ (YearBase::Calendar, YearRepr::Full, YearRange::Extended) => {
+ Self::CalendarYearFullExtendedRange(
+ modifier::CalendarYearFullExtendedRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ (YearBase::Calendar, YearRepr::Full, _) => {
+ Self::CalendarYearFullStandardRange(
+ modifier::CalendarYearFullStandardRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ #[cfg(feature = "large-dates")]
+ (YearBase::Calendar, YearRepr::Century, YearRange::Extended) => {
+ Self::CalendarYearCenturyExtendedRange(
+ modifier::CalendarYearCenturyExtendedRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ (YearBase::Calendar, YearRepr::Century, _) => {
+ Self::CalendarYearCenturyStandardRange(
+ modifier::CalendarYearCenturyStandardRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ #[cfg(feature = "large-dates")]
+ (YearBase::IsoWeek, YearRepr::Full, YearRange::Extended) => {
+ Self::IsoYearFullExtendedRange(modifier::IsoYearFullExtendedRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ (YearBase::IsoWeek, YearRepr::Full, _) => {
+ Self::IsoYearFullStandardRange(modifier::IsoYearFullStandardRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ })
+ }
+ #[cfg(feature = "large-dates")]
+ (YearBase::IsoWeek, YearRepr::Century, YearRange::Extended) => {
+ Self::IsoYearCenturyExtendedRange(
+ modifier::IsoYearCenturyExtendedRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ (YearBase::IsoWeek, YearRepr::Century, _) => {
+ Self::IsoYearCenturyStandardRange(
+ modifier::IsoYearCenturyStandardRange {
+ padding: padding.unwrap_or_default().into(),
+ sign_is_mandatory: sign_behavior.unwrap_or_default().into(),
+ },
+ )
+ }
+ (YearBase::Calendar, YearRepr::LastTwo, _) => {
+ #[cfg(feature = "large-dates")]
+ reject_modifier!(range, "range", "when `repr:last_two` is used");
+ reject_modifier!(
+ sign_behavior,
+ "sign",
+ "when `repr:last_two` is used"
+ );
+ Self::CalendarYearLastTwo(modifier::CalendarYearLastTwo {
+ padding: padding.unwrap_or_default().into(),
+ })
+ }
+ (YearBase::IsoWeek, YearRepr::LastTwo, _) => {
+ #[cfg(feature = "large-dates")]
+ reject_modifier!(range, "range", "when `repr:last_two` is used");
+ reject_modifier!(
+ sign_behavior,
+ "sign",
+ "when `repr:last_two` is used"
+ );
+ Self::IsoYearLastTwo(modifier::IsoYearLastTwo {
+ padding: padding.unwrap_or_default().into(),
+ })
+ }
+ }
+ }
+ })
+ }
+ })+
+ }
+}
+
+impl_from_ast_component_for!(
+ [false] crate::format_description::Component,
+ [true] FormatDescriptionV3Inner<'_>,
+);
+
/// Get the target type for a given enum.
macro_rules! target_ty {
($name:ident $type:ty) => {
@@ -368,6 +633,10 @@ macro_rules! target_value {
};
}
+trait ModifierValue {
+ type Type;
+}
+
/// Declare the various modifiers.
///
/// For the general case, ordinary syntax can be used. Note that you _must_ declare a default
@@ -387,35 +656,51 @@ macro_rules! target_value {
/// but is represented as `true` in the public API.
macro_rules! modifier {
($(
+ $(#[expect($expect_inner:meta)])?
enum $name:ident $(($target_ty:ty))? {
$(
$(#[$attr:meta])?
$variant:ident $(($target_value:expr))? = $parse_variant:literal
),* $(,)?
}
)+) => {$(
- #[derive(Default)]
+ #[derive(Default, Clone, Copy)]
enum $name {
$($(#[$attr])? $variant),*
}
impl $name {
/// Parse the modifier from its string representation.
#[inline]
- fn from_modifier_value(value: &Spanned<&[u8]>) -> Result<Option<Self>, Error> {
- $(if value.eq_ignore_ascii_case($parse_variant) {
- return Ok(Some(Self::$variant));
+ fn from_modifier_value<const VERSION: u8>(
+ value_span: impl FnOnce() -> Span,
+ value: &str,
+ ) -> Result<Self, Error>
+ {
+ assert_version!();
+
+ $(if ident_eq::<VERSION>(&value, $parse_variant) {
+ return Ok(Self::$variant);
})*
+
+ hint::cold_path();
+ let span = value_span();
Err(Error {
- _inner: unused(value.span.error("invalid modifier value")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::from_utf8_lossy(value).into_owned(),
- index: value.span.start.byte as usize,
+ _inner: unused(span.error("invalid modifier value")),
+ public: InvalidFormatDescription::InvalidModifier {
+ value: value.to_owned(),
+ index: span.start.byte as usize,
},
})
}
}
+ $(#[expect($expect_inner)])?
+ impl ModifierValue for $name {
+ type Type = target_ty!($name $($target_ty)?);
+ }
+
+ $(#[expect($expect_inner)])?
impl From<$name> for target_ty!($name $($target_ty)?) {
#[inline]
fn from(modifier: $name) -> Self {
@@ -430,130 +715,154 @@ macro_rules! modifier {
// Keep in alphabetical order.
modifier! {
enum HourBase(bool) {
- Twelve(true) = b"12",
+ Twelve(true) = "12",
#[default]
- TwentyFour(false) = b"24",
+ TwentyFour(false) = "24",
}
enum MonthCaseSensitive(bool) {
- False(false) = b"false",
+ False(false) = "false",
#[default]
- True(true) = b"true",
+ True(true) = "true",
}
+ #[expect(deprecated)]
enum MonthRepr {
#[default]
- Numerical = b"numerical",
- Long = b"long",
- Short = b"short",
+ Numerical = "numerical",
+ Long = "long",
+ Short = "short",
+ }
+
+ enum OptionalFormat(bool) {
+ False(false) = "false",
+ #[default]
+ True(true) = "true",
}
enum Padding {
- Space = b"space",
+ Space = "space",
#[default]
- Zero = b"zero",
- None = b"none",
+ Zero = "zero",
+ None = "none",
}
enum PeriodCase(bool) {
- Lower(false) = b"lower",
+ Lower(false) = "lower",
#[default]
- Upper(true) = b"upper",
+ Upper(true) = "upper",
}
enum PeriodCaseSensitive(bool) {
- False(false) = b"false",
+ False(false) = "false",
#[default]
- True(true) = b"true",
+ True(true) = "true",
}
enum SignBehavior(bool) {
#[default]
- Automatic(false) = b"automatic",
- Mandatory(true) = b"mandatory",
+ Automatic(false) = "automatic",
+ Mandatory(true) = "mandatory",
}
enum SubsecondDigits {
- One = b"1",
- Two = b"2",
- Three = b"3",
- Four = b"4",
- Five = b"5",
- Six = b"6",
- Seven = b"7",
- Eight = b"8",
- Nine = b"9",
+ One = "1",
+ Two = "2",
+ Three = "3",
+ Four = "4",
+ Five = "5",
+ Six = "6",
+ Seven = "7",
+ Eight = "8",
+ Nine = "9",
#[default]
- OneOrMore = b"1+",
+ OneOrMore = "1+",
}
+ enum TrailingInput {
+ #[default]
+ Prohibit = "prohibit",
+ Discard = "discard",
+ }
+
+ #[expect(deprecated)]
enum UnixTimestampPrecision {
#[default]
- Second = b"second",
- Millisecond = b"millisecond",
- Microsecond = b"microsecond",
- Nanosecond = b"nanosecond",
+ Second = "second",
+ Millisecond = "millisecond",
+ Microsecond = "microsecond",
+ Nanosecond = "nanosecond",
}
+ #[expect(deprecated)]
enum WeekNumberRepr {
#[default]
- Iso = b"iso",
- Sunday = b"sunday",
- Monday = b"monday",
+ Iso = "iso",
+ Sunday = "sunday",
+ Monday = "monday",
}
enum WeekdayCaseSensitive(bool) {
- False(false) = b"false",
+ False(false) = "false",
#[default]
- True(true) = b"true",
+ True(true) = "true",
}
enum WeekdayOneIndexed(bool) {
- False(false) = b"false",
+ False(false) = "false",
#[default]
- True(true) = b"true",
+ True(true) = "true",
}
+ #[expect(deprecated)]
enum WeekdayRepr {
- Short = b"short",
+ Short = "short",
#[default]
- Long = b"long",
- Sunday = b"sunday",
- Monday = b"monday",
+ Long = "long",
+ Sunday = "sunday",
+ Monday = "monday",
}
enum YearBase(bool) {
#[default]
- Calendar(false) = b"calendar",
- IsoWeek(true) = b"iso_week",
+ Calendar(false) = "calendar",
+ IsoWeek(true) = "iso_week",
}
+ #[expect(deprecated)]
enum YearRepr {
#[default]
- Full = b"full",
- Century = b"century",
- LastTwo = b"last_two",
+ Full = "full",
+ Century = "century",
+ LastTwo = "last_two",
}
+ // For v1 and v2 format descriptions, the default is `extended`. For v3 format descriptions,
+ // the default is `standard`. For backwards compatibility, the default here needs to stay
+ // `extended`.
+ #[expect(deprecated)]
enum YearRange {
- Standard = b"standard",
+ Standard = "standard",
#[default]
- Extended = b"extended",
+ Extended = "extended",
}
}
/// Parse a modifier value using `FromStr`. Requires the modifier value to be valid UTF-8.
#[inline]
-fn parse_from_modifier_value<T: FromStr>(value: &Spanned<&[u8]>) -> Result<Option<T>, Error> {
- str::from_utf8(value)
- .ok()
- .and_then(|val| val.parse::<T>().ok())
- .map(|val| Some(val))
- .ok_or_else(|| Error {
- _inner: unused(value.span.error("invalid modifier value")),
- public: crate::error::InvalidFormatDescription::InvalidModifier {
- value: String::from_utf8_lossy(value).into_owned(),
- index: value.span.start.byte as usize,
+fn parse_from_modifier_value<T>(value_span: impl FnOnce() -> Span, value: &str) -> Result<T, Error>
+where
+ T: FromStr,
+{
+ value.parse::<T>().map_err(|_| {
+ hint::cold_path();
+ let span = value_span();
+ Error {
+ _inner: unused(span.error("invalid modifier value")),
+ public: InvalidFormatDescription::InvalidModifier {
+ value: value.to_owned(),
+ index: span.start.byte as usize,
},
- })
+ }
+ })
}
### external/vendor/time/src/format_description/parse/lexer.rs
@@ -1,291 +0,0 @@
-//! Lexer for parsing format descriptions.
-
-use core::iter;
-
-use super::{attach_location, unused, Error, Location, Spanned, SpannedValue};
-
-/// An iterator over the lexed tokens.
-pub(super) struct Lexed<I: Iterator> {
- /// The internal iterator.
- iter: iter::Peekable<I>,
-}
-
-impl<I: Iterator> Iterator for Lexed<I> {
- type Item = I::Item;
-
- fn next(&mut self) -> Option<Self::Item> {
- self.iter.next()
- }
-}
-
-impl<'iter, 'token: 'iter, I: Iterator<Item = Result<Token<'token>, Error>> + 'iter> Lexed<I> {
- /// Peek at the next item in the iterator.
- #[inline]
- pub(super) fn peek(&mut self) -> Option<&I::Item> {
- self.iter.peek()
- }
-
- /// Consume the next token if it is whitespace.
- #[inline]
- pub(super) fn next_if_whitespace(&mut self) -> Option<Spanned<&'token [u8]>> {
- if let Some(&Ok(Token::ComponentPart {
- kind: ComponentKind::Whitespace,
- value,
- })) = self.peek()
- {
- self.next(); // consume
- Some(value)
- } else {
- None
- }
- }
-
- /// Consume the next token if it is a component item that is not whitespace.
- #[inline]
- pub(super) fn next_if_not_whitespace(&mut self) -> Option<Spanned<&'token [u8]>> {
- if let Some(&Ok(Token::ComponentPart {
- kind: ComponentKind::NotWhitespace,
- value,
- })) = self.peek()
- {
- self.next(); // consume
- Some(value)
- } else {
- None
- }
- }
-
- /// Consume the next token if it is an opening bracket.
- #[inline]
- pub(super) fn next_if_opening_bracket(&mut self) -> Option<Location> {
- if let Some(&Ok(Token::Bracket {
- kind: BracketKind::Opening,
- location,
- })) = self.peek()
- {
- self.next(); // consume
- Some(location)
- } else {
- None
- }
- }
-
- /// Peek at the next token if it is a closing bracket.
- #[inline]
- pub(super) fn peek_closing_bracket(&'iter mut self) -> Option<&'iter Location> {
- if let Some(Ok(Token::Bracket {
- kind: BracketKind::Closing,
- location,
- })) = self.peek()
- {
- Some(location)
- } else {
- None
- }
- }
-
- /// Consume the next token if it is a closing bracket.
- #[inline]
- pub(super) fn next_if_closing_bracket(&mut self) -> Option<Location> {
- if let Some(&Ok(Token::Bracket {
- kind: BracketKind::Closing,
- location,
- })) = self.peek()
- {
- self.next(); // consume
- Some(location)
- } else {
- None
- }
- }
-}
-
-/// A token emitted by the lexer. There is no semantic meaning at this stage.
-pub(super) enum Token<'a> {
- /// A literal string, formatted and parsed as-is.
- Literal(Spanned<&'a [u8]>),
- /// An opening or closing bracket. May or may not be the start or end of a component.
- Bracket {
- /// Whether the bracket is opening or closing.
- kind: BracketKind,
- /// Where the bracket was in the format string.
- location: Location,
- },
- /// One part of a component. This could be its name, a modifier, or whitespace.
- ComponentPart {
- /// Whether the part is whitespace or not.
- kind: ComponentKind,
- /// The part itself.
- value: Spanned<&'a [u8]>,
- },
-}
-
-/// What type of bracket is present.
-pub(super) enum BracketKind {
- /// An opening bracket: `[`
- Opening,
- /// A closing bracket: `]`
- Closing,
-}
-
-/// Indicates whether the component is whitespace or not.
-pub(super) enum ComponentKind {
- Whitespace,
- NotWhitespace,
-}
-
-/// Parse the string into a series of [`Token`]s.
-///
-/// `VERSION` controls the version of the format description that is being parsed. Currently, this
-/// must be 1 or 2.
-///
-/// - When `VERSION` is 1, `[[` is the only escape sequence, resulting in a literal `[`.
-/// - When `VERSION` is 2, all escape sequences begin with `\`. The only characters that may
-/// currently follow are `\`, `[`, and `]`, all of which result in the literal character. All
-/// other characters result in a lex error.
-#[inline]
-pub(super) fn lex<const VERSION: usize>(
- mut input: &[u8],
-) -> Lexed<impl Iterator<Item = Result<Token<'_>, Error>>> {
- validate_version!(VERSION);
-
- let mut depth: u8 = 0;
- let mut iter = attach_location(input.iter()).peekable();
- let mut second_bracket_location = None;
-
- let iter = iter::from_fn(move || {
- // The flag is only set when version is zero.
- if version!(..=1) {
- // There is a flag set to emit the second half of an escaped bracket pair.
- if let Some(location) = second_bracket_location.take() {
- return Some(Ok(Token::Bracket {
- kind: BracketKind::Opening,
- location,
- }));
- }
- }
-
- Some(Ok(match iter.next()? {
- // possible escape sequence
- (b'\\', backslash_loc) if version!(2..) => {
- match iter.next() {
- Some((b'\\' | b'[' | b']', char_loc)) => {
- // The escaped character is emitted as-is.
- let char = &input[1..2];
- input = &input[2..];
- if depth == 0 {
- Token::Literal(char.spanned(backslash_loc.to(char_loc)))
- } else {
- Token::ComponentPart {
- kind: ComponentKind::NotWhitespace,
- value: char.spanned(backslash_loc.to(char_loc)),
- }
- }
- }
- Some((_, loc)) => {
- return Some(Err(Error {
- _inner: unused(loc.error("invalid escape sequence")),
- public: crate::error::InvalidFormatDescription::Expected {
- what: "valid escape sequence",
- index: loc.byte as usize,
- },
- }));
- }
- None => {
- return Some(Err(Error {
- _inner: unused(backslash_loc.error("unexpected end of input")),
- public: crate::error::InvalidFormatDescription::Expected {
- what: "valid escape sequence",
- index: backslash_loc.byte as usize,
- },
- }));
- }
- }
- }
- // potentially escaped opening bracket
- (b'[', location) if version!(..=1) => {
- if let Some((_, second_location)) = iter.next_if(|&(&byte, _)| byte == b'[') {
- // Escaped bracket. Store the location of the second so we can emit it later.
- second_bracket_location = Some(second_location);
- input = &input[2..];
- } else {
- // opening bracket
- depth += 1;
- input = &input[1..];
- }
-
- Token::Bracket {
- kind: BracketKind::Opening,
- location,
- }
- }
- // opening bracket
- (b'[', location) => {
- depth += 1;
- input = &input[1..];
-
- Token::Bracket {
- kind: BracketKind::Opening,
- location,
- }
- }
- // closing bracket
- (b']', location) if depth > 0 => {
- depth -= 1;
- input = &input[1..];
-
- Token::Bracket {
- kind: BracketKind::Closing,
- location,
- }
- }
- // literal
- (_, start_location) if depth == 0 => {
- let mut bytes = 1;
- let mut end_location = start_location;
-
- while let Some((_, location)) =
- iter.next_if(|&(&byte, _)| !((version!(2..) && byte == b'\\') || byte == b'['))
- {
- end_location = location;
- bytes += 1;
- }
-
- let value = &input[..bytes];
- input = &input[bytes..];
-
- Token::Literal(value.spanned(start_location.to(end_location)))
- }
- // component part
- (byte, start_location) => {
- let mut bytes = 1;
- let mut end_location = start_location;
- let is_whitespace = byte.is_ascii_whitespace();
-
- while let Some((_, location)) = iter.next_if(|&(byte, _)| {
- !matches!(byte, b'\\' | b'[' | b']')
- && is_whitespace == byte.is_ascii_whitespace()
- }) {
- end_location = location;
- bytes += 1;
- }
-
- let value = &input[..bytes];
- input = &input[bytes..];
-
- Token::ComponentPart {
- kind: if is_whitespace {
- ComponentKind::Whitespace
- } else {
- ComponentKind::NotWhitespace
- },
- value: value.spanned(start_location.to(end_location)),
- }
- }
- }))
- });
-
- Lexed {
- iter: iter.peekable(),
- }
-}
### external/vendor/time/src/format_description/parse/lexer_ast.rs
[binary or diff unavailable]
### external/vendor/time/src/format_description/parse/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/format_description/parse/strftime.rs
[binary or diff unavailable]
### external/vendor/time/src/format_description/well_known/iso8601/adt_hack.rs
[binary or diff unavailable]
### external/vendor/time/src/formatting/component_provider.rs
[binary or diff unavailable]
### external/vendor/time/src/formatting/formattable.rs
[binary or diff unavailable]
### external/vendor/time/src/formatting/iso8601.rs
[binary or diff unavailable]
### external/vendor/time/src/formatting/metadata.rs
[binary or diff unavailable]
### external/vendor/time/src/formatting/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/instant.rs
[binary or diff unavailable]
### external/vendor/time/src/internal_macros.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/js_sys_date_offsetdatetime.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/js_sys_date_timestamp.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/js_sys_date_utcdatetime.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/offsetdatetime_systemtime.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/offsetdatetime_timestamp.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/offsetdatetime_utcdatetime.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/systemdatetime_timestamp.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/timestamp_utcdatetime.rs
[binary or diff unavailable]
### external/vendor/time/src/interop/utcdatetime_systemtime.rs
[binary or diff unavailable]
### external/vendor/time/src/iter/date_iter.rs
[binary or diff unavailable]
### external/vendor/time/src/iter/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/iter/month_iter.rs
[binary or diff unavailable]
### external/vendor/time/src/iter/weekday_iter.rs
[binary or diff unavailable]
### external/vendor/time/src/lib.rs
[binary or diff unavailable]
### external/vendor/time/src/macros.rs
[binary or diff unavailable]
### external/vendor/time/src/month.rs
[binary or diff unavailable]
### external/vendor/time/src/num_fmt.rs
[binary or diff unavailable]
### external/vendor/time/src/offset_date_time.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/combinator/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/combinator/rfc/iso8601.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/combinator/rfc/rfc2822.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/component.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/iso8601.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/parsable.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/parsed.rs
[binary or diff unavailable]
### external/vendor/time/src/parsing/shim.rs
[binary or diff unavailable]
### external/vendor/time/src/plain_date_time.rs
[binary or diff unavailable]
### external/vendor/time/src/quickcheck.rs
[binary or diff unavailable]
### external/vendor/time/src/rand010.rs
[binary or diff unavailable]
### external/vendor/time/src/rand08.rs
[binary or diff unavailable]
### external/vendor/time/src/rand09.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/iso8601.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/rfc2822.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/rfc3339.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/timestamp/microseconds.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/timestamp/milliseconds.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/timestamp/milliseconds_i64.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/timestamp/mod.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/timestamp/nanoseconds.rs
[binary or diff unavailable]
### external/vendor/time/src/serde/visitor.rs
[binary or diff unavailable]
### external/vendor/time/src/signed_duration.rs
[binary or diff unavailable]
### external/vendor/time/src/sys/local_offset_at/wasm_js.rs
[binary or diff unavailable]
### external/vendor/time/src/sys/local_offset_at/windows.rs
[binary or diff unavailable]
### external/vendor/time/src/sys/refresh_tz/unix.rs
[binary or diff unavailable]
### external/vendor/time/src/tests.rs
[binary or diff unavailable]
### external/vendor/time/src/time.rs
[binary or diff unavailable]
### external/vendor/time/src/timestamp.rs
[binary or diff unavailable]
### external/vendor/time/src/utc_date_time.rs
[binary or diff unavailable]
### external/vendor/time/src/utc_offset.rs
[binary or diff unavailable]
### external/vendor/time/src/util.rs
[binary or diff unavailable]
### external/vendor/time/src/weekday.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_date.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_date.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_datetime.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_datetime.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_format_description.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_format_description.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_offset.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_offset.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_serializer.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_serializer.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_time.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_time.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_utc_datetime.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/compile-fail/invalid_utc_datetime.stderr
[binary or diff unavailable]
### external/vendor/time/tests/integration/convert.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/date.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/date_iter.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/derives.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/duration.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/error.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/ext.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/format_description.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/formatting.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/instant.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/macros.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/main.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/meta.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/month.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/month_iter.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/offset_date_time.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/parse_format_description.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/parsed.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/parsing.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/plain_date_time.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/quickcheck.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/rand.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/error_conditions.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/iso8601.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/json.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/macros.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/mod.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/rfc2822.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/rfc3339.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde/timestamps.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/serde_helpers.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/time.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/timestamp.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/utc_date_time.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/utc_offset.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/util.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/weekday.rs
[binary or diff unavailable]
### external/vendor/time/tests/integration/weekday_iter.rs
[binary or diff unavailable]
### src/rust/Cargo.lock
[binary or diff unavailable]
### src/rust/util/Cargo.toml
[binary or diff unavailable]
### test/simulator-graphical-bb03/Cargo.lock
[binary or diff unavailable]
### test/simulator-graphical/Cargo.lock
[binary or diff unavailable]Why this scored 33/100
Community notes
Notes can correct, qualify, or add evidence to the AI analysis. Every note shown here has been validated by a human moderator.
The AI analysis stands alone for now. Submit a note if you can add evidence or important context.