Merge remote-tracking branch 'agent/benma-agent/rust-audit-upgrades'
What changed, and why it matters
This is a large dependency upgrade commit for the BitBox02 firmware, primarily updating vendored Rust cryptography and utility crates (such as aead, anyhow, chacha20poly1305, sha2, etc.) and adding build flags to use smaller 32-bit and compact software-only backends. The commit itself is a routine maintenance/audit upgrade merge; it does not introduce an obvious vulnerability in the diff shown, but any large dependency bump carries a risk of subtle breaking changes or supply-chain issues. There is no vendor statement or external advisory supplied that identifies this commit as a security fix or as addressing a known vulnerability.
Treat as a normal dependency maintenance commit. Review the full upstream changelogs of the updated crates (especially aead, chacha20poly1305, sha2, crypto-bigint) for any security advisories or breaking behavior. Verify that the new cfg flags are applied consistently across all build paths and that firmware tests still pass. Run the project's cryptographic test suite and consider a firmware-size/performance regression check.
Security signals we found
Large dependency upgrade with breaking API changes in cryptographic traits
New build-time cfg flags selecting smaller software-only SHA-2 and 32-bit crypto-bigint backends
Removal of deprecated/stateful AEAD traits in upstream aead crate
No explicit security bug fix or CVE reference in commit or supplied materials
Evidence from the diff
The merge commit ‘rust-audit-upgrades’ updates many external/vendor Rust crates and synchronizes build configuration across .cargo/config.toml, CMakeLists.txt, and CI. Notable changes include: switching the aead crate from 0.5.2 to 0.6.1 (API changes: AeadInOut trait, removal of AeadMut*, removal of stream module, generic-array replaced by hybrid-array), adding –cfg cpubits=”32”, sha2_backend=”soft”, and sha2_backend_soft=”compact” flags to reduce firmware size, and updating anyhow and other crates. The diff provided is only a small sample of the 300-file change. No specific security bug, CVE, or advisory is mentioned in the commit message or supplied references.
Changed components
external/vendor/aeadexternal/vendor/anyhowexternal/vendor/chacha20poly1305external/vendor/sha2 (via cfg flags)external/vendor/crypto-bigint (via cfg flags).cargo/config.tomlCMakeLists.txt.github/workflows/ci-common.ymlInspect captured patch +235078 / −59716
### .cargo/config.toml
@@ -6,11 +6,23 @@ include = [{ path = "config.local.toml", optional = true }]
# test` and other cargo-based builds. This is replicated in src/CMakeLists.txt,
# test/simulator-graphical*/CMakeLists.txt for CMake-based builds.
# See https://github.com/rust-bitcoin/rust-secp256k1/tree/7c8270a8506e31731e540fab7ee1abde1f48314e/secp256k1-sys#linking-to-external-symbols
-rustflags = ["--cfg", "rust_secp_no_symbol_renaming"]
+# The compact SHA-2 backend saves ~3kB (measured when first enabled).
+# See https://github.com/RustCrypto/hashes/pull/686.
+# 32-bit crypto-bigint limbs save ~2.4kB on Cortex-M4. Use the same backend in host tests.
+# Keep these flags in sync with CMakeLists.txt and .github/workflows/ci-common.yml.
+rustflags = [
+ "--cfg", 'cpubits="32"',
+ "--cfg", "rust_secp_no_symbol_renaming",
+ "--cfg", 'sha2_backend="soft"',
+ "--cfg", 'sha2_backend_soft="compact"',
+]
[target.'cfg(all(target_arch = "arm", target_os = "none"))']
rustflags = [
+ "--cfg", 'cpubits="32"',
"--cfg", "rust_secp_no_symbol_renaming",
+ "--cfg", 'sha2_backend="soft"',
+ "--cfg", 'sha2_backend_soft="compact"',
"-C", "linker-plugin-lto",
# This is needed if your flash or ram addresses are not aligned to 0x10000 in memory.x
# See https://github.com/rust-embedded/cortex-m-quickstart/pull/95
### .github/workflows/ci-common.yml
@@ -15,8 +15,8 @@ on:
type: string
env:
CARGOFLAGS: "--locked"
- # RUSTFLAGS replaces .cargo/config.toml, so repeat the required secp256k1 cfg.
- RUSTFLAGS: "-Dwarnings --cfg=rust_secp_no_symbol_renaming"
+ # RUSTFLAGS replaces .cargo/config.toml, so repeat its backend and secp256k1 cfgs.
+ RUSTFLAGS: '-Dwarnings --cfg=cpubits="32" --cfg=rust_secp_no_symbol_renaming --cfg=sha2_backend="soft" --cfg=sha2_backend_soft="compact"'
CFLAGS: "-Werror"
jobs:
### CMakeLists.txt
@@ -173,11 +173,18 @@ else()
set(RUSTFLAGS "")
endif()
+# Keep the smaller 32-bit crypto-bigint backend in sync with .cargo/config.toml.
+string(APPEND RUSTFLAGS " --cfg=cpubits=\"32\"")
+
# Use libsecp256k1 that we link ourselves.
# See https://github.com/rust-bitcoin/rust-secp256k1/tree/7c8270a8506e31731e540fab7ee1abde1f48314e/secp256k1-sys#linking-to-external-symbols
# This is replicated in .cargo/config.toml because RUSTFLAGS here override the rustflags there.
string(APPEND RUSTFLAGS " --cfg=rust_secp_no_symbol_renaming")
+# Keep the compact SHA-2 backend in sync with .cargo/config.toml.
+string(APPEND RUSTFLAGS " --cfg=sha2_backend=\"soft\" --cfg=sha2_backend_soft=\"compact\"")
+separate_arguments(CARGO_ENV_FLAGS NATIVE_COMMAND "$ENV{CARGOFLAGS}")
+
#-----------------------------------------------------------------------------
# Print system information and build options
### external/vendor/aead/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"d25ef64c47aa2a16d9200724c0f56bddb4f5c24800986e070517867cfcdee0a4","CHANGELOG.md":"8870cb71cd8b46213591c7a4ee7ad80985600bd00c9f88331f825407498a00a7","Cargo.toml":"bf935971de51d6c168946e1822e1e4c3267aad0e1ae6e036b4e5baeb6d81a4be","Cargo.toml.orig":"c541eaa8f4355b379a5d3cf15e6ac710fde852fce72b5d5e9293f328d4f40622","LICENSE-APACHE":"b1cf9a3333ca78152b859012cd4a804156e5243e9ca20ad1df7327ba5ea7405c","LICENSE-MIT":"949ab7b3e7140fee216f06fe3a2bd67d68dd511f8ea73c1e01c98cb348e9c8ae","README.md":"8e195a2c3d0437b035de4640adabc6fb29ed91d814ec5073e7c2ae1a4d988748","src/dev.rs":"8a615fadb1236158cea9fde4ea96e8bb2ced4757c43b829c23eb143fc816d894","src/lib.rs":"477a851e2666a29dc3a724a75b7558d32d9ed7584364e1567dc6746c32a74fc5","src/stream.rs":"0b89b1e648972b2434cfed6556302f28ad2d8bdc11434f6905354167bf8a38e7"},"package":"d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"aab688881c8a5b1a0ba3088156dcca5862f7888520fbc6c2ce13987b9386ad57","CHANGELOG.md":"449fbb0fbfbf401b5e1d4b8383d1938b981d2bb03940109993b9e1811cdbe4f3","Cargo.lock":"2e275cfa6bd98da17d0eb94fdecf23f83f6da629fd8d83223194ec9020e77d97","Cargo.toml":"cda27d7960de6273a9969330ad54e6b87fbbf18e582da44d05ac2f2f972d0952","Cargo.toml.orig":"0da0e2362ce942618293c1a911cc955570becbf90f767c345b8f7c2e0d8a1554","LICENSE-APACHE":"b1cf9a3333ca78152b859012cd4a804156e5243e9ca20ad1df7327ba5ea7405c","LICENSE-MIT":"33b32a251d445c5c03a634e64c53314c55540fc367fabdd45d9b6c8f260c028c","README.md":"9b68d9e33e8b1ee904455d7e834b2a0a01a1d9eba4ae2ee279ca98941b8e2a28","src/dev.rs":"951c14eaa0517e1eaee035d4d4a204cd384a588b4be26a254240c42a015018ea","src/lib.rs":"a0c317d7c4a3209885193c93a357f0d86fb353bdb2837cfb889ab0ffc4bd7cbd","tests/data/postfix_fail.blb":"a5de9025a8dd4b8954f145462bdcc4d2f677fbab2971f6f61cbbf24ee12d0e37","tests/data/postfix_pass.blb":"4fa5d8e04fb8aa968ba079635e751ac89f0fa3b968d6cb83d89d81512bc45400","tests/data/prefix_fail.blb":"54fb9bf29f0d86525854a1762e89df55eef11f9ce860555d000e3fd1fd233a30","tests/data/prefix_pass.blb":"7b1c59d21eb68a8a97ed625bfe457bf95c005b344468d49f1330502c3a5e0777","tests/dummy.rs":"6678d520e4133e199c0fe2dfe9f0005f03159f7312e850d1255849db04b5d50f"},"package":"1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"}
\ No newline at end of file
### external/vendor/aead/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1ae238c527c204dd9590e3abc406cfbb342d46ea"
+ "sha1": "3d2d90045bffc402af4edb6a5a4dbb1e217329d1"
},
"path_in_vcs": "aead"
}
\ No newline at end of file
### external/vendor/aead/CHANGELOG.md
@@ -5,6 +5,50 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.6.1 (2026-06-17)
+### Changed
+- Have `getrandom` feature enable `rand_core` ([#2452])
+
+[#2452]: https://github.com/RustCrypto/traits/pull/2452
+
+## 0.6.0 (2026-06-08)
+### Added
+- Enable `missing_debug_implementations` lint and add `Debug` impls ([#1411])
+- `AeadCore::TAG_POSITION` and `TagPosition` enum ([#1798])
+- Re-export `crypto_common` as `common` ([#2237])
+
+### Changed
+- Replace `generic-array` with `hybrid-array` ([#1384])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1759])
+- Replace `AeadInPlace` with `AeadInOut` ([#1793])
+- Split `new_test!` into `new_pass_test!` and `new_fail_test!` ([#2019])
+- Bump `crypto-common` to v0.2 ([#2276])
+
+### Removed
+- `AeadCore::CiphertextOverhead` constant ([#1737])
+- Stateful AEAD traits: `AeadMut*` ([#1740])
+- `stream` module - extracted into `aead-stream` crate ([#1801])
+- `heapless` support - will be added back in a future patch release ([#1999])
+- Nonce generation APIs - use `Generate` trait instead ([#2098])
+
+### Fixed
+- Minor documentation error in `AeadCore::TagSize` ([#1351])
+
+[#1351]: https://github.com/RustCrypto/traits/pull/1351
+[#1384]: https://github.com/RustCrypto/traits/pull/1384
+[#1411]: https://github.com/RustCrypto/traits/pull/1411
+[#1737]: https://github.com/RustCrypto/traits/pull/1737
+[#1740]: https://github.com/RustCrypto/traits/pull/1740
+[#1759]: https://github.com/RustCrypto/traits/pull/1759
+[#1793]: https://github.com/RustCrypto/traits/pull/1793
+[#1798]: https://github.com/RustCrypto/traits/pull/1798
+[#1801]: https://github.com/RustCrypto/traits/pull/1801
+[#1999]: https://github.com/RustCrypto/traits/pull/1999
+[#2019]: https://github.com/RustCrypto/traits/pull/2019
+[#2098]: https://github.com/RustCrypto/traits/pull/2098
+[#2237]: https://github.com/RustCrypto/traits/pull/2237
+[#2276]: https://github.com/RustCrypto/traits/pull/2276
+
## 0.5.2 (2023-04-02)
### Added
- `arrayvec` feature ([#1219])
### external/vendor/aead/Cargo.lock
@@ -0,0 +1,443 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.6.1"
+dependencies = [
+ "arrayvec",
+ "blobby",
+ "bytes",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "arrayvec"
+version = "0.7.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7c02d123df017efcdfbd739ef81735b36c5ba83ec3c59c80a9d7ecc718f92e50"
+
+[[package]]
+name = "bitflags"
+version = "2.13.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "bytes"
+version = "1.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[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 = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "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.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[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.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[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.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "log"
+version = "0.4.32"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "953f07c43838f8e6f9758cab68bf5bed85465e7587ebe0b823f1bcd81978ad3a"
+
+[[package]]
+name = "memchr"
+version = "2.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
+
+[[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.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[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",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen 0.46.0",
+]
+
+[[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 0.51.0",
+]
+
+[[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 = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[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-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 = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/aead/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "aead"
-version = "0.5.2"
+version = "0.6.1"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
@@ -34,48 +40,84 @@ repository = "https://github.com/RustCrypto/traits"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = []
+default = ["rand_core"]
+dev = [
+ "blobby",
+ "alloc",
+]
+getrandom = [
+ "common/getrandom",
+ "rand_core",
]
+rand_core = ["common/rand_core"]
+
+[lib]
+name = "aead"
+path = "src/lib.rs"
+
+[[test]]
+name = "dummy"
+path = "tests/dummy.rs"
[dependencies.arrayvec]
version = "0.7"
optional = true
default-features = false
[dependencies.blobby]
-version = "0.3"
+version = "0.4"
optional = true
[dependencies.bytes]
-version = "1"
+version = "1.11.1"
optional = true
default-features = false
-[dependencies.crypto-common]
-version = "0.1.4"
+[dependencies.common]
+version = "0.2"
+package = "crypto-common"
-[dependencies.generic-array]
-version = "0.14"
-default-features = false
+[dependencies.inout]
+version = "0.2.2"
-[dependencies.heapless]
-version = "0.7"
-optional = true
-default-features = false
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
-[features]
-alloc = []
-default = ["rand_core"]
-dev = ["blobby"]
-getrandom = [
- "crypto-common/getrandom",
- "rand_core",
-]
-rand_core = ["crypto-common/rand_core"]
-std = [
- "alloc",
- "crypto-common/std",
-]
-stream = []
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/aead/Cargo.toml.orig
@@ -1,39 +1,38 @@
[package]
name = "aead"
-version = "0.5.2"
-description = """
-Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
-such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
-"""
+version = "0.6.1"
authors = ["RustCrypto Developers"]
-edition = "2021"
-license = "MIT OR Apache-2.0"
-readme = "README.md"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/aead"
+readme = "README.md"
repository = "https://github.com/RustCrypto/traits"
+license = "MIT OR Apache-2.0"
keywords = ["crypto", "encryption"]
categories = ["cryptography", "no-std"]
-rust-version = "1.56"
+description = """
+Traits for Authenticated Encryption with Associated Data (AEAD) algorithms,
+such as AES-GCM as ChaCha20Poly1305, which provide a high-level API
+"""
[dependencies]
-crypto-common = "0.1.4"
-generic-array = { version = "0.14", default-features = false }
+common = { version = "0.2", package = "crypto-common" }
+inout = "0.2.2"
# optional dependencies
arrayvec = { version = "0.7", optional = true, default-features = false }
-blobby = { version = "0.3", optional = true }
-bytes = { version = "1", optional = true, default-features = false }
-heapless = { version = "0.7", optional = true, default-features = false }
+blobby = { version = "0.4", optional = true }
+bytes = { version = "1.11.1", optional = true, default-features = false }
[features]
default = ["rand_core"]
alloc = []
-std = ["alloc", "crypto-common/std"]
-dev = ["blobby"]
-getrandom = ["crypto-common/getrandom", "rand_core"]
-rand_core = ["crypto-common/rand_core"]
-stream = []
+dev = ["blobby", "alloc"]
+getrandom = ["common/getrandom", "rand_core"]
+rand_core = ["common/rand_core"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/aead/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Copyright (c) 2019 MobileCoin, LLC
Permission is hereby granted, free of charge, to any
### external/vendor/aead/README.md
@@ -15,15 +15,6 @@ modern cryptographic implementations.
See [RustCrypto/AEADs] for cipher implementations which use this trait.
-[Documentation][docs-link]
-
-## Minimum Supported Rust Version
-
-Rust **1.56** or higher.
-
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
-
## SemVer Policy
- All on-by-default features of this library are covered by SemVer
@@ -51,11 +42,11 @@ dual licensed as above, without any additional terms or conditions.
[docs-image]: https://docs.rs/aead/badge.svg
[docs-link]: https://docs.rs/aead/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs
-[build-image]: https://github.com/RustCrypto/traits/workflows/aead/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/traits/actions?query=workflow%3Aaead
+[build-image]: https://github.com/RustCrypto/traits/actions/workflows/aead.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/traits/actions/workflows/aead.yml?query=branch:master
[//]: # (general links)
### external/vendor/aead/src/dev.rs
@@ -1,75 +1,191 @@
//! Development-related functionality
+
+#![allow(clippy::missing_errors_doc, reason = "dev module")]
+#![allow(clippy::missing_panics_doc, reason = "dev module")]
+#![allow(clippy::unwrap_in_result, reason = "dev module")]
+
+use crate::{
+ Aead, AeadInOut, Payload, Tag, TagPosition, array::typenum::Unsigned, inout::InOutBuf,
+};
pub use blobby;
+use common::KeyInit;
+
+/// AEAD test vector
+#[derive(Debug, Clone, Copy)]
+pub struct TestVector {
+ /// Initialization key
+ pub key: &'static [u8],
+ /// Nonce
+ pub nonce: &'static [u8],
+ /// Additional associated data
+ pub aad: &'static [u8],
+ /// Plaintext
+ pub plaintext: &'static [u8],
+ /// Ciphertext
+ pub ciphertext: &'static [u8],
+}
+
+/// Run AEAD test for the provided passing test vector
+#[allow(clippy::cast_possible_truncation)]
+pub fn pass_test<C: AeadInOut + KeyInit>(
+ &TestVector {
+ key,
+ nonce,
+ aad,
+ plaintext,
+ ciphertext,
+ }: &TestVector,
+) -> Result<(), &'static str> {
+ let nonce = nonce.try_into().expect("wrong nonce size");
+ let cipher = <C as KeyInit>::new_from_slice(key).expect("failed to initialize the cipher");
+
+ let res = cipher
+ .encrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: plaintext,
+ },
+ )
+ .map_err(|_| "encryption failure")?;
+ if res != ciphertext {
+ return Err("encrypted data is different from target ciphertext");
+ }
+
+ let res = cipher
+ .decrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: ciphertext,
+ },
+ )
+ .map_err(|_| "decryption failure")?;
+ if res != plaintext {
+ return Err("decrypted data is different from target plaintext");
+ }
+
+ let (ct, tag) = match C::TAG_POSITION {
+ TagPosition::Prefix => {
+ let (tag, ct) = ciphertext.split_at(C::TagSize::USIZE);
+ (ct, tag)
+ }
+ TagPosition::Postfix => ciphertext.split_at(plaintext.len()),
+ };
+ let tag: &Tag<C> = tag.try_into().expect("tag has correct length");
+
+ // Fill output buffer with "garbage" to test that its data does not get read during encryption
+ let mut buf: alloc::vec::Vec<u8> = (0..plaintext.len()).map(|i| i as u8).collect();
+ let inout_buf = InOutBuf::new(plaintext, &mut buf).expect("pt and buf have the same length");
+
+ let calc_tag = cipher
+ .encrypt_inout_detached(nonce, aad, inout_buf)
+ .map_err(|_| "encrypt_inout_detached: encryption failure")?;
+ if tag != &calc_tag {
+ return Err("encrypt_inout_detached: tag mismatch");
+ }
+ if ct != buf {
+ return Err("encrypt_inout_detached: ciphertext mismatch");
+ }
+
+ // Fill output buffer with "garbage"
+ buf.iter_mut()
+ .enumerate()
+ .for_each(|(i, v): (usize, &mut u8)| *v = i as u8);
+
+ let inout_buf = InOutBuf::new(ct, &mut buf).expect("ct and buf have the same length");
+ cipher
+ .decrypt_inout_detached(nonce, aad, inout_buf, tag)
+ .map_err(|_| "decrypt_inout_detached: decryption failure")?;
+ if plaintext != buf {
+ return Err("decrypt_inout_detached: plaintext mismatch");
+ }
+
+ Ok(())
+}
+
+/// Run AEAD test for the provided failing test vector
+pub fn fail_test<C: AeadInOut + KeyInit>(
+ &TestVector {
+ key,
+ nonce,
+ aad,
+ ciphertext,
+ ..
+ }: &TestVector,
+) -> Result<(), &'static str> {
+ let nonce = nonce.try_into().expect("wrong nonce size");
+ let cipher = <C as KeyInit>::new_from_slice(key).expect("failed to initialize the cipher");
+
+ let res = cipher.decrypt(
+ nonce,
+ Payload {
+ aad,
+ msg: ciphertext,
+ },
+ );
+ if res.is_ok() {
+ Err("decryption must return error")
+ } else {
+ Ok(())
+ }
+}
-/// Define AEAD test
+/// Define AEAD test for passing test vectors
#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! new_test {
+macro_rules! new_pass_test {
($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
#[test]
fn $name() {
- use aead::{
- dev::blobby::Blob6Iterator,
- generic_array::{typenum::Unsigned, GenericArray},
- Aead, KeyInit, Payload,
- };
-
- fn run_test(
- key: &[u8],
- nonce: &[u8],
- aad: &[u8],
- pt: &[u8],
- ct: &[u8],
- pass: bool,
- ) -> Result<(), &'static str> {
- let key = key.try_into().map_err(|_| "wrong key size")?;
- let cipher = <$cipher>::new(key);
- let nonce = nonce.try_into().map_err(|_| "wrong nonce size")?;
-
- if !pass {
- let res = cipher.decrypt(nonce, Payload { aad: aad, msg: ct });
- if res.is_ok() {
- return Err("decryption must return error");
- }
- return Ok(());
- }
+ use $crate::dev::TestVector;
- let res = cipher
- .encrypt(nonce, Payload { aad: aad, msg: pt })
- .map_err(|_| "encryption failure")?;
- if res != ct {
- return Err("encrypted data is different from target ciphertext");
- }
- let res = cipher
- .decrypt(nonce, Payload { aad: aad, msg: ct })
- .map_err(|_| "decryption failure")?;
- if res != pt {
- return Err("decrypted data is different from target plaintext");
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $test_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, nonce, aad, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ let res = $crate::dev::pass_test::<$cipher>(tv);
+
+ if let Err(reason) = res {
+ panic!(
+ "\n\
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n"
+ );
}
- Ok(())
}
+ }
+ };
+}
+
+/// Define AEAD test for failing test vectors
+#[macro_export]
+macro_rules! new_fail_test {
+ ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
+ #[test]
+ fn $name() {
+ use $crate::dev::TestVector;
+
+ $crate::dev::blobby::parse_into_structs!(
+ include_bytes!(concat!("data/", $test_name, ".blb"));
+ static TEST_VECTORS: &[
+ TestVector { key, nonce, aad, plaintext, ciphertext }
+ ];
+ );
+
+ for (i, tv) in TEST_VECTORS.iter().enumerate() {
+ let res = $crate::dev::fail_test::<$cipher>(tv);
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob6Iterator::new(data).unwrap().enumerate() {
- let [key, nonce, aad, pt, ct, status] = row.unwrap();
- let pass = match status[0] {
- 0 => false,
- 1 => true,
- _ => panic!("invalid value for pass flag"),
- };
- if let Err(reason) = run_test(key, nonce, aad, pt, ct, pass) {
+ if let Err(reason) = res {
panic!(
"\n\
- Failed test №{}\n\
- reason: \t{:?}\n\
- key:\t{:?}\n\
- nonce:\t{:?}\n\
- aad:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n\
- pass:\t{}\n\
- ",
- i, reason, key, nonce, aad, pt, ct, pass,
+ Failed test #{i}\n\
+ reason:\t{reason:?}\n\
+ test vector:\t{tv:?}\n"
);
}
}
### external/vendor/aead/src/lib.rs
@@ -1,76 +1,40 @@
-//! [Authenticated Encryption with Associated Data] (AEAD) traits
-//!
-//! This crate provides an abstract interface for AEAD ciphers, which guarantee
-//! both confidentiality and integrity, even from a powerful attacker who is
-//! able to execute [chosen-ciphertext attacks]. The resulting security property,
-//! [ciphertext indistinguishability], is considered a basic requirement for
-//! modern cryptographic implementations.
-//!
-//! See [RustCrypto/AEADs] for cipher implementations which use this trait.
-//!
-//! [Authenticated Encryption with Associated Data]: https://en.wikipedia.org/wiki/Authenticated_encryption
-//! [chosen-ciphertext attacks]: https://en.wikipedia.org/wiki/Chosen-ciphertext_attack
-//! [ciphertext indistinguishability]: https://en.wikipedia.org/wiki/Ciphertext_indistinguishability
-//! [RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs
-
#![no_std]
#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
#![forbid(unsafe_code)]
-#![warn(clippy::unwrap_used, missing_docs, rust_2018_idioms)]
#[cfg(feature = "alloc")]
extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
-
#[cfg(feature = "dev")]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
pub mod dev;
-#[cfg(feature = "stream")]
-#[cfg_attr(docsrs, doc(cfg(feature = "stream")))]
-pub mod stream;
-
-pub use crypto_common::{Key, KeyInit, KeySizeUser};
-pub use generic_array::{self, typenum::consts};
+pub use common::{
+ self, Key, KeyInit, KeySizeUser,
+ array::{self, typenum::consts},
+};
#[cfg(feature = "arrayvec")]
-#[cfg_attr(docsrs, doc(cfg(feature = "arrayvec")))]
pub use arrayvec;
-
#[cfg(feature = "bytes")]
-#[cfg_attr(docsrs, doc(cfg(feature = "bytes")))]
pub use bytes;
-
-#[cfg(feature = "getrandom")]
-#[cfg_attr(docsrs, doc(cfg(feature = "getrandom")))]
-pub use crypto_common::rand_core::OsRng;
-
-#[cfg(feature = "heapless")]
-#[cfg_attr(docsrs, doc(cfg(feature = "heapless")))]
-pub use heapless;
-
#[cfg(feature = "rand_core")]
-#[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
-pub use crypto_common::rand_core;
+pub use common::{Generate, rand_core};
+pub use inout;
+use common::array::{Array, ArraySize, typenum::Unsigned};
use core::fmt;
-use generic_array::{typenum::Unsigned, ArrayLength, GenericArray};
+use inout::InOutBuf;
#[cfg(feature = "alloc")]
use alloc::vec::Vec;
-
#[cfg(feature = "bytes")]
use bytes::BytesMut;
-#[cfg(feature = "rand_core")]
-use rand_core::{CryptoRng, RngCore};
-
/// Error type.
///
/// This type is deliberately opaque as to avoid potential side-channel
@@ -87,83 +51,83 @@ impl fmt::Display for Error {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for Error {}
+impl core::error::Error for Error {}
-/// Nonce: single-use value for ensuring ciphertexts are unique
-pub type Nonce<A> = GenericArray<u8, <A as AeadCore>::NonceSize>;
+/// Nonce: single-use value for ensuring ciphertexts are unique.
+///
+/// AEAD algorithms accept a parameter to encryption/decryption called
+/// a "nonce" which must be unique every time encryption is performed and
+/// never repeated for the same key. The nonce is often prepended to the
+/// ciphertext, a.k.a. an explicit nonce, but may also be an implicit counter.
+///
+/// AEAD decryption takes the nonce which was originally used to produce a
+/// given ciphertext as a parameter along with the ciphertext itself.
+///
+/// # Generating random nonces
+///
+/// Nonces don't necessarily have to be random, but it is a simple strategy
+/// which can be implemented as follows using the [`Generate`] trait
+/// (requires `getrandom` feature):
+///
+/// ```text
+/// use aead::{Nonce, Generate};
+///
+/// let nonce = Nonce::<AeadAlg>::generate();
+/// ```
+///
+/// <div class="warning">
+/// AEAD algorithms often fail catastrophically if nonces are ever repeated
+/// (with SIV modes being an exception).
+///
+/// Using random nonces runs the risk of repeating them unless the nonce
+/// size is particularly large, e.g. 192-bit extended nonces used by the
+/// `XChaCha20Poly1305` and `XSalsa20Poly1305` constructions.
+///
+/// [NIST SP 800-38D] recommends the following:
+///
+/// > The total number of invocations of the authenticated encryption
+/// > function shall not exceed 2<sup>32</sup>, including all IV lengths and all
+/// > instances of the authenticated encryption function with the given key.
+///
+/// Following this guideline, only 4,294,967,296 messages with random
+/// nonces can be encrypted under a given key. While this bound is high,
+/// it's possible to encounter in practice, and systems which might
+/// reach it should consider alternatives to purely random nonces, like
+/// a counter or a combination of a random nonce + counter.
+///
+/// See the [`aead-stream`] crate for a ready-made implementation of the latter.
+/// </div>
+///
+/// [NIST SP 800-38D]: https://csrc.nist.gov/publications/detail/sp/800-38d/final
+/// [`aead-stream`]: https://docs.rs/aead-stream
+pub type Nonce<A> = Array<u8, <A as AeadCore>::NonceSize>;
/// Tag: authentication code which ensures ciphertexts are authentic
-pub type Tag<A> = GenericArray<u8, <A as AeadCore>::TagSize>;
+pub type Tag<A> = Array<u8, <A as AeadCore>::TagSize>;
+
+/// Enum which specifies tag position used by an AEAD algorithm.
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+pub enum TagPosition {
+ /// Postfix tag
+ Postfix,
+ /// Prefix tag
+ Prefix,
+}
-/// Authenticated Encryption with Associated Data (AEAD) algorithm core trait.
-///
-/// Defines nonce, tag, and overhead sizes that are consumed by various other
-/// `Aead*` traits.
+/// Authenticated Encryption with Associated Data (AEAD) algorithm.
pub trait AeadCore {
/// The length of a nonce.
- type NonceSize: ArrayLength<u8>;
-
- /// The maximum length of the nonce.
- type TagSize: ArrayLength<u8>;
+ type NonceSize: ArraySize;
- /// The upper bound amount of additional space required to support a
- /// ciphertext vs. a plaintext.
- type CiphertextOverhead: ArrayLength<u8> + Unsigned;
+ /// The maximum length of the tag.
+ type TagSize: ArraySize;
- /// Generate a random nonce for this AEAD algorithm.
- ///
- /// AEAD algorithms accept a parameter to encryption/decryption called
- /// a "nonce" which must be unique every time encryption is performed and
- /// never repeated for the same key. The nonce is often prepended to the
- /// ciphertext. The nonce used to produce a given ciphertext must be passed
- /// to the decryption function in order for it to decrypt correctly.
- ///
- /// Nonces don't necessarily have to be random, but it is one strategy
- /// which is implemented by this function.
- ///
- /// # ⚠️Security Warning
- ///
- /// AEAD algorithms often fail catastrophically if nonces are ever repeated
- /// (with SIV modes being an exception).
- ///
- /// Using random nonces runs the risk of repeating them unless the nonce
- /// size is particularly large (e.g. 192-bit extended nonces used by the
- /// `XChaCha20Poly1305` and `XSalsa20Poly1305` constructions.
- ///
- /// [NIST SP 800-38D] recommends the following:
- ///
- /// > The total number of invocations of the authenticated encryption
- /// > function shall not exceed 2^32, including all IV lengths and all
- /// > instances of the authenticated encryption function with the given key.
- ///
- /// Following this guideline, only 4,294,967,296 messages with random
- /// nonces can be encrypted under a given key. While this bound is high,
- /// it's possible to encounter in practice, and systems which might
- /// reach it should consider alternatives to purely random nonces, like
- /// a counter or a combination of a random nonce + counter.
- ///
- /// See the [`stream`] module for a ready-made implementation of the latter.
- ///
- /// [NIST SP 800-38D]: https://csrc.nist.gov/publications/detail/sp/800-38d/final
- #[cfg(feature = "rand_core")]
- #[cfg_attr(docsrs, doc(cfg(feature = "rand_core")))]
- fn generate_nonce(mut rng: impl CryptoRng + RngCore) -> Nonce<Self>
- where
- Nonce<Self>: Default,
- {
- let mut nonce = Nonce::<Self>::default();
- rng.fill_bytes(&mut nonce);
- nonce
- }
+ /// The AEAD tag position.
+ const TAG_POSITION: TagPosition;
}
/// Authenticated Encryption with Associated Data (AEAD) algorithm.
-///
-/// This trait is intended for use with stateless AEAD algorithms. The
-/// [`AeadMut`] trait provides a stateful interface.
#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
pub trait Aead: AeadCore {
/// Encrypt the given plaintext payload, and return the resulting
/// ciphertext as a vector of bytes.
@@ -188,6 +152,9 @@ pub trait Aead: AeadCore {
/// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not
/// use a postfix tag will need to override this to correctly assemble the
/// ciphertext message.
+ ///
+ /// # Errors
+ /// AEAD algorithm implementations may return an error if the plaintext or AAD are too long.
fn encrypt<'msg, 'aad>(
&self,
nonce: &Nonce<Self>,
@@ -211,70 +178,81 @@ pub trait Aead: AeadCore {
/// AES-GCM-SIV, ChaCha20Poly1305). [`Aead`] implementations which do not
/// use a postfix tag will need to override this to correctly parse the
/// ciphertext message.
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
+ /// - if the `ciphertext` is too long
+ /// - if the `aad` is too long
fn decrypt<'msg, 'aad>(
&self,
nonce: &Nonce<Self>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
) -> Result<Vec<u8>>;
}
-/// Stateful Authenticated Encryption with Associated Data algorithm.
#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
-pub trait AeadMut: AeadCore {
- /// Encrypt the given plaintext slice, and return the resulting ciphertext
- /// as a vector of bytes.
- ///
- /// See notes on [`Aead::encrypt()`] about allowable message payloads and
- /// Associated Additional Data (AAD).
+impl<T: AeadInOut> Aead for T {
fn encrypt<'msg, 'aad>(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>>;
+ ) -> Result<Vec<u8>> {
+ let payload = plaintext.into();
+ let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
+ buffer.extend_from_slice(payload.msg);
+ self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
+ Ok(buffer)
+ }
- /// Decrypt the given ciphertext slice, and return the resulting plaintext
- /// as a vector of bytes.
- ///
- /// See notes on [`Aead::encrypt()`] and [`Aead::decrypt()`] about allowable
- /// message payloads and Associated Additional Data (AAD).
fn decrypt<'msg, 'aad>(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>>;
+ ) -> Result<Vec<u8>> {
+ let payload = ciphertext.into();
+ let mut buffer = Vec::from(payload.msg);
+ self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
+ Ok(buffer)
+ }
}
-/// Implement the `decrypt_in_place` method on [`AeadInPlace`] and
-/// [`AeadMutInPlace]`, using a macro to gloss over the `&self` vs `&mut self`.
-///
-/// Assumes a postfix authentication tag. AEAD ciphers which do not use a
-/// postfix authentication tag will need to define their own implementation.
-macro_rules! impl_decrypt_in_place {
- ($aead:expr, $nonce:expr, $aad:expr, $buffer:expr) => {{
- if $buffer.len() < Self::TagSize::to_usize() {
- return Err(Error);
- }
+/// In-place and inout AEAD trait which handles the authentication tag as a return value/separate parameter.
+pub trait AeadInOut: AeadCore {
+ /// Encrypt the data in the provided [`InOutBuf`], returning the authentication tag.
+ ///
+ /// # Errors
+ /// AEAD algorithm implementations may return an error if the plaintext or AAD are too long.
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ associated_data: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>>;
- let tag_pos = $buffer.len() - Self::TagSize::to_usize();
- let (msg, tag) = $buffer.as_mut().split_at_mut(tag_pos);
- $aead.decrypt_in_place_detached($nonce, $aad, msg, Tag::<Self>::from_slice(tag))?;
- $buffer.truncate(tag_pos);
- Ok(())
- }};
-}
+ /// Decrypt the data in the provided [`InOutBuf`], returning an error in the event the
+ /// provided authentication tag is invalid for the given ciphertext (i.e. ciphertext
+ /// is modified/unauthentic).
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
+ /// - if the `ciphertext` is too long
+ /// - if the `aad` is too long
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ associated_data: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()>;
-/// In-place stateless AEAD trait.
-///
-/// This trait is both object safe and has no dependencies on `alloc` or `std`.
-pub trait AeadInPlace: AeadCore {
/// Encrypt the given buffer containing a plaintext message in-place.
///
/// The buffer must have sufficient capacity to store the ciphertext
/// message, which will always be larger than the original plaintext.
/// The exact size needed is cipher-dependent, but generally includes
/// the size of an authentication tag.
///
+ /// # Errors
/// Returns an error if the buffer has insufficient capacity to store the
/// resulting ciphertext message.
fn encrypt_in_place(
@@ -283,191 +261,151 @@ pub trait AeadInPlace: AeadCore {
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
- let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?;
- buffer.extend_from_slice(tag.as_slice())?;
+ match Self::TAG_POSITION {
+ TagPosition::Prefix => {
+ let msg_len = buffer.len();
+ buffer.extend_from_slice(&Tag::<Self>::default())?;
+ let buffer = buffer.as_mut();
+ let tag_size = Self::TagSize::USIZE;
+ buffer.copy_within(..msg_len, tag_size);
+ let (tag_dst, msg) = buffer.split_at_mut(tag_size);
+ let tag = self.encrypt_inout_detached(nonce, associated_data, msg.into())?;
+ tag_dst.copy_from_slice(&tag);
+ }
+ TagPosition::Postfix => {
+ let tag =
+ self.encrypt_inout_detached(nonce, associated_data, buffer.as_mut().into())?;
+ buffer.extend_from_slice(tag.as_slice())?;
+ }
+ }
Ok(())
}
- /// Encrypt the data in-place, returning the authentication tag
- fn encrypt_in_place_detached(
- &self,
- nonce: &Nonce<Self>,
- associated_data: &[u8],
- buffer: &mut [u8],
- ) -> Result<Tag<Self>>;
-
/// Decrypt the message in-place, returning an error in the event the
/// provided authentication tag does not match the given ciphertext.
///
/// The buffer will be truncated to the length of the original plaintext
/// message upon success.
+ ///
+ /// # Errors
+ /// - if the `ciphertext` is inauthentic (i.e. tag verification failure)
fn decrypt_in_place(
&self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut dyn Buffer,
) -> Result<()> {
- impl_decrypt_in_place!(self, nonce, associated_data, buffer)
+ let tag_size = Self::TagSize::USIZE;
+ let tagless_len = buffer.len().checked_sub(tag_size).ok_or(Error)?;
+
+ match Self::TAG_POSITION {
+ TagPosition::Prefix => {
+ let (tag, msg) = buffer.as_mut().split_at_mut(tag_size);
+ let tag = Tag::<Self>::try_from(&*tag).expect("tag length mismatch");
+ self.decrypt_inout_detached(nonce, associated_data, msg.into(), &tag)?;
+ buffer.as_mut().copy_within(tag_size.., 0);
+ }
+ TagPosition::Postfix => {
+ let (msg, tag) = buffer.as_mut().split_at_mut(tagless_len);
+ let tag = Tag::<Self>::try_from(&*tag).expect("tag length mismatch");
+ self.decrypt_inout_detached(nonce, associated_data, msg.into(), &tag)?;
+ }
+ }
+ buffer.truncate(tagless_len);
+ Ok(())
}
-
- /// Decrypt the message in-place, returning an error in the event the provided
- /// authentication tag does not match the given ciphertext (i.e. ciphertext
- /// is modified/unauthentic)
- fn decrypt_in_place_detached(
- &self,
- nonce: &Nonce<Self>,
- associated_data: &[u8],
- buffer: &mut [u8],
- tag: &Tag<Self>,
- ) -> Result<()>;
}
-/// In-place stateful AEAD trait.
+/// Legacy in-place stateless AEAD trait.
///
-/// This trait is both object safe and has no dependencies on `alloc` or `std`.
-pub trait AeadMutInPlace: AeadCore {
+/// NOTE: deprecated! Please migrate to [`AeadInOut`].
+#[deprecated(since = "0.6.0", note = "use `AeadInOut` instead")]
+#[allow(clippy::missing_errors_doc)]
+pub trait AeadInPlace: AeadCore {
/// Encrypt the given buffer containing a plaintext message in-place.
- ///
- /// The buffer must have sufficient capacity to store the ciphertext
- /// message, which will always be larger than the original plaintext.
- /// The exact size needed is cipher-dependent, but generally includes
- /// the size of an authentication tag.
- ///
- /// Returns an error if the buffer has insufficient capacity to store the
- /// resulting ciphertext message.
+ #[deprecated(since = "0.6.0", note = "use `AeadInOut::encrypt_in_place` instead")]
fn encrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
- ) -> Result<()> {
- let tag = self.encrypt_in_place_detached(nonce, associated_data, buffer.as_mut())?;
- buffer.extend_from_slice(tag.as_slice())?;
- Ok(())
- }
+ buffer: &mut dyn Buffer,
+ ) -> Result<()>;
/// Encrypt the data in-place, returning the authentication tag
+ #[deprecated(
+ since = "0.6.0",
+ note = "use `AeadInOut::encrypt_inout_detached` instead"
+ )]
fn encrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag<Self>>;
/// Decrypt the message in-place, returning an error in the event the
/// provided authentication tag does not match the given ciphertext.
- ///
- /// The buffer will be truncated to the length of the original plaintext
- /// message upon success.
+ #[deprecated(since = "0.6.0", note = "use `AeadInOut::decrypt_in_place` instead")]
fn decrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
- ) -> Result<()> {
- impl_decrypt_in_place!(self, nonce, associated_data, buffer)
- }
+ buffer: &mut dyn Buffer,
+ ) -> Result<()>;
- /// Decrypt the data in-place, returning an error in the event the provided
+ /// Decrypt the message in-place, returning an error in the event the provided
/// authentication tag does not match the given ciphertext (i.e. ciphertext
/// is modified/unauthentic)
+ #[deprecated(
+ since = "0.6.0",
+ note = "use `AeadInOut::decrypt_inout_detached` instead"
+ )]
fn decrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag<Self>,
) -> Result<()>;
}
-#[cfg(feature = "alloc")]
-impl<Alg: AeadInPlace> Aead for Alg {
- fn encrypt<'msg, 'aad>(
- &self,
- nonce: &Nonce<Self>,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- fn decrypt<'msg, 'aad>(
- &self,
- nonce: &Nonce<Self>,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-}
-
-#[cfg(feature = "alloc")]
-impl<Alg: AeadMutInPlace> AeadMut for Alg {
- fn encrypt<'msg, 'aad>(
- &mut self,
- nonce: &Nonce<Self>,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + Self::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- fn decrypt<'msg, 'aad>(
- &mut self,
- nonce: &Nonce<Self>,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(nonce, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-}
-
-impl<Alg: AeadInPlace> AeadMutInPlace for Alg {
+#[allow(deprecated)]
+impl<T: AeadInOut> AeadInPlace for T {
fn encrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
+ buffer: &mut dyn Buffer,
) -> Result<()> {
- <Self as AeadInPlace>::encrypt_in_place(self, nonce, associated_data, buffer)
+ <Self as AeadInOut>::encrypt_in_place(self, nonce, associated_data, buffer)
}
fn encrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
) -> Result<Tag<Self>> {
- <Self as AeadInPlace>::encrypt_in_place_detached(self, nonce, associated_data, buffer)
+ self.encrypt_inout_detached(nonce, associated_data, buffer.into())
}
fn decrypt_in_place(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
- buffer: &mut impl Buffer,
+ buffer: &mut dyn Buffer,
) -> Result<()> {
- <Self as AeadInPlace>::decrypt_in_place(self, nonce, associated_data, buffer)
+ <Self as AeadInOut>::decrypt_in_place(self, nonce, associated_data, buffer)
}
fn decrypt_in_place_detached(
- &mut self,
+ &self,
nonce: &Nonce<Self>,
associated_data: &[u8],
buffer: &mut [u8],
tag: &Tag<Self>,
) -> Result<()> {
- <Self as AeadInPlace>::decrypt_in_place_detached(self, nonce, associated_data, buffer, tag)
+ self.decrypt_inout_detached(nonce, associated_data, buffer.into(), tag)
}
}
@@ -479,8 +417,7 @@ impl<Alg: AeadInPlace> AeadMutInPlace for Alg {
///
/// If you don't care about AAD, you can pass a `&[u8]` as the payload to
/// `encrypt`/`decrypt` and it will automatically be coerced to this type.
-#[cfg(feature = "alloc")]
-#[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
+#[derive(Debug)]
pub struct Payload<'msg, 'aad> {
/// Message to be encrypted/decrypted
pub msg: &'msg [u8],
@@ -492,8 +429,7 @@ pub struct Payload<'msg, 'aad> {
pub aad: &'aad [u8],
}
-#[cfg(feature = "alloc")]
-impl<'msg, 'aad> From<&'msg [u8]> for Payload<'msg, 'aad> {
+impl<'msg> From<&'msg [u8]> for Payload<'msg, '_> {
fn from(msg: &'msg [u8]) -> Self {
Self { msg, aad: b"" }
}
@@ -514,10 +450,13 @@ pub trait Buffer: AsRef<[u8]> + AsMut<[u8]> {
self.as_ref().is_empty()
}
- /// Extend this buffer from the given slice
+ /// Extend this buffer from the given slice.
+ ///
+ /// # Errors
+ /// If the buffer has insufficient capacity.
fn extend_from_slice(&mut self, other: &[u8]) -> Result<()>;
- /// Truncate this buffer to the given size
+ /// Truncate this buffer to the given size.
fn truncate(&mut self, len: usize);
}
@@ -563,29 +502,3 @@ impl<const N: usize> Buffer for arrayvec::ArrayVec<u8, N> {
arrayvec::ArrayVec::truncate(self, len);
}
}
-
-#[cfg(feature = "heapless")]
-impl<const N: usize> Buffer for heapless::Vec<u8, N> {
- fn extend_from_slice(&mut self, other: &[u8]) -> Result<()> {
- heapless::Vec::extend_from_slice(self, other).map_err(|_| Error)
- }
-
- fn truncate(&mut self, len: usize) {
- heapless::Vec::truncate(self, len);
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- /// Ensure that `AeadInPlace` is object-safe
- #[allow(dead_code)]
- type DynAeadInPlace<N, T, O> =
- dyn AeadInPlace<NonceSize = N, TagSize = T, CiphertextOverhead = O>;
-
- /// Ensure that `AeadMutInPlace` is object-safe
- #[allow(dead_code)]
- type DynAeadMutInPlace<N, T, O> =
- dyn AeadMutInPlace<NonceSize = N, TagSize = T, CiphertextOverhead = O>;
-}
### external/vendor/aead/src/stream.rs
@@ -1,542 +0,0 @@
-//! Streaming AEAD support.
-//!
-//! Implementation of the STREAM online authenticated encryption construction
-//! as described in the paper
-//! [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1].
-//!
-//! ## About
-//!
-//! The STREAM construction supports encrypting/decrypting sequences of AEAD
-//! message segments, which is useful in cases where the overall message is too
-//! large to fit in a single buffer and needs to be processed incrementally.
-//!
-//! STREAM defends against reordering and truncation attacks which are common
-//! in naive schemes which attempt to provide these properties, and is proven
-//! to meet the security definition of "nonce-based online authenticated
-//! encryption" (nOAE) as given in the aforementioned paper.
-//!
-//! ## Diagram
-//!
-//! 
-//!
-//! Legend:
-//!
-//! - 𝐄k: AEAD encryption under key `k`
-//! - 𝐌: message
-//! - 𝐍: nonce
-//! - 𝐀: additional associated data
-//! - 𝐂: ciphertext
-//! - 𝜏: MAC tag
-//!
-//! [1]: https://eprint.iacr.org/2015/189.pdf
-
-#![allow(clippy::upper_case_acronyms)]
-
-use crate::{AeadCore, AeadInPlace, Buffer, Error, Key, KeyInit, Result};
-use core::ops::{AddAssign, Sub};
-use generic_array::{
- typenum::{Unsigned, U4, U5},
- ArrayLength, GenericArray,
-};
-
-#[cfg(feature = "alloc")]
-use {crate::Payload, alloc::vec::Vec};
-
-/// Nonce as used by a given AEAD construction and STREAM primitive.
-pub type Nonce<A, S> = GenericArray<u8, NonceSize<A, S>>;
-
-/// Size of a nonce as used by a STREAM construction, sans the overhead of
-/// the STREAM protocol itself.
-pub type NonceSize<A, S> =
- <<A as AeadCore>::NonceSize as Sub<<S as StreamPrimitive<A>>::NonceOverhead>>::Output;
-
-/// STREAM encryptor instantiated with [`StreamBE32`] as the underlying
-/// STREAM primitive.
-pub type EncryptorBE32<A> = Encryptor<A, StreamBE32<A>>;
-
-/// STREAM decryptor instantiated with [`StreamBE32`] as the underlying
-/// STREAM primitive.
-pub type DecryptorBE32<A> = Decryptor<A, StreamBE32<A>>;
-
-/// STREAM encryptor instantiated with [`StreamLE31`] as the underlying
-/// STREAM primitive.
-pub type EncryptorLE31<A> = Encryptor<A, StreamLE31<A>>;
-
-/// STREAM decryptor instantiated with [`StreamLE31`] as the underlying
-/// STREAM primitive.
-pub type DecryptorLE31<A> = Decryptor<A, StreamLE31<A>>;
-
-/// Create a new STREAM from the provided AEAD.
-pub trait NewStream<A>: StreamPrimitive<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<Self::NonceOverhead>,
- NonceSize<A, Self>: ArrayLength<u8>,
-{
- /// Create a new STREAM with the given key and nonce.
- fn new(key: &Key<A>, nonce: &Nonce<A, Self>) -> Self
- where
- A: KeyInit,
- Self: Sized,
- {
- Self::from_aead(A::new(key), nonce)
- }
-
- /// Create a new STREAM from the given AEAD cipher.
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self;
-}
-
-/// Low-level STREAM implementation.
-///
-/// This trait provides a particular "flavor" of STREAM, as there are
-/// different ways the specifics of the construction can be implemented.
-///
-/// Deliberately immutable and stateless to permit parallel operation.
-pub trait StreamPrimitive<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<Self::NonceOverhead>,
- NonceSize<A, Self>: ArrayLength<u8>,
-{
- /// Number of bytes this STREAM primitive requires from the nonce.
- type NonceOverhead: ArrayLength<u8>;
-
- /// Type used as the STREAM counter.
- type Counter: AddAssign + Copy + Default + Eq;
-
- /// Value to use when incrementing the STREAM counter (i.e. one)
- const COUNTER_INCR: Self::Counter;
-
- /// Maximum value of the STREAM counter.
- const COUNTER_MAX: Self::Counter;
-
- /// Encrypt an AEAD message in-place at the given position in the STREAM.
- fn encrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()>;
-
- /// Decrypt an AEAD message in-place at the given position in the STREAM.
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()>;
-
- /// Encrypt the given plaintext payload, and return the resulting
- /// ciphertext as a vector of bytes.
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- fn encrypt<'msg, 'aad>(
- &self,
- position: Self::Counter,
- last_block: bool,
- plaintext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = plaintext.into();
- let mut buffer = Vec::with_capacity(payload.msg.len() + A::TagSize::to_usize());
- buffer.extend_from_slice(payload.msg);
- self.encrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- /// Decrypt the given ciphertext slice, and return the resulting plaintext
- /// as a vector of bytes.
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- fn decrypt<'msg, 'aad>(
- &self,
- position: Self::Counter,
- last_block: bool,
- ciphertext: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- let payload = ciphertext.into();
- let mut buffer = Vec::from(payload.msg);
- self.decrypt_in_place(position, last_block, payload.aad, &mut buffer)?;
- Ok(buffer)
- }
-
- /// Obtain [`Encryptor`] for this [`StreamPrimitive`].
- fn encryptor(self) -> Encryptor<A, Self>
- where
- Self: Sized,
- {
- Encryptor::from_stream_primitive(self)
- }
-
- /// Obtain [`Decryptor`] for this [`StreamPrimitive`].
- fn decryptor(self) -> Decryptor<A, Self>
- where
- Self: Sized,
- {
- Decryptor::from_stream_primitive(self)
- }
-}
-
-/// Implement a stateful STREAM object (i.e. encryptor or decryptor)
-macro_rules! impl_stream_object {
- (
- $name:ident,
- $next_method:tt,
- $next_in_place_method:tt,
- $last_method:tt,
- $last_in_place_method:tt,
- $op:tt,
- $in_place_op:tt,
- $op_desc:expr,
- $obj_desc:expr
- ) => {
- #[doc = "Stateful STREAM object which can"]
- #[doc = $op_desc]
- #[doc = "AEAD messages one-at-a-time."]
- #[doc = ""]
- #[doc = "This corresponds to the "]
- #[doc = $obj_desc]
- #[doc = "object as defined in the paper"]
- #[doc = "[Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1]."]
- #[doc = ""]
- #[doc = "[1]: https://eprint.iacr.org/2015/189.pdf"]
- pub struct $name<A, S>
- where
- A: AeadInPlace,
- S: StreamPrimitive<A>,
- A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
- NonceSize<A, S>: ArrayLength<u8>,
- {
- /// Underlying STREAM primitive.
- stream: S,
-
- /// Current position in the STREAM.
- position: S::Counter,
- }
-
- impl<A, S> $name<A, S>
- where
- A: AeadInPlace,
- S: StreamPrimitive<A>,
- A::NonceSize: Sub<<S as StreamPrimitive<A>>::NonceOverhead>,
- NonceSize<A, S>: ArrayLength<u8>,
- {
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given AEAD key and nonce."]
- pub fn new(key: &Key<A>, nonce: &Nonce<A, S>) -> Self
- where
- A: KeyInit,
- S: NewStream<A>,
- {
- Self::from_stream_primitive(S::new(key, nonce))
- }
-
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given AEAD primitive."]
- pub fn from_aead(aead: A, nonce: &Nonce<A, S>) -> Self
- where
- A: KeyInit,
- S: NewStream<A>,
- {
- Self::from_stream_primitive(S::from_aead(aead, nonce))
- }
-
- #[doc = "Create a"]
- #[doc = $obj_desc]
- #[doc = "object from the given STREAM primitive."]
- pub fn from_stream_primitive(stream: S) -> Self {
- Self {
- stream,
- position: Default::default(),
- }
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the next AEAD message in this STREAM, returning the"]
- #[doc = "result as a [`Vec`]."]
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- pub fn $next_method<'msg, 'aad>(
- &mut self,
- payload: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- if self.position == S::COUNTER_MAX {
- // Counter overflow. Note that the maximum counter value is
- // deliberately disallowed, as it would preclude being able
- // to encrypt a last block (i.e. with `$last_in_place_method`)
- return Err(Error);
- }
-
- let result = self.stream.$op(self.position, false, payload)?;
-
- // Note: overflow checked above
- self.position += S::COUNTER_INCR;
- Ok(result)
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the next AEAD message in this STREAM in-place."]
- pub fn $next_in_place_method(
- &mut self,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- if self.position == S::COUNTER_MAX {
- // Counter overflow. Note that the maximum counter value is
- // deliberately disallowed, as it would preclude being able
- // to encrypt a last block (i.e. with `$last_in_place_method`)
- return Err(Error);
- }
-
- self.stream
- .$in_place_op(self.position, false, associated_data, buffer)?;
-
- // Note: overflow checked above
- self.position += S::COUNTER_INCR;
- Ok(())
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the last AEAD message in this STREAM,"]
- #[doc = "consuming the "]
- #[doc = $obj_desc]
- #[doc = "object in order to prevent further use."]
- #[cfg(feature = "alloc")]
- #[cfg_attr(docsrs, doc(cfg(feature = "alloc")))]
- pub fn $last_method<'msg, 'aad>(
- self,
- payload: impl Into<Payload<'msg, 'aad>>,
- ) -> Result<Vec<u8>> {
- self.stream.$op(self.position, true, payload)
- }
-
- #[doc = "Use the underlying AEAD to"]
- #[doc = $op_desc]
- #[doc = "the last AEAD message in this STREAM in-place,"]
- #[doc = "consuming the "]
- #[doc = $obj_desc]
- #[doc = "object in order to prevent further use."]
- pub fn $last_in_place_method(
- self,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- self.stream
- .$in_place_op(self.position, true, associated_data, buffer)
- }
- }
- };
-}
-
-impl_stream_object!(
- Encryptor,
- encrypt_next,
- encrypt_next_in_place,
- encrypt_last,
- encrypt_last_in_place,
- encrypt,
- encrypt_in_place,
- "encrypt",
- "ℰ STREAM encryptor"
-);
-
-impl_stream_object!(
- Decryptor,
- decrypt_next,
- decrypt_next_in_place,
- decrypt_last,
- decrypt_last_in_place,
- decrypt,
- decrypt_in_place,
- "decrypt",
- "𝒟 STREAM decryptor"
-);
-
-/// The original "Rogaway-flavored" STREAM as described in the paper
-/// [Online Authenticated-Encryption and its Nonce-Reuse Misuse-Resistance][1].
-///
-/// Uses a 32-bit big endian counter and 1-byte "last block" flag stored as
-/// the last 5-bytes of the AEAD nonce.
-///
-/// [1]: https://eprint.iacr.org/2015/189.pdf
-pub struct StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- /// Underlying AEAD cipher
- aead: A,
-
- /// Nonce (sans STREAM overhead)
- nonce: Nonce<A, Self>,
-}
-
-impl<A> NewStream<A> for StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
- Self {
- aead,
- nonce: nonce.clone(),
- }
- }
-}
-
-impl<A> StreamPrimitive<A> for StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- type NonceOverhead = U5;
- type Counter = u32;
- const COUNTER_INCR: u32 = 1;
- const COUNTER_MAX: u32 = core::u32::MAX;
-
- fn encrypt_in_place(
- &self,
- position: u32,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block);
- self.aead.encrypt_in_place(&nonce, associated_data, buffer)
- }
-
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block);
- self.aead.decrypt_in_place(&nonce, associated_data, buffer)
- }
-}
-
-impl<A> StreamBE32<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U5>,
- <<A as AeadCore>::NonceSize as Sub<U5>>::Output: ArrayLength<u8>,
-{
- /// Compute the full AEAD nonce including the STREAM counter and last
- /// block flag.
- fn aead_nonce(&self, position: u32, last_block: bool) -> crate::Nonce<A> {
- let mut result = GenericArray::default();
-
- // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics)
- let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
- prefix.copy_from_slice(&self.nonce);
-
- let (counter, flag) = tail.split_at_mut(4);
- counter.copy_from_slice(&position.to_be_bytes());
- flag[0] = last_block as u8;
-
- result
- }
-}
-
-/// STREAM as instantiated with a 31-bit little endian counter and 1-bit
-/// "last block" flag stored as the most significant bit of the counter
-/// when interpreted as a 32-bit integer.
-///
-/// The 31-bit + 1-bit value is stored as the last 4 bytes of the AEAD nonce.
-pub struct StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- /// Underlying AEAD cipher
- aead: A,
-
- /// Nonce (sans STREAM overhead)
- nonce: Nonce<A, Self>,
-}
-
-impl<A> NewStream<A> for StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- fn from_aead(aead: A, nonce: &Nonce<A, Self>) -> Self {
- Self {
- aead,
- nonce: nonce.clone(),
- }
- }
-}
-
-impl<A> StreamPrimitive<A> for StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- type NonceOverhead = U4;
- type Counter = u32;
- const COUNTER_INCR: u32 = 1;
- const COUNTER_MAX: u32 = 0xfff_ffff;
-
- fn encrypt_in_place(
- &self,
- position: u32,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block)?;
- self.aead.encrypt_in_place(&nonce, associated_data, buffer)
- }
-
- fn decrypt_in_place(
- &self,
- position: Self::Counter,
- last_block: bool,
- associated_data: &[u8],
- buffer: &mut dyn Buffer,
- ) -> Result<()> {
- let nonce = self.aead_nonce(position, last_block)?;
- self.aead.decrypt_in_place(&nonce, associated_data, buffer)
- }
-}
-
-impl<A> StreamLE31<A>
-where
- A: AeadInPlace,
- A::NonceSize: Sub<U4>,
- <<A as AeadCore>::NonceSize as Sub<U4>>::Output: ArrayLength<u8>,
-{
- /// Compute the full AEAD nonce including the STREAM counter and last
- /// block flag.
- fn aead_nonce(&self, position: u32, last_block: bool) -> Result<crate::Nonce<A>> {
- if position > Self::COUNTER_MAX {
- return Err(Error);
- }
-
- let mut result = GenericArray::default();
-
- // TODO(tarcieri): use `generic_array::sequence::Concat` (or const generics)
- let (prefix, tail) = result.split_at_mut(NonceSize::<A, Self>::to_usize());
- prefix.copy_from_slice(&self.nonce);
-
- let position_with_flag = position | ((last_block as u32) << 31);
- tail.copy_from_slice(&position_with_flag.to_le_bytes());
-
- Ok(result)
- }
-}
### external/vendor/aead/tests/data/postfix_fail.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/postfix_pass.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/prefix_fail.blb
[binary or diff unavailable]
### external/vendor/aead/tests/data/prefix_pass.blb
[binary or diff unavailable]
### external/vendor/aead/tests/dummy.rs
@@ -0,0 +1,195 @@
+//! This module defines dummy (horribly insecure!) AEAD implementations
+//! to test implementation of the AEAD traits and helper macros in the `dev` module.
+
+#![cfg(feature = "dev")]
+#![allow(missing_docs, reason = "tests")]
+#![allow(clippy::trivially_copy_pass_by_ref, reason = "tests")]
+#![allow(clippy::unwrap_used, reason = "tests")]
+
+use aead::{
+ AeadCore, AeadInOut, Error, Key, KeyInit, KeySizeUser, Nonce, Result, Tag, TagPosition,
+ array::Array, consts::U8,
+};
+use core::fmt;
+use inout::InOutBuf;
+
+struct DummyAead {
+ key: [u8; 8],
+}
+
+impl fmt::Debug for DummyAead {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("DummyAead").finish_non_exhaustive()
+ }
+}
+
+impl DummyAead {
+ fn process_aad(&self, nonce: &[u8; 8], aad: &[u8]) -> u64 {
+ let mut tag = u64::from_le_bytes(*nonce);
+ let key = u64::from_le_bytes(self.key);
+
+ let mut aad_iter = aad.chunks_exact(8);
+ for chunk in &mut aad_iter {
+ tag ^= u64::from_le_bytes(chunk.try_into().unwrap());
+ tag = tag.wrapping_add(key);
+ }
+ let aad_rem = aad_iter.remainder();
+ if !aad_rem.is_empty() {
+ let mut chunk = [0u8; 8];
+ chunk[..aad_rem.len()].copy_from_slice(aad_rem);
+ tag ^= u64::from_le_bytes(chunk);
+ tag = tag.wrapping_add(key);
+ }
+
+ tag
+ }
+
+ fn encrypt_inner(
+ &self,
+ nonce: &[u8; 8],
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<[u8; 8]> {
+ let mut tag = self.process_aad(nonce, aad);
+
+ let (blocks, mut rem) = buffer.into_chunks::<U8>();
+ for mut block in blocks {
+ block.xor_in2out(&self.key.into());
+ tag ^= u64::from_be_bytes(block.get_out().0);
+ }
+
+ if !rem.is_empty() {
+ rem.xor_in2out(&self.key[..rem.len()]);
+
+ let out_rem = rem.get_out();
+ let mut block = [0u8; 8];
+ block[..out_rem.len()].copy_from_slice(out_rem);
+ tag ^= u64::from_le_bytes(block);
+ }
+
+ Ok(tag.to_le_bytes())
+ }
+
+ fn decrypt_inner(
+ &self,
+ nonce: &[u8; 8],
+ aad: &[u8],
+ mut buffer: InOutBuf<'_, '_, u8>,
+ tag: &[u8; 8],
+ ) -> Result<()> {
+ let exp_tag = u64::from_le_bytes(*tag);
+ let mut tag = self.process_aad(nonce, aad);
+
+ let (blocks, mut rem) = buffer.reborrow().into_chunks::<U8>();
+ for mut block in blocks {
+ tag ^= u64::from_be_bytes(block.get_in().0);
+ block.xor_in2out(&self.key.into());
+ }
+
+ if !rem.is_empty() {
+ let in_rem = rem.get_in();
+ let mut block = [0u8; 8];
+ block[..in_rem.len()].copy_from_slice(in_rem);
+ tag ^= u64::from_le_bytes(block);
+
+ rem.xor_in2out(&self.key[..rem.len()]);
+ }
+
+ if tag == exp_tag {
+ Ok(())
+ } else {
+ buffer.get_out().fill(0);
+ Err(Error)
+ }
+ }
+}
+
+#[derive(Debug)]
+pub struct PrefixDummyAead(DummyAead);
+
+impl KeySizeUser for PrefixDummyAead {
+ type KeySize = U8;
+}
+
+impl KeyInit for PrefixDummyAead {
+ fn new(key: &Key<Self>) -> Self {
+ Self(DummyAead { key: key.0 })
+ }
+}
+
+impl AeadCore for PrefixDummyAead {
+ type NonceSize = U8;
+ type TagSize = U8;
+ const TAG_POSITION: TagPosition = TagPosition::Prefix;
+}
+
+impl AeadInOut for PrefixDummyAead {
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>> {
+ self.0.encrypt_inner(nonce.into(), aad, buffer).map(Array)
+ }
+
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()> {
+ self.0.decrypt_inner(nonce.into(), aad, buffer, tag.into())
+ }
+}
+
+#[derive(Debug)]
+pub struct PostfixDummyAead(DummyAead);
+
+impl KeySizeUser for PostfixDummyAead {
+ type KeySize = U8;
+}
+
+impl KeyInit for PostfixDummyAead {
+ fn new(key: &Key<Self>) -> Self {
+ Self(DummyAead { key: key.0 })
+ }
+}
+
+impl AeadCore for PostfixDummyAead {
+ type NonceSize = U8;
+ type TagSize = U8;
+ const TAG_POSITION: TagPosition = TagPosition::Postfix;
+}
+
+impl AeadInOut for PostfixDummyAead {
+ fn encrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ ) -> Result<Tag<Self>> {
+ self.0.encrypt_inner(nonce.into(), aad, buffer).map(Array)
+ }
+
+ fn decrypt_inout_detached(
+ &self,
+ nonce: &Nonce<Self>,
+ aad: &[u8],
+ buffer: InOutBuf<'_, '_, u8>,
+ tag: &Tag<Self>,
+ ) -> Result<()> {
+ self.0.decrypt_inner(nonce.into(), aad, buffer, tag.into())
+ }
+}
+
+#[cfg(feature = "dev")]
+mod tests {
+ use super::{PostfixDummyAead, PrefixDummyAead};
+
+ aead::new_pass_test!(dummy_prefix_pass, "prefix_pass", PrefixDummyAead);
+ aead::new_fail_test!(dummy_prefix_fail, "prefix_fail", PrefixDummyAead);
+ aead::new_pass_test!(dummy_postfix_pass, "postfix_pass", PostfixDummyAead);
+ aead::new_fail_test!(dummy_postfix_fail, "postfix_fail", PostfixDummyAead);
+}
### 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/base16ct/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"61e987635c874915b3f443ae090ab3e290dbc924fa295ecd30000ea90ef56f1a","CHANGELOG.md":"4804ca1b5d84da4177354125912a29ca7a9a6a4ebba5b752fcee61911c9fe23f","Cargo.toml":"5050aa1f3351bf8c11a55b9695a41f5ec4652c95d7243c5b45a301692e2782e6","Cargo.toml.orig":"1c06e13c10380bc494ec2909809e4d38ac1dd7875f0d676ea3b7c3df3628b57c","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"0aa8963e105e8b6e02f634484145d4e5b0f42d0a6dd05c16f8148f033383adef","README.md":"535e9fe765cd20cc185be3458871253bca8ded1c2132e6e20ed3706044ddf2e9","benches/mod.rs":"976e6c0443e69a0578a2cf2252c4ed486ff0dc39823d0c369625e31c89941657","src/display.rs":"7042d46254a4fe4c1d66fe41be90916010247fd6dbdf3e87532541aa1a199696","src/error.rs":"8c5ac9c8d2d3b6fe18d8cf56d7e48149fb4d44c32ccb71f566f243c70e9bb187","src/lib.rs":"be52249977ee3d023a22beb0f805ad2d2bd69333cd17a0670c92002e57557ce9","src/lower.rs":"5ed8a602a6fbbe15c01c27a18a579a9df0599cecab7bd0420b26862c62ea91aa","src/mixed.rs":"12fc969194a5bf4776c9f1ccfd208c1abfa9e0abcd265a9b493f0af8382163dc","src/upper.rs":"c75c9b6ef7eddc5e23ef1699b1445ddf729e031a13e328c9e9b181e681daeec1","tests/lib.rs":"1b5ae439670c8c1ca3843922bd484dc642b660d91f401a29fa279d9e01fdab92"},"package":"4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"82c6aaf4f1ee71c1a6a4e032c566292f1720415831469cc9d1d26c94b7042ea8","CHANGELOG.md":"b2e1c87ae9da42e56f8c3870a60d04c16fab092c3b6da647c863cda01e18011a","Cargo.lock":"f0014bb1c2ab24d793a3a8501854b7fe5b5d7e0513cf75bd846b171ed7eafdea","Cargo.toml":"71f43fd6a618c6914ea149f9adb39d11a39876071ea01556b8bee0e93d9d632e","Cargo.toml.orig":"be56ce3a1760d8860032adc72ba887a735b93f1a087f43946a68312b8f411161","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"54fb6dfe99a6906f862aa40282f0e8e9d9d0f22d57d99ab8acbaf4c8ceaa70e0","README.md":"e84a0d385575ff9e54c3b89265c8da316b9a8673a0a7c11c3a728e76a557cdb5","benches/mod.rs":"be5c1574736c0d48f1df7b00a4fb9935e4b850cda1685d8cd5bc61a4411b6094","src/display.rs":"9e45093df7c2a3c758e499d3fec1d60e400df554f158f0d26bc6e93f98ff43e0","src/error.rs":"56b2c8893aec1331796a4c951476e2e20b45b55848d14e1116dbf4a1f195e589","src/lib.rs":"178db5fdbf52816e139a958b2739494d4b17f8e54905ab9155ef1c84410fedb8","src/lower.rs":"21b523f53f17b14051d60d2792b9186ad7ce744f4ee8fb3584cd3ecad7c032d9","src/mixed.rs":"2d13475dc62ff8431daa6792f3240e11d22f0f93c221529645f5080fbedb73c8","src/upper.rs":"e527d6a26c14698e988317b7e8a5d15e65e50fdee67b5e11da512f51349982ab","tests/lib.rs":"1b5ae439670c8c1ca3843922bd484dc642b660d91f401a29fa279d9e01fdab92"},"package":"fd307490d624467aa6f74b0eabb77633d1f758a7b25f12bceb0b22e08d9726f6"}
\ No newline at end of file
### external/vendor/base16ct/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1987929403b544d4632121aacff3d28aa09a0771"
+ "sha1": "071bfe69e2010e869397d27c63a88f188bd6477b"
},
"path_in_vcs": "base16ct"
}
\ No newline at end of file
### external/vendor/base16ct/CHANGELOG.md
@@ -4,6 +4,24 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 1.0.0 (2026-01-03)
+### Fixed
+- Switch from `doc_auto_cfg` to `doc_cfg` ([#2072])
+
+[#2072]: https://github.com/RustCrypto/formats/pull/2072
+
+## 0.3.0 (2025-08-20)
+### Changed
+- Upgrade to 2024 edition; MSRV 1.85 ([#1670])
+- Use `core::error:Error` ([#1842])
+
+### Removed
+- `std` feature ([#2004])
+
+[#1670]: https://github.com/RustCrypto/formats/pull/1670
+[#1842]: https://github.com/RustCrypto/formats/pull/1842
+[#2004]: https://github.com/RustCrypto/formats/pull/2004
+
## 0.2.0 (2023-02-26)
### Changed
- MSRV 1.60 ([#802])
### external/vendor/base16ct/Cargo.lock
@@ -0,0 +1,7 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "base16ct"
+version = "1.0.0"
### external/vendor/base16ct/Cargo.toml
@@ -10,16 +10,23 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.60"
+edition = "2024"
+rust-version = "1.85"
name = "base16ct"
-version = "0.2.0"
+version = "1.0.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Pure Rust implementation of Base16 a.k.a hexadecimal (RFC 4648) which avoids
any usages of data-dependent branches/LUTs and thereby provides portable
-\"best effort\" constant-time operation and embedded-friendly no_std support
+"best effort" constant-time operation and embedded-friendly no_std support
"""
+homepage = "https://github.com/RustCrypto/formats/tree/master/base16ct"
documentation = "https://docs.rs/base16ct"
readme = "README.md"
keywords = [
@@ -34,7 +41,8 @@ categories = [
"parser-implementations",
]
license = "Apache-2.0 OR MIT"
-repository = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+repository = "https://github.com/RustCrypto/formats"
+resolver = "2"
[package.metadata.docs.rs]
all-features = true
@@ -45,4 +53,15 @@ rustdoc-args = [
[features]
alloc = []
-std = ["alloc"]
+
+[lib]
+name = "base16ct"
+path = "src/lib.rs"
+
+[[test]]
+name = "lib"
+path = "tests/lib.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
### external/vendor/base16ct/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "base16ct"
-version = "0.2.0"
+version = "1.0.0"
description = """
Pure Rust implementation of Base16 a.k.a hexadecimal (RFC 4648) which avoids
any usages of data-dependent branches/LUTs and thereby provides portable
@@ -9,16 +9,16 @@ any usages of data-dependent branches/LUTs and thereby provides portable
authors = ["RustCrypto Developers"]
license = "Apache-2.0 OR MIT"
documentation = "https://docs.rs/base16ct"
-repository = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+homepage = "https://github.com/RustCrypto/formats/tree/master/base16ct"
+repository = "https://github.com/RustCrypto/formats"
categories = ["cryptography", "encoding", "no-std", "parser-implementations"]
keywords = ["crypto", "hex", "hexadecimal"]
readme = "README.md"
-edition = "2021"
-rust-version = "1.60"
+edition = "2024"
+rust-version = "1.85"
[features]
alloc = []
-std = ["alloc"]
[package.metadata.docs.rs]
all-features = true
### external/vendor/base16ct/LICENSE-MIT
@@ -1,5 +1,5 @@
Copyright (c) 2014 Steve "Sc00bz" Thomas (steve at tobtu dot com)
-Copyright (c) 2022 The RustCrypto Project Developers
+Copyright (c) 2022-2025 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/base16ct/README.md
@@ -18,12 +18,12 @@ Supports `no_std` environments and avoids heap allocations in the core API
[Documentation][docs-link]
-## Minimum Supported Rust Version
+## Minimum Supported Rust Version (MSRV) Policy
-This crate requires **Rust 1.60** at a minimum.
+MSRV increases are not considered breaking changes and can happen in patch releases.
-We may change the MSRV in the future, but it will be accompanied by a minor
-version bump.
+The crate MSRV accounts for all supported targets and crate feature combinations, excluding
+explicitly unstable features.
## License
@@ -42,14 +42,14 @@ dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
-[crate-image]: https://buildstats.info/crate/base16ct
+[crate-image]: https://img.shields.io/crates/v/base16ct
[crate-link]: https://crates.io/crates/base16ct
[docs-image]: https://docs.rs/base16ct/badge.svg
[docs-link]: https://docs.rs/base16ct/
[build-image]: https://github.com/RustCrypto/formats/actions/workflows/base16ct.yml/badge.svg
[build-link]: https://github.com/RustCrypto/formats/actions/workflows/base16ct.yml
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.60+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/300570-formats
### external/vendor/base16ct/benches/mod.rs
@@ -1,7 +1,7 @@
#![feature(test)]
extern crate test;
-use test::{black_box, Bencher};
+use test::{Bencher, black_box};
#[bench]
fn decode_lower(b: &mut Bencher) {
### external/vendor/base16ct/src/display.rs
@@ -6,7 +6,7 @@ pub struct HexDisplay<'a>(pub &'a [u8]);
impl fmt::Display for HexDisplay<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
- write!(f, "{:X}", self)
+ write!(f, "{self:X}")
}
}
### external/vendor/base16ct/src/error.rs
@@ -22,11 +22,10 @@ impl fmt::Display for Error {
}
}
-#[cfg(feature = "std")]
-impl std::error::Error for Error {}
+impl core::error::Error for Error {}
-impl From<Error> for core::fmt::Error {
- fn from(_: Error) -> core::fmt::Error {
- core::fmt::Error::default()
+impl From<Error> for fmt::Error {
+ fn from(_: Error) -> fmt::Error {
+ fmt::Error
}
}
### external/vendor/base16ct/src/lib.rs
@@ -1,5 +1,5 @@
#![no_std]
-#![cfg_attr(docsrs, feature(doc_auto_cfg))]
+#![cfg_attr(docsrs, feature(doc_cfg))]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
@@ -62,8 +62,6 @@
#[cfg(feature = "alloc")]
#[macro_use]
extern crate alloc;
-#[cfg(feature = "std")]
-extern crate std;
/// Function for decoding and encoding lower Base16 (hex)
pub mod lower;
### external/vendor/base16ct/src/lower.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, encoded_len, Error};
+use crate::{Error, decode_inner, encoded_len};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, String, Vec};
+use crate::{String, Vec, decoded_len};
/// Decode a lower Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
### external/vendor/base16ct/src/mixed.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, Error};
+use crate::{Error, decode_inner};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, Vec};
+use crate::{Vec, decoded_len};
/// Decode a mixed Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
### external/vendor/base16ct/src/upper.rs
@@ -1,6 +1,6 @@
-use crate::{decode_inner, encoded_len, Error};
+use crate::{Error, decode_inner, encoded_len};
#[cfg(feature = "alloc")]
-use crate::{decoded_len, String, Vec};
+use crate::{String, Vec, decoded_len};
/// Decode an upper Base16 (hex) string into the provided destination buffer.
pub fn decode(src: impl AsRef<[u8]>, dst: &mut [u8]) -> Result<&[u8], Error> {
@@ -46,7 +46,7 @@ pub fn encode_string(input: &[u8]) -> String {
let res = encode(input, &mut dst).expect("dst length is correct");
debug_assert_eq!(elen, res.len());
- unsafe { crate::String::from_utf8_unchecked(dst) }
+ unsafe { String::from_utf8_unchecked(dst) }
}
/// Decode a single nibble of upper hex
### external/vendor/bip32-ed25519/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".github/workflows/ci.yml":"d0ff5825b83ec08980dbb04e73e937b936197b228b1bb011bcaafd3e77c28688","Cargo.toml":"adfbd61e5383bc0797d07f7ca8066f036d608eb0a8a8b94b0324de8253d3b23d","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"5530596cde343de2238ec3276d94599ff6e78b7b7a20f6143162b3eceb727f29","README.md":"99a18dfc2a588d8b8cb3c287dad52d2e76c2b2b3be0e7a95cce19f509e9d59d7","rustfmt.toml":"f32d2f03b3f4b1e295c79ed49d543f1205c7dac7c3dc74f05a5a27af4fea0584","src/arbitrary.rs":"ecb52788eec1142459ab252c320a5f0e421eb63cf959260b16e689ccfc8f2590","src/bigint.rs":"756b33c8d971b282b43268671c08fb4d8af095a6ebb6e9dc0c750631650e4d14","src/lib.rs":"5744fd99f11d4a98bf88a5f4e9f73e13eb56cf7b29bacd8ebd98736bd06d88af","tests/table_test.rs":"2507b6b762fa27044a0a3922073ee50e4bcfc2f66b10f8e3ac9d36a12818c51f","tests/testdata/gen_table.py":"2fd91055920d9ac4cfb6c004b96aca42aaf2e3cf074d0d49d48ada993abdaedf","tests/testdata/table.json":"9e37a43d759f793b091f87488ea4b6d733154a10d29554c5103e12d617ae70cd"},"package":null}
\ No newline at end of file
+{"files":{".github/workflows/ci.yml":"d0ff5825b83ec08980dbb04e73e937b936197b228b1bb011bcaafd3e77c28688","Cargo.toml":"0d6a579aca6b22f48fc66ae32bab55413e48b8d4c8d8a5d28644b84fa42b9dc5","LICENSE-APACHE":"c71d239df91726fc519c6eb72d318ec65820627232b2f796219e87dcf35d0ab4","LICENSE-MIT":"5530596cde343de2238ec3276d94599ff6e78b7b7a20f6143162b3eceb727f29","README.md":"99a18dfc2a588d8b8cb3c287dad52d2e76c2b2b3be0e7a95cce19f509e9d59d7","rustfmt.toml":"f32d2f03b3f4b1e295c79ed49d543f1205c7dac7c3dc74f05a5a27af4fea0584","src/arbitrary.rs":"ecb52788eec1142459ab252c320a5f0e421eb63cf959260b16e689ccfc8f2590","src/bigint.rs":"756b33c8d971b282b43268671c08fb4d8af095a6ebb6e9dc0c750631650e4d14","src/lib.rs":"0dfd4c92271d5f3dbe2c0355265a975d60851a0feb0ba89031a74693acaf93a0","tests/table_test.rs":"0fa26516ff1b0fb4622ca1a6f32eaf30b90e1fcb0ec46f8667e91e99005180c1","tests/testdata/gen_table.py":"2fd91055920d9ac4cfb6c004b96aca42aaf2e3cf074d0d49d48ada993abdaedf","tests/testdata/table.json":"9e37a43d759f793b091f87488ea4b6d733154a10d29554c5103e12d617ae70cd"},"package":null}
\ No newline at end of file
### external/vendor/bip32-ed25519/Cargo.toml
@@ -12,7 +12,7 @@
[package]
edition = "2024"
name = "bip32-ed25519"
-version = "0.2.1"
+version = "0.2.2"
authors = ["Shift Crypto AG <support@shiftcrypto.ch>"]
build = false
autolib = false
@@ -38,31 +38,30 @@ name = "table_test"
path = "tests/table_test.rs"
[dependencies.curve25519-dalek]
-version = "4"
+version = "5.0"
default-features = false
[dependencies.digest]
-version = "0.10"
+version = "0.11"
default-features = false
[dependencies.hmac]
-version = "0.12"
-features = ["reset"]
+version = "0.13"
default-features = false
[dependencies.zeroize]
-version = "1"
+version = "1.9"
features = ["zeroize_derive"]
[dev-dependencies]
-ed25519-bip32 = "0.4.0"
-num-bigint = "0.4.0"
-quickcheck = "1"
-quickcheck_macros = "1"
-serde_json = "1.0.48"
+ed25519-bip32 = "0.5.0"
+num-bigint = "0.5.1"
+quickcheck = "1.1"
+quickcheck_macros = "1.2"
+serde_json = "1.0.154"
[dev-dependencies.ed25519-dalek]
-version = "2.0.0"
+version = "3.0.0"
features = ["hazmat"]
default-features = false
@@ -71,9 +70,9 @@ version = "0.4.3"
features = ["serde"]
[dev-dependencies.serde]
-version = "1.0.104"
+version = "1.0.229"
features = ["derive"]
[dev-dependencies.sha2]
-version = "0.10"
+version = "0.11"
default-features = false
### external/vendor/bip32-ed25519/src/lib.rs
@@ -15,8 +15,8 @@ use alloc::boxed::Box;
use core::convert::TryInto;
use core::ops::{Deref, DerefMut};
-use digest::{Digest, core_api::BlockSizeUser, typenum::U64};
-use hmac::{Mac, SimpleHmac};
+use digest::{Digest, block_api::BlockSizeUser, typenum::U64};
+use hmac::{KeyInit, Mac, SimpleHmac};
use zeroize::{Zeroize, ZeroizeOnDrop, Zeroizing};
use curve25519_dalek::{
### external/vendor/bip32-ed25519/tests/table_test.rs
@@ -1,13 +1,11 @@
+// Compare our key derivation with ed25519_bip32 using the same test vectors.
+
use serde::Deserialize;
use std::fs::File;
use std::io::BufReader;
-// Our crate:
use bip32_ed25519::{ED25519_EXPANDED_SECRET_KEY_SIZE, Xprv};
-// Another crate for comparison:
-use ed25519_bip32;
-
fn mk_other_xprv(
key: &[u8; ED25519_EXPANDED_SECRET_KEY_SIZE],
chain_code: &[u8; 32],
### external/vendor/blake2/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"4a6647eae78567b5ffee84c768035d1cc1291d305162b99d7add8c72d05a3441","CHANGELOG.md":"3ef44e9baac1fd907756799009f4452ace487c9e80b32518fe2bdb758929255f","Cargo.toml":"44e9d8775828733264ddd041abf6faab096ddc25b4d6138c0274a5c98b000bda","Cargo.toml.orig":"52e3b2e2163a7fa9c44f030daf65707bbcadb5f620657acaa47c7574909a6319","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"9c768944eb4a0422ca2efc25ea9fb2fb9e7fbd3fdb04e86b87366339cb7466db","README.md":"b0218e8484d85a340ca0e21c13752355e7a24e17497e62bdb674717f5eb88bec","benches/mod.rs":"f61c6cacfe1a3f70940806d0213572f7887dc1ecc9c1946a868baad3e8a6c341","src/as_bytes.rs":"01e8e60ef0a9b68fa6bae6c1577f3967aef442c245003967604eef7e9ccae5a9","src/consts.rs":"03edc1d4697a6074c9389202324444f27625ef11f17d34cc86b83d0dda920e79","src/lib.rs":"4014e33ab4dbe879ebf8168a4cbe88f71b837589e1cd238fd469e0579337f9ff","src/macros.rs":"4d92b71adb3f464758635fa00058d478b814bb5004e5677055815547acf3a698","src/simd.rs":"79d6d11d14664c908c2f6a2120c23e8de0e0422b610a8b838aa95ba469ef43fc","src/simd/simd_opt.rs":"b254d82005e288f1d07531ef71b2468be0bc70ae9bdba1b46001acac4db283fe","src/simd/simd_opt/u32x4.rs":"f87ab763a2f7a60e0192c9eb16df3fd172f7e1747cd26e081b5e7f074701b13c","src/simd/simd_opt/u64x4.rs":"6f9e371ec300bbb3af4f4f6d9b052257eb4da669b5595b16b17f4710559f5b85","src/simd/simdint.rs":"3b506bb05761752142f61ca8de138958af9a050ddcfe5bbf454dd9a003bf71c3","src/simd/simdop.rs":"6154f31c9675f33ba476eb6d5378deda657afc79ad43be1c9257f4f4306e43ce","src/simd/simdty.rs":"24e6e7eac6005eec0aceec7b96b3a8e04ca695479bfd22e704f51926515f6f13","tests/data/blake2b/fixed.blb":"b8e100fe195f7c201973fdcb6cfcd23cc752f5c8c9431a3076208ec81709d658","tests/data/blake2b/mac.blb":"79b14e080b63c0860823c7837b8b005d9b9fbeab6cd2eaa072621ff377eafd7a","tests/data/blake2b/variable.blb":"c91130bc29c9fad4c952b79c4126bebd752073d033bf41bfe54dd656b37698e9","tests/data/blake2s/mac.blb":"4bca0c66c84951babf34ff95b9d8b0d5f6332403000bbd40cebcc142ff22d832","tests/data/blake2s/variable.blb":"ef88d9f6407013337ac8ed587ec1552b502f1001e029291c6075b40e44e3d63a","tests/mac.rs":"1e5c414e1cd44cc023ea3b7dc8a154fe8a6b36dce496a3b7a5b933e412ed51c0","tests/mod.rs":"d2da3d57ecaddbfcf292fd0475ebfd988efd52f992bd08113ef4b990f961087d","tests/persona.rs":"5e7131d30c3b4a777cc8bd8c74c00cf418d80241da10a7b74e12282c8e3fd775"},"package":"46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"dc55676bed5522173a0baf94b038de34c10f1b2e803c40813441e25df6bf76fb","CHANGELOG.md":"60a32facded37f95db2c89e295f7280b4bd17b1b4847d2bb17126c7cb01aea09","Cargo.lock":"aa51a39fe57519335f332b45500c9f35d4a45c84d6cbc8463ba107c11f9c83ac","Cargo.toml":"2ebca3b53e39bae23244d2a83997b4cfcf18efe61297a0b0d8812f7829c94c8a","Cargo.toml.orig":"e0b6c564059c0f225bcc13401df1e86bd4aa7052f782764d6bb8112d08ffb8fe","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"3721e5764ca384059a3521d84c0fb40373894a099d8246fe76bf0d7418041846","README.md":"1d69f2703bc40269549abf1363b2fc77b0f7735be61e81766522394e2958e089","benches/mod.rs":"f61c6cacfe1a3f70940806d0213572f7887dc1ecc9c1946a868baad3e8a6c341","src/consts.rs":"fc125936729983d132a43c3a51df53efe0076424bb3b2e69d9ff13bc0d8b4f2f","src/lib.rs":"a2454ef04822408b8043216ce202cc96bf11d4b69c38a93efbe3a3479955319f","src/macros.rs":"a2af7261ea14747e094d1f63e7ea29051e95a41fe3bc80e77bcc63ffd4121e1e","src/simd.rs":"718011e305dfc2633ecc7fa397519cf59c4e581f1c56535b32ee595b1870c16e","tests/data/blake2b_kat.blb":"349fe288feb3454cc92bafec3a8dc288c5f866ad0f14ad1a88adcfedcd820160","tests/data/blake2b_mac_kat.blb":"59571b8b46a5aca8d4f220b7d2a26c0d3ea5b8091792ddc5ed39fb3d9c7a684d","tests/data/blake2b_variable_kat.blb":"3e5a2d116ae86e83cee17507bc47591be189d8ed75329df166198b5821749904","tests/data/blake2s_mac_kat.blb":"b92e00d6ea305740f5b0d605c1fca621f085da3466c938307aa36b913a6f0dff","tests/data/blake2s_variable_kat.blb":"3fc58809bface0b49de94a6b44b32773216da671c20976732b7a427abd2e7ad1","tests/mac.rs":"685068303355059636b59eab6ec57442e324e740800aadbad796bdd3b2f3f0bb","tests/mod.rs":"f8e158d0d3dd63b0c93b6788fce808c9e05fb59d2e6b5b22e61c12482e895fb3","tests/persona.rs":"1d72409e123ccc890599efa22cb9ac8883a9180e89d58b41a841ed875f80b1c9","tests/unkeyed.rs":"88b80ba41741e88e49b36b655ec73e4b618c3c3ddf5317789f580fecee5a4b70"},"package":"5b5d4d889834ee8ecfc0f8426ad30faf7cdcb10f741a8e6d7224d95325479f6f"}
\ No newline at end of file
### external/vendor/blake2/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "1f727ce37ff40fa0cce84eb8543a45bdd3ca4a4e"
+ "sha1": "fa3084083d946ac12436567d5a59c0935d5db1fa"
},
"path_in_vcs": "blake2"
}
\ No newline at end of file
### external/vendor/blake2/CHANGELOG.md
@@ -5,6 +5,37 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.11.0 (2026-08-26)
+### Added
+- `zeroize` support ([#545])
+- `Blake2b128`, `Blake2b256`, `Blake2s128` type aliases ([#564])
+- `CustomizedInit` support ([#664])
+- `alloc` crate feature ([#678])
+
+### Changed
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#652])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+- Update to `digest` v0.11
+- Replace type aliases with newtypes ([#678])
+
+### Removed
+- `std` crate feature ([#678])
+- `Blake2bVar` and `Blake2sVar` types ([#744])
+- SIMD support ([#898])
+
+### Fixed
+- Handling of unkeyed hashes in keyed mode ([#510], [#612])
+
+[#510]: https://github.com/RustCrypto/hashes/pull/510
+[#545]: https://github.com/RustCrypto/hashes/pull/545
+[#564]: https://github.com/RustCrypto/hashes/pull/564
+[#612]: https://github.com/RustCrypto/hashes/pull/612
+[#652]: https://github.com/RustCrypto/hashes/pull/652
+[#664]: https://github.com/RustCrypto/hashes/pull/664
+[#678]: https://github.com/RustCrypto/hashes/pull/678
+[#744]: https://github.com/RustCrypto/hashes/pull/744
+[#898]: https://github.com/RustCrypto/hashes/pull/898
+
## 0.10.6 (2022-12-16)
### Added
- `size_opt` Cargo feature ([#440])
### external/vendor/blake2/Cargo.lock
@@ -0,0 +1,91 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "blake2"
+version = "0.11.0"
+dependencies = [
+ "digest",
+ "hex-literal",
+]
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "digest"
+version = "0.11.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "ctutils",
+ "zeroize",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.13"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/blake2/Cargo.toml
@@ -10,15 +10,21 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
name = "blake2"
-version = "0.10.6"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "BLAKE2 hash functions"
documentation = "https://docs.rs/blake2"
readme = "README.md"
keywords = [
- "crypto",
"blake2",
"hash",
"digest",
@@ -30,22 +36,47 @@ categories = [
license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/hashes"
+[package.metadata.docs.rs]
+all-features = true
+
+[features]
+alloc = ["digest/alloc"]
+default = ["alloc"]
+reset = []
+size_opt = []
+zeroize = ["digest/zeroize"]
+
+[lib]
+name = "blake2"
+path = "src/lib.rs"
+
+[[test]]
+name = "mac"
+path = "tests/mac.rs"
+
+[[test]]
+name = "mod"
+path = "tests/mod.rs"
+
+[[test]]
+name = "persona"
+path = "tests/persona.rs"
+
+[[test]]
+name = "unkeyed"
+path = "tests/unkeyed.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
+
[dependencies.digest]
-version = "0.10.3"
+version = "0.11"
features = ["mac"]
[dev-dependencies.digest]
-version = "0.10.3"
+version = "0.11"
features = ["dev"]
[dev-dependencies.hex-literal]
-version = "0.2.2"
-
-[features]
-default = ["std"]
-reset = []
-simd = []
-simd_asm = ["simd_opt"]
-simd_opt = ["simd"]
-size_opt = []
-std = ["digest/std"]
+version = "1"
### external/vendor/blake2/Cargo.toml.orig
@@ -1,28 +1,30 @@
[package]
name = "blake2"
-version = "0.10.6"
-description = "BLAKE2 hash functions"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-readme = "README.md"
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/blake2"
+readme = "README.md"
repository = "https://github.com/RustCrypto/hashes"
-keywords = ["crypto", "blake2", "hash", "digest"]
+license = "MIT OR Apache-2.0"
+keywords = ["blake2", "hash", "digest"]
categories = ["cryptography", "no-std"]
+description = "BLAKE2 hash functions"
[dependencies]
-digest = { version = "0.10.3", features = ["mac"] }
+digest = { version = "0.11", features = ["mac"] }
[dev-dependencies]
-digest = { version = "0.10.3", features = ["dev"] }
-hex-literal = "0.2.2"
+digest = { version = "0.11", features = ["dev"] }
+hex-literal = "1"
[features]
-default = ["std"]
-std = ["digest/std"]
+default = ["alloc"]
+alloc = ["digest/alloc"]
+zeroize = ["digest/zeroize"]
reset = [] # Enable reset functionality
-simd = []
-simd_opt = ["simd"]
-simd_asm = ["simd_opt"]
size_opt = [] # Optimize for code size. Removes some `inline(always)`
+
+[package.metadata.docs.rs]
+all-features = true
### external/vendor/blake2/LICENSE-MIT
@@ -1,5 +1,6 @@
-Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros
+Copyright (c) 2017-2026 The RustCrypto Project Developers
Copyright (c) 2017 Artyom Pavlov
+Copyright (c) 2015-2016 The blake2-rfc Developers, Cesar Barros
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/blake2/README.md
@@ -2,33 +2,65 @@
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
-Pure Rust implementation of the [BLAKE2 hash function][1] family.
+Pure Rust implementation of the [BLAKE2] hash function family.
+
+## Examples
+
+### Fixed output size
+
+```rust
+use blake2::{Blake2b512, Blake2s256, Digest};
+use hex_literal::hex;
+
+// create a Blake2b512 object
+let mut hasher = Blake2b512::new();
+
+// write input message
+hasher.update(b"hello world");
+
+// read hash digest and consume hasher
+let hash = hasher.finalize();
+assert_eq!(hash, hex!(
+ "021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbc"
+ "c05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0"
+));
+
+// same example for Blake2s256:
+let mut hasher = Blake2s256::new();
+hasher.update(b"hello world");
+let hash = hasher.finalize();
+assert_eq!(hash, hex!("9aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b"));
+```
-[Documentation][docs-link]
+See the [`digest`] crate docs for additional examples.
-## Minimum Supported Rust Version
+### Variable output size
-Rust **1.41** or higher.
+This implementation supports output sizes variable at compile time:
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+```rust
+use blake2::{Blake2b, Digest, digest::consts::U10};
+use hex_literal::hex;
-## SemVer Policy
+type Blake2b80 = Blake2b<U10>;
-- All on-by-default features of this library are covered by SemVer
-- MSRV is considered exempt from SemVer as noted above
+let mut hasher = Blake2b80::new();
+hasher.update(b"my_input");
+let res = hasher.finalize();
+assert_eq!(res, hex!("2cc55c84e416924e6400"));
+```
## License
-Licensed under either of:
+The crate is licensed under either of:
- * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
- * [MIT license](http://opensource.org/licenses/MIT)
+* [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
+* [MIT license](http://opensource.org/licenses/MIT)
at your option.
@@ -47,10 +79,11 @@ dual licensed as above, without any additional terms or conditions.
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260041-hashes
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
-[build-image]: https://github.com/RustCrypto/hashes/workflows/blake2/badge.svg?branch=master
-[build-link]: https://github.com/RustCrypto/hashes/actions?query=workflow%3Ablake2
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
+[build-image]: https://github.com/RustCrypto/hashes/actions/workflows/blake2.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/hashes/actions/workflows/blake2.yml?query=branch:master
[//]: # (general links)
-[1]: https://blake2.net/
+[BLAKE2]: https://blake2.net/
+[`digest`]: https://docs.rs/digest
### external/vendor/blake2/src/as_bytes.rs
@@ -1,45 +0,0 @@
-// Copyright 2016 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use core::mem;
-use core::slice;
-
-#[allow(clippy::missing_safety_doc)]
-pub unsafe trait Safe {}
-
-pub trait AsBytes {
- fn as_bytes(&self) -> &[u8];
- fn as_mut_bytes(&mut self) -> &mut [u8];
-}
-
-impl<T: Safe> AsBytes for [T] {
- #[inline]
- fn as_bytes(&self) -> &[u8] {
- unsafe {
- slice::from_raw_parts(self.as_ptr() as *const u8, self.len() * mem::size_of::<T>())
- }
- }
-
- #[inline]
- fn as_mut_bytes(&mut self) -> &mut [u8] {
- unsafe {
- slice::from_raw_parts_mut(
- self.as_mut_ptr() as *mut u8,
- self.len() * mem::size_of::<T>(),
- )
- }
- }
-}
-
-unsafe impl Safe for u8 {}
-unsafe impl Safe for u16 {}
-unsafe impl Safe for u32 {}
-unsafe impl Safe for u64 {}
-unsafe impl Safe for i8 {}
-unsafe impl Safe for i16 {}
-unsafe impl Safe for i32 {}
-unsafe impl Safe for i64 {}
### external/vendor/blake2/src/consts.rs
@@ -1,6 +1,4 @@
-#![allow(clippy::unreadable_literal)]
-
-pub static SIGMA: [[usize; 16]; 12] = [
+pub(crate) static SIGMA: [[usize; 16]; 12] = [
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15],
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
[11, 8, 12, 0, 5, 2, 15, 13, 10, 14, 3, 6, 7, 1, 9, 4],
@@ -15,7 +13,7 @@ pub static SIGMA: [[usize; 16]; 12] = [
[14, 10, 4, 8, 9, 15, 13, 6, 1, 12, 0, 2, 11, 7, 5, 3],
];
-pub static BLAKE2B_IV: [u64; 8] = [
+pub(crate) static BLAKE2B_IV: [u64; 8] = [
0x6a09e667f3bcc908,
0xbb67ae8584caa73b,
0x3c6ef372fe94f82b,
@@ -26,22 +24,6 @@ pub static BLAKE2B_IV: [u64; 8] = [
0x5be0cd19137e2179,
];
-/*
-pub const BLAKE2B_BLOCKBYTES : usize = 128;
-pub const BLAKE2B_OUTBYTES : usize = 64;
-pub const BLAKE2B_KEYBYTES : usize = 64;
-pub const BLAKE2B_SALTBYTES : usize = 16;
-pub const BLAKE2B_PERSONALBYTES : usize = 16;
-*/
-
-pub static BLAKE2S_IV: [u32; 8] = [
+pub(crate) static BLAKE2S_IV: [u32; 8] = [
0x6A09E667, 0xBB67AE85, 0x3C6EF372, 0xA54FF53A, 0x510E527F, 0x9B05688C, 0x1F83D9AB, 0x5BE0CD19,
];
-
-/*
-pub const BLAKE2S_BLOCKBYTES : usize = 64;
-pub const BLAKE2S_OUTBYTES : usize = 32;
-pub const BLAKE2S_KEYBYTES : usize = 32;
-pub const BLAKE2S_SALTBYTES : usize = 8;
-pub const BLAKE2S_PERSONALBYTES : usize = 8;
-*/
### external/vendor/blake2/src/lib.rs
@@ -1,115 +1,41 @@
-//! An implementation of the [BLAKE2][1] hash functions.
-//!
-//! # Usage
-//!
-//! [`Blake2b512`] and [`Blake2s256`] can be used in the following way:
-//!
-//! ```rust
-//! use blake2::{Blake2b512, Blake2s256, Digest};
-//! use hex_literal::hex;
-//!
-//! // create a Blake2b512 object
-//! let mut hasher = Blake2b512::new();
-//!
-//! // write input message
-//! hasher.update(b"hello world");
-//!
-//! // read hash digest and consume hasher
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("
-//! 021ced8799296ceca557832ab941a50b4a11f83478cf141f51f933f653ab9fbc
-//! c05a037cddbed06e309bf334942c4e58cdf1a46e237911ccd7fcf9787cbc7fd0
-//! ")[..]);
-//!
-//! // same example for Blake2s256:
-//! let mut hasher = Blake2s256::new();
-//! hasher.update(b"hello world");
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("
-//! 9aec6806794561107e594b1f6a8a6b0c92a0cba9acf5e5e93cca06f781813b0b
-//! ")[..]);
-//! ```
-//!
-//! Also see [RustCrypto/hashes](https://github.com/RustCrypto/hashes) readme.
-//!
-//! ## Variable output size
-//!
-//! This implementation supports run and compile time variable sizes.
-//!
-//! Run time variable output example:
-//! ```rust
-//! use blake2::Blake2bVar;
-//! use blake2::digest::{Update, VariableOutput};
-//! use hex_literal::hex;
-//!
-//! let mut hasher = Blake2bVar::new(10).unwrap();
-//! hasher.update(b"my_input");
-//! let mut buf = [0u8; 10];
-//! hasher.finalize_variable(&mut buf).unwrap();
-//! assert_eq!(buf, hex!("2cc55c84e416924e6400"));
-//! ```
-//!
-//! Compile time variable output example:
-//! ```rust
-//! use blake2::{Blake2b, Digest, digest::consts::U10};
-//! use hex_literal::hex;
-//!
-//! type Blake2b80 = Blake2b<U10>;
-//!
-//! let mut hasher = Blake2b80::new();
-//! hasher.update(b"my_input");
-//! let res = hasher.finalize();
-//! assert_eq!(res[..], hex!("2cc55c84e416924e6400")[..]);
-//! ```
-//!
-//! # Acknowledgment
-//! Based on the [blake2-rfc][2] crate.
-//!
-//! [1]: https://en.wikipedia.org/wiki/BLAKE_(hash_function)#BLAKE2
-//! [2]: https://github.com/cesarb/blake2-rfc
-
#![no_std]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
-#![cfg_attr(feature = "simd", feature(platform_intrinsics, repr_simd))]
-#![cfg_attr(feature = "simd", allow(incomplete_features))]
-
-#[cfg(feature = "std")]
-extern crate std;
+#![cfg_attr(docsrs, feature(doc_cfg))]
pub use digest::{self, Digest};
-use core::{convert::TryInto, fmt, marker::PhantomData, ops::Div};
+use core::{fmt, marker::PhantomData, ops::Div};
use digest::{
- block_buffer::{Lazy, LazyBuffer},
- consts::{U128, U32, U4, U64},
- core_api::{
- AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, CoreWrapper,
- CtVariableCoreWrapper, OutputSizeUser, RtVariableCoreWrapper, TruncSide, UpdateCore,
- VariableOutputCore,
+ CustomizedInit, FixedOutput, HashMarker, InvalidOutputSize, MacMarker, Output, Update,
+ array::{Array, ArraySize},
+ block_api::{
+ AlgorithmName, Block, BlockSizeUser, Buffer, BufferKindUser, OutputSizeUser, TruncSide,
+ UpdateCore, VariableOutputCore, VariableOutputCoreCustomized,
},
- crypto_common::{InvalidLength, Key, KeyInit, KeySizeUser},
- generic_array::{ArrayLength, GenericArray},
- typenum::{IsLessOrEqual, LeEq, NonZero, Unsigned},
- FixedOutput, HashMarker, InvalidOutputSize, MacMarker, Output, Update,
+ block_buffer::{Lazy, LazyBuffer},
+ common::{InvalidLength, Key, KeyInit, KeySizeUser},
+ consts::{U4, U16, U32, U64, U128},
+ typenum::{IsLessOrEqual, True, Unsigned},
};
#[cfg(feature = "reset")]
use digest::{FixedOutputReset, Reset};
-mod as_bytes;
+#[cfg(feature = "zeroize")]
+use digest::zeroize::{Zeroize, ZeroizeOnDrop};
+
mod consts;
mod simd;
#[macro_use]
mod macros;
-use as_bytes::AsBytes;
use consts::{BLAKE2B_IV, BLAKE2S_IV};
-use simd::{u32x4, u64x4, Vector4};
+use simd::{u32x4, u64x4};
blake2_impl!(
Blake2bVarCore,
@@ -127,12 +53,30 @@ blake2_impl!(
"Blake2b instance with a fixed output.",
);
-/// BLAKE2b which allows to choose output size at runtime.
-pub type Blake2bVar = RtVariableCoreWrapper<Blake2bVarCore>;
-/// Core hasher state of BLAKE2b generic over output size.
-pub type Blake2bCore<OutSize> = CtVariableCoreWrapper<Blake2bVarCore, OutSize>;
-/// BLAKE2b generic over output size.
-pub type Blake2b<OutSize> = CoreWrapper<Blake2bCore<OutSize>>;
+digest::buffer_ct_variable!(
+ /// BLAKE2b generic over output size.
+ pub struct Blake2b<OutSize>(Blake2bVarCore);
+ exclude: SerializableState;
+ max_size: U64;
+);
+
+// TODO: impl in the macro
+impl<OutSize> CustomizedInit for Blake2b<OutSize>
+where
+ OutSize: ArraySize + IsLessOrEqual<U64, Output = True>,
+{
+ fn new_customized(customization: &[u8]) -> Self {
+ Self {
+ core: CustomizedInit::new_customized(customization),
+ buffer: Default::default(),
+ }
+ }
+}
+
+/// BLAKE2b-128 hasher state.
+pub type Blake2b128 = Blake2b<U16>;
+/// BLAKE2b-256 hasher state.
+pub type Blake2b256 = Blake2b<U32>;
/// BLAKE2b-512 hasher state.
pub type Blake2b512 = Blake2b<U64>;
@@ -157,12 +101,28 @@ blake2_impl!(
"Blake2s instance with a fixed output.",
);
-/// BLAKE2s which allows to choose output size at runtime.
-pub type Blake2sVar = RtVariableCoreWrapper<Blake2sVarCore>;
-/// Core hasher state of BLAKE2s generic over output size.
-pub type Blake2sCore<OutSize> = CtVariableCoreWrapper<Blake2sVarCore, OutSize>;
-/// BLAKE2s generic over output size.
-pub type Blake2s<OutSize> = CoreWrapper<Blake2sCore<OutSize>>;
+digest::buffer_ct_variable!(
+ /// BLAKE2s generic over output size.
+ pub struct Blake2s<OutSize>(Blake2sVarCore);
+ exclude: SerializableState;
+ max_size: U32;
+);
+
+// TODO: impl in the macro
+impl<OutSize> CustomizedInit for Blake2s<OutSize>
+where
+ OutSize: ArraySize + IsLessOrEqual<U32, Output = True>,
+{
+ fn new_customized(customization: &[u8]) -> Self {
+ Self {
+ core: CustomizedInit::new_customized(customization),
+ buffer: Default::default(),
+ }
+ }
+}
+
+/// BLAKE2s-128 hasher state.
+pub type Blake2s128 = Blake2s<U16>;
/// BLAKE2s-256 hasher state.
pub type Blake2s256 = Blake2s<U32>;
### external/vendor/blake2/src/macros.rs
@@ -44,8 +44,7 @@ macro_rules! blake2_impl {
// salt is two words long
if salt.len() < length {
- let mut padded_salt =
- GenericArray::<u8, <$bytes as Div<U4>>::Output>::default();
+ let mut padded_salt = Array::<u8, <$bytes as Div<U4>>::Output>::default();
for i in 0..salt.len() {
padded_salt[i] = salt[i];
}
@@ -63,8 +62,7 @@ macro_rules! blake2_impl {
// persona is also two words long
if persona.len() < length {
- let mut padded_persona =
- GenericArray::<u8, <$bytes as Div<U4>>::Output>::default();
+ let mut padded_persona = Array::<u8, <$bytes as Div<U4>>::Output>::default();
for i in 0..persona.len() {
padded_persona[i] = persona[i];
}
@@ -95,13 +93,14 @@ macro_rules! blake2_impl {
fn finalize_with_flag(
&mut self,
- final_block: &GenericArray<u8, $block_size>,
+ final_block: &Array<u8, $block_size>,
flag: $word,
out: &mut Output<Self>,
) {
self.compress(final_block, !0, flag);
- let buf = [self.h[0].to_le(), self.h[1].to_le()];
- out.copy_from_slice(buf.as_bytes())
+ let n = size_of::<$vec>();
+ out[..n].copy_from_slice(self.h[0].to_le().as_bytes());
+ out[n..].copy_from_slice(self.h[1].to_le().as_bytes());
}
fn compress(&mut self, block: &Block<Self>, f0: $word, f1: $word) {
@@ -224,7 +223,7 @@ macro_rules! blake2_impl {
) {
self.t += buffer.get_pos() as u64;
let block = buffer.pad_with_zeros();
- self.finalize_with_flag(block, 0, out);
+ self.finalize_with_flag(&block, 0, out);
}
}
@@ -248,6 +247,26 @@ macro_rules! blake2_impl {
f.write_str(concat!(stringify!($name), " { ... }"))
}
}
+
+ impl Drop for $name {
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ {
+ self.h.zeroize();
+ self.t.zeroize();
+ }
+ }
+ }
+
+ impl VariableOutputCoreCustomized for $name {
+ #[inline]
+ fn new_customized(customization: &[u8], output_size: usize) -> Self {
+ Self::new_with_params(&[], customization, 0, output_size)
+ }
+ }
+
+ #[cfg(feature = "zeroize")]
+ impl ZeroizeOnDrop for $name {}
};
}
@@ -259,66 +278,72 @@ macro_rules! blake2_mac_impl {
#[doc=$doc]
pub struct $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
core: $hash,
buffer: LazyBuffer<<$hash as BlockSizeUser>::BlockSize>,
#[cfg(feature = "reset")]
- key_block: Key<Self>,
+ key_block: Option<Key<Self>>,
_out: PhantomData<OutSize>,
}
impl<OutSize> $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
/// Create new instance using provided key, salt, and persona.
///
- /// Key length should not be bigger than block size, salt and persona
- /// length should not be bigger than quarter of block size. If any
- /// of those conditions is false the method will return an error.
+ /// Setting key to `None` indicates unkeyed usage.
+ ///
+ /// # Errors
+ ///
+ /// If key is `Some`, then its length should not be zero or bigger
+ /// than the block size. The salt and persona length should not be
+ /// bigger than quarter of block size. If any of those conditions is
+ /// false the method will return an error.
#[inline]
pub fn new_with_salt_and_personal(
- key: &[u8],
+ key: Option<&[u8]>,
salt: &[u8],
persona: &[u8],
) -> Result<Self, InvalidLength> {
- let kl = key.len();
+ let kl = key.map_or(0, |k| k.len());
let bs = <$hash as BlockSizeUser>::BlockSize::USIZE;
let qbs = bs / 4;
- if kl > bs || salt.len() > qbs || persona.len() > qbs {
+ if key.is_some() && kl == 0 || kl > bs || salt.len() > qbs || persona.len() > qbs {
return Err(InvalidLength);
}
- let mut padded_key = Block::<$hash>::default();
- padded_key[..kl].copy_from_slice(key);
+ let buffer = if let Some(k) = key {
+ let mut padded_key = Block::<$hash>::default();
+ padded_key[..kl].copy_from_slice(k);
+ LazyBuffer::new(&padded_key)
+ } else {
+ LazyBuffer::default()
+ };
Ok(Self {
- core: <$hash>::new_with_params(salt, persona, key.len(), OutSize::USIZE),
- buffer: LazyBuffer::new(&padded_key),
+ core: <$hash>::new_with_params(salt, persona, kl, OutSize::USIZE),
+ buffer,
#[cfg(feature = "reset")]
- key_block: {
+ key_block: key.map(|k| {
let mut t = Key::<Self>::default();
- t[..kl].copy_from_slice(key);
+ t[..kl].copy_from_slice(k);
t
- },
+ }),
_out: PhantomData,
})
}
}
impl<OutSize> KeySizeUser for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
type KeySize = $max_size;
}
impl<OutSize> KeyInit for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn new(key: &Key<Self>) -> Self {
@@ -340,7 +365,7 @@ macro_rules! blake2_mac_impl {
key_block: {
let mut t = Key::<Self>::default();
t[..kl].copy_from_slice(key);
- t
+ Some(t)
},
_out: PhantomData,
})
@@ -349,8 +374,7 @@ macro_rules! blake2_mac_impl {
impl<OutSize> Update for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn update(&mut self, input: &[u8]) {
@@ -361,16 +385,14 @@ macro_rules! blake2_mac_impl {
impl<OutSize> OutputSizeUser for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size> + 'static,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
type OutputSize = OutSize;
}
impl<OutSize> FixedOutput for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size> + 'static,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn finalize_into(mut self, out: &mut Output<Self>) {
@@ -384,23 +406,25 @@ macro_rules! blake2_mac_impl {
#[cfg(feature = "reset")]
impl<OutSize> Reset for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
fn reset(&mut self) {
self.core.reset();
- let kl = self.key_block.len();
- let mut padded_key = Block::<$hash>::default();
- padded_key[..kl].copy_from_slice(&self.key_block);
- self.buffer = LazyBuffer::new(&padded_key);
+ self.buffer = if let Some(k) = self.key_block {
+ let kl = k.len();
+ let mut padded_key = Block::<$hash>::default();
+ padded_key[..kl].copy_from_slice(&k);
+ LazyBuffer::new(&padded_key)
+ } else {
+ LazyBuffer::default()
+ }
}
}
#[cfg(feature = "reset")]
impl<OutSize> FixedOutputReset for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
#[inline]
fn finalize_into_reset(&mut self, out: &mut Output<Self>) {
@@ -412,21 +436,40 @@ macro_rules! blake2_mac_impl {
}
}
- impl<OutSize> MacMarker for $name<OutSize>
- where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ impl<OutSize> MacMarker for $name<OutSize> where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>
{
}
impl<OutSize> fmt::Debug for $name<OutSize>
where
- OutSize: ArrayLength<u8> + IsLessOrEqual<$max_size>,
- LeEq<OutSize, $max_size>: NonZero,
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}{} {{ ... }}", stringify!($name), OutSize::USIZE)
}
}
+
+ impl<OutSize> Drop for $name<OutSize>
+ where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>,
+ {
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ {
+ // `self.core` zeroized by its `Drop` impl
+ self.buffer.zeroize();
+ #[cfg(feature = "reset")]
+ if let Some(mut key_block) = self.key_block {
+ key_block.zeroize();
+ }
+ }
+ }
+ }
+ #[cfg(feature = "zeroize")]
+ impl<OutSize> ZeroizeOnDrop for $name<OutSize> where
+ OutSize: ArraySize + IsLessOrEqual<$max_size, Output = True>
+ {
+ }
};
}
### external/vendor/blake2/src/simd.rs
@@ -1,63 +1,46 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-mod simd_opt;
-mod simdint;
-mod simdop;
-mod simdty;
-
-pub use self::simdty::{u32x4, u64x4};
-
-pub trait Vector4<T>: Copy {
- fn gather(src: &[T], i0: usize, i1: usize, i2: usize, i3: usize) -> Self;
-
- #[allow(clippy::wrong_self_convention)]
- fn from_le(self) -> Self;
- fn to_le(self) -> Self;
-
- fn wrapping_add(self, rhs: Self) -> Self;
-
- fn rotate_right_const(self, n: u32) -> Self;
-
- fn shuffle_left_1(self) -> Self;
- fn shuffle_left_2(self) -> Self;
- fn shuffle_left_3(self) -> Self;
-
- #[inline(always)]
- fn shuffle_right_1(self) -> Self {
- self.shuffle_left_3()
- }
- #[inline(always)]
- fn shuffle_right_2(self) -> Self {
- self.shuffle_left_2()
- }
- #[inline(always)]
- fn shuffle_right_3(self) -> Self {
- self.shuffle_left_1()
- }
-}
+use core::ops::{Add, BitXor, Shl, Shr};
+
+#[cfg(feature = "zeroize")]
+use digest::zeroize::Zeroize;
macro_rules! impl_vector4 {
($vec:ident, $word:ident) => {
- impl Vector4<$word> for $vec {
+ #[derive(Clone, Copy, Debug)]
+ #[repr(C)]
+ pub(crate) struct $vec(
+ pub(crate) $word,
+ pub(crate) $word,
+ pub(crate) $word,
+ pub(crate) $word,
+ );
+
+ impl $vec {
+ #[inline(always)]
+ pub(crate) fn new(e0: $word, e1: $word, e2: $word, e3: $word) -> Self {
+ Self(e0, e1, e2, e3)
+ }
+
#[inline(always)]
- fn gather(src: &[$word], i0: usize, i1: usize, i2: usize, i3: usize) -> Self {
+ pub(crate) fn gather(
+ src: &[$word],
+ i0: usize,
+ i1: usize,
+ i2: usize,
+ i3: usize,
+ ) -> Self {
$vec::new(src[i0], src[i1], src[i2], src[i3])
}
#[cfg(target_endian = "little")]
#[inline(always)]
- fn from_le(self) -> Self {
+ #[allow(clippy::wrong_self_convention)]
+ pub(crate) fn from_le(self) -> Self {
self
}
#[cfg(not(target_endian = "little"))]
#[inline(always)]
- fn from_le(self) -> Self {
+ pub(crate) fn from_le(self) -> Self {
$vec::new(
$word::from_le(self.0),
$word::from_le(self.1),
@@ -68,13 +51,13 @@ macro_rules! impl_vector4 {
#[cfg(target_endian = "little")]
#[inline(always)]
- fn to_le(self) -> Self {
+ pub(crate) fn to_le(self) -> Self {
self
}
#[cfg(not(target_endian = "little"))]
#[inline(always)]
- fn to_le(self) -> Self {
+ pub(crate) fn to_le(self) -> Self {
$vec::new(
self.0.to_le(),
self.1.to_le(),
@@ -84,55 +67,118 @@ macro_rules! impl_vector4 {
}
#[inline(always)]
- fn wrapping_add(self, rhs: Self) -> Self {
+ pub(crate) fn wrapping_add(self, rhs: Self) -> Self {
self + rhs
}
#[inline(always)]
- fn rotate_right_const(self, n: u32) -> Self {
- simd_opt::$vec::rotate_right_const(self, n)
+ pub(crate) fn rotate_right_const(self, n: u32) -> Self {
+ $vec::new(
+ self.0.rotate_right(n),
+ self.1.rotate_right(n),
+ self.2.rotate_right(n),
+ self.3.rotate_right(n),
+ )
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_1(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [1, 2, 3, 0];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn shuffle_left_1(self) -> Self {
+ $vec::new(self.1, self.2, self.3, self.0)
}
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_1(self) -> Self {
- $vec::new(self.1, self.2, self.3, self.0)
+ pub(crate) fn shuffle_left_2(self) -> Self {
+ $vec::new(self.2, self.3, self.0, self.1)
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_2(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [2, 3, 0, 1];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn shuffle_left_3(self) -> Self {
+ $vec::new(self.3, self.0, self.1, self.2)
}
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_2(self) -> Self {
- $vec::new(self.2, self.3, self.0, self.1)
+ pub(crate) fn shuffle_right_1(self) -> Self {
+ self.shuffle_left_3()
+ }
+ #[inline(always)]
+ pub(crate) fn shuffle_right_2(self) -> Self {
+ self.shuffle_left_2()
+ }
+ #[inline(always)]
+ pub(crate) fn shuffle_right_3(self) -> Self {
+ self.shuffle_left_1()
}
- #[cfg(feature = "simd")]
#[inline(always)]
- fn shuffle_left_3(self) -> Self {
- use crate::simd::simdint::simd_shuffle4;
- const IDX: [u32; 4] = [3, 0, 1, 2];
- unsafe { simd_shuffle4(self, self, IDX) }
+ pub(crate) fn as_bytes(&self) -> &[u8] {
+ let p = self as *const Self as *const u8;
+ unsafe { core::slice::from_raw_parts(p, core::mem::size_of::<Self>()) }
}
+ }
+
+ impl Add for $vec {
+ type Output = Self;
- #[cfg(not(feature = "simd"))]
#[inline(always)]
- fn shuffle_left_3(self) -> Self {
- $vec::new(self.3, self.0, self.1, self.2)
+ fn add(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0.wrapping_add(rhs.0),
+ self.1.wrapping_add(rhs.1),
+ self.2.wrapping_add(rhs.2),
+ self.3.wrapping_add(rhs.3),
+ )
+ }
+ }
+
+ impl BitXor for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn bitxor(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 ^ rhs.0,
+ self.1 ^ rhs.1,
+ self.2 ^ rhs.2,
+ self.3 ^ rhs.3,
+ )
+ }
+ }
+
+ impl Shl<$vec> for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn shl(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 << rhs.0,
+ self.1 << rhs.1,
+ self.2 << rhs.2,
+ self.3 << rhs.3,
+ )
+ }
+ }
+
+ impl Shr<$vec> for $vec {
+ type Output = Self;
+
+ #[inline(always)]
+ fn shr(self, rhs: Self) -> Self::Output {
+ $vec::new(
+ self.0 >> rhs.0,
+ self.1 >> rhs.1,
+ self.2 >> rhs.2,
+ self.3 >> rhs.3,
+ )
+ }
+ }
+
+ #[cfg(feature = "zeroize")]
+ impl Zeroize for $vec {
+ fn zeroize(&mut self) {
+ self.0.zeroize();
+ self.1.zeroize();
+ self.2.zeroize();
+ self.3.zeroize();
}
}
};
### external/vendor/blake2/src/simd/simd_opt.rs
@@ -1,52 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#[allow(unused_macros)]
-#[cfg(feature = "simd")]
-macro_rules! transmute_shuffle {
- ($tmp:ident, $shuffle:ident, $vec:expr, $idx_n:expr, $idx:expr) => {
- unsafe {
- use crate::simd::simdint::$shuffle;
- use crate::simd::simdty::$tmp;
- use core::mem::transmute;
-
- const IDX: [u32; $idx_n] = $idx;
- let tmp_i: $tmp = transmute($vec);
- let tmp_o: $tmp = $shuffle(tmp_i, tmp_i, IDX);
- transmute(tmp_o)
- }
- };
-}
-
-#[cfg(feature = "simd")]
-pub mod u32x4;
-#[cfg(feature = "simd")]
-pub mod u64x4;
-
-#[cfg(not(feature = "simd"))]
-macro_rules! simd_opt {
- ($vec:ident) => {
- pub mod $vec {
- use crate::simd::simdty::$vec;
-
- #[inline(always)]
- pub fn rotate_right_const(vec: $vec, n: u32) -> $vec {
- $vec::new(
- vec.0.rotate_right(n),
- vec.1.rotate_right(n),
- vec.2.rotate_right(n),
- vec.3.rotate_right(n),
- )
- }
- }
- };
-}
-
-#[cfg(not(feature = "simd"))]
-simd_opt!(u32x4);
-#[cfg(not(feature = "simd"))]
-simd_opt!(u64x4);
### external/vendor/blake2/src/simd/simd_opt/u32x4.rs
@@ -1,69 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use crate::simd::simdty::u32x4;
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
- match n {
- 16 => rotate_right_16(vec),
- 8 => rotate_right_8(vec),
- _ => rotate_right_any(vec, n),
- }
-}
-
-#[cfg(not(feature = "simd_opt"))]
-#[inline(always)]
-pub fn rotate_right_const(vec: u32x4, n: u32) -> u32x4 {
- rotate_right_any(vec, n)
-}
-
-#[inline(always)]
-fn rotate_right_any(vec: u32x4, n: u32) -> u32x4 {
- let r = n as u32;
- let l = 32 - r;
-
- (vec >> u32x4::new(r, r, r, r)) ^ (vec << u32x4::new(l, l, l, l))
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_16(vec: u32x4) -> u32x4 {
- if cfg!(target_feature = "ssse3") {
- // pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x16,
- simd_shuffle16,
- vec,
- 16,
- [2, 3, 0, 1, 6, 7, 4, 5, 10, 11, 8, 9, 14, 15, 12, 13]
- )
- } else if cfg!(any(target_feature = "sse2", target_feature = "neon")) {
- // pshuflw+pshufhw (SSE2) / vrev (NEON)
- transmute_shuffle!(u16x8, simd_shuffle8, vec, 8, [1, 0, 3, 2, 5, 4, 7, 6])
- } else {
- rotate_right_any(vec, 16)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_8(vec: u32x4) -> u32x4 {
- if cfg!(target_feature = "ssse3") {
- // pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x16,
- simd_shuffle16,
- vec,
- 16,
- [1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]
- )
- } else {
- rotate_right_any(vec, 8)
- }
-}
### external/vendor/blake2/src/simd/simd_opt/u64x4.rs
@@ -1,143 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-use crate::simd::simdty::u64x4;
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 {
- match n {
- 32 => rotate_right_32(vec),
- 24 => rotate_right_24(vec),
- 16 => rotate_right_16(vec),
- _ => rotate_right_any(vec, n),
- }
-}
-
-#[cfg(not(feature = "simd_opt"))]
-#[inline(always)]
-pub fn rotate_right_const(vec: u64x4, n: u32) -> u64x4 {
- rotate_right_any(vec, n)
-}
-
-#[inline(always)]
-fn rotate_right_any(vec: u64x4, n: u32) -> u64x4 {
- let r = n as u64;
- let l = 64 - r;
-
- (vec >> u64x4::new(r, r, r, r)) ^ (vec << u64x4::new(l, l, l, l))
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_32(vec: u64x4) -> u64x4 {
- if cfg!(any(target_feature = "sse2", target_feature = "neon")) {
- // 2 x pshufd (SSE2) / vpshufd (AVX2) / 2 x vrev (NEON)
- transmute_shuffle!(u32x8, simd_shuffle8, vec, 8, [1, 0, 3, 2, 5, 4, 7, 6])
- } else {
- rotate_right_any(vec, 32)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_24(vec: u64x4) -> u64x4 {
- if cfg!(all(
- feature = "simd_asm",
- target_feature = "neon",
- target_arch = "arm"
- )) {
- // 4 x vext (NEON)
- rotate_right_vext(vec, 3)
- } else if cfg!(target_feature = "ssse3") {
- // 2 x pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x32,
- simd_shuffle32,
- vec,
- 32,
- [
- 3, 4, 5, 6, 7, 0, 1, 2, 11, 12, 13, 14, 15, 8, 9, 10, 19, 20, 21, 22, 23, 16, 17,
- 18, 27, 28, 29, 30, 31, 24, 25, 26
- ]
- )
- } else {
- rotate_right_any(vec, 24)
- }
-}
-
-#[cfg(feature = "simd_opt")]
-#[inline(always)]
-fn rotate_right_16(vec: u64x4) -> u64x4 {
- if cfg!(all(
- feature = "simd_asm",
- target_feature = "neon",
- target_arch = "arm"
- )) {
- // 4 x vext (NEON)
- rotate_right_vext(vec, 2)
- } else if cfg!(target_feature = "ssse3") {
- // 2 x pshufb (SSSE3) / vpshufb (AVX2)
- transmute_shuffle!(
- u8x32,
- simd_shuffle32,
- vec,
- 32,
- [
- 2, 3, 4, 5, 6, 7, 0, 1, 10, 11, 12, 13, 14, 15, 8, 9, 18, 19, 20, 21, 22, 23, 16,
- 17, 26, 27, 28, 29, 30, 31, 24, 25
- ]
- )
- } else if cfg!(target_feature = "sse2") {
- // 2 x pshuflw+pshufhw (SSE2)
- transmute_shuffle!(
- u16x16,
- simd_shuffle16,
- vec,
- 16,
- [1, 2, 3, 0, 5, 6, 7, 4, 9, 10, 11, 8, 13, 14, 15, 12]
- )
- } else {
- rotate_right_any(vec, 16)
- }
-}
-
-#[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))]
-mod simd_asm_neon_arm {
- use crate::simd::simdty::{u64x2, u64x4};
-
- #[inline(always)]
- fn vext_u64(vec: u64x2, b: u8) -> u64x2 {
- unsafe {
- let result: u64x2;
- asm!("vext.8 ${0:e}, ${1:e}, ${1:e}, $2\nvext.8 ${0:f}, ${1:f}, ${1:f}, $2"
- : "=w" (result)
- : "w" (vec), "n" (b));
- result
- }
- }
-
- #[inline(always)]
- pub fn rotate_right_vext(vec: u64x4, b: u8) -> u64x4 {
- use crate::simd::simdint::{simd_shuffle2, simd_shuffle4};
-
- unsafe {
- let tmp0 = vext_u64(simd_shuffle2(vec, vec, [0, 1]), b);
- let tmp1 = vext_u64(simd_shuffle2(vec, vec, [2, 3]), b);
- simd_shuffle4(tmp0, tmp1, [0, 1, 2, 3])
- }
- }
-}
-
-#[cfg(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm"))]
-use self::simd_asm_neon_arm::rotate_right_vext;
-
-#[cfg(feature = "simd_opt")]
-#[cfg(not(all(feature = "simd_asm", target_feature = "neon", target_arch = "arm")))]
-fn rotate_right_vext(_vec: u64x4, _n: u8) -> u64x4 {
- unreachable!()
-}
### external/vendor/blake2/src/simd/simdint.rs
@@ -1,22 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#![allow(dead_code)]
-
-#[cfg(feature = "simd")]
-extern "platform-intrinsic" {
- pub fn simd_add<T>(x: T, y: T) -> T;
- pub fn simd_shl<T>(x: T, y: T) -> T;
- pub fn simd_shr<T>(x: T, y: T) -> T;
- pub fn simd_xor<T>(x: T, y: T) -> T;
-
- pub fn simd_shuffle2<T, U>(v: T, w: T, idx: [u32; 2]) -> U;
- pub fn simd_shuffle4<T, U>(v: T, w: T, idx: [u32; 4]) -> U;
- pub fn simd_shuffle8<T, U>(v: T, w: T, idx: [u32; 8]) -> U;
- pub fn simd_shuffle16<T, U>(v: T, w: T, idx: [u32; 16]) -> U;
- pub fn simd_shuffle32<T, U>(v: T, w: T, idx: [u32; 32]) -> U;
-}
### external/vendor/blake2/src/simd/simdop.rs
@@ -1,103 +0,0 @@
-// Copyright 2015 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#[cfg(feature = "simd")]
-use crate::simd::simdint;
-use crate::simd::simdty::{u32x4, u64x4};
-
-use core::ops::{Add, BitXor, Shl, Shr};
-
-macro_rules! impl_ops {
- ($vec:ident) => {
- impl Add for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn add(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_add(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn add(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0.wrapping_add(rhs.0),
- self.1.wrapping_add(rhs.1),
- self.2.wrapping_add(rhs.2),
- self.3.wrapping_add(rhs.3),
- )
- }
- }
-
- impl BitXor for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn bitxor(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_xor(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn bitxor(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 ^ rhs.0,
- self.1 ^ rhs.1,
- self.2 ^ rhs.2,
- self.3 ^ rhs.3,
- )
- }
- }
-
- impl Shl<$vec> for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn shl(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_shl(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn shl(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 << rhs.0,
- self.1 << rhs.1,
- self.2 << rhs.2,
- self.3 << rhs.3,
- )
- }
- }
-
- impl Shr<$vec> for $vec {
- type Output = Self;
-
- #[cfg(feature = "simd")]
- #[inline(always)]
- fn shr(self, rhs: Self) -> Self::Output {
- unsafe { simdint::simd_shr(self, rhs) }
- }
-
- #[cfg(not(feature = "simd"))]
- #[inline(always)]
- fn shr(self, rhs: Self) -> Self::Output {
- $vec::new(
- self.0 >> rhs.0,
- self.1 >> rhs.1,
- self.2 >> rhs.2,
- self.3 >> rhs.3,
- )
- }
- }
- };
-}
-
-impl_ops!(u32x4);
-impl_ops!(u64x4);
### external/vendor/blake2/src/simd/simdty.rs
@@ -1,77 +0,0 @@
-// Copyright 2016 blake2-rfc Developers
-//
-// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or
-// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or
-// http://opensource.org/licenses/MIT>, at your option. This file may not be
-// copied, modified, or distributed except according to those terms.
-
-#![allow(dead_code, non_camel_case_types)]
-
-use crate::as_bytes::Safe;
-
-#[cfg(feature = "simd")]
-macro_rules! decl_simd {
- ($($decl:item)*) => {
- $(
- #[derive(Clone, Copy, Debug)]
- #[repr(simd)]
- $decl
- )*
- }
-}
-
-#[cfg(not(feature = "simd"))]
-macro_rules! decl_simd {
- ($($decl:item)*) => {
- $(
- #[derive(Clone, Copy, Debug)]
- #[repr(C)]
- $decl
- )*
- }
-}
-
-decl_simd! {
- pub struct Simd2<T>(pub T, pub T);
- pub struct Simd4<T>(pub T, pub T, pub T, pub T);
- pub struct Simd8<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
- pub struct Simd16<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
- pub struct Simd32<T>(pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T,
- pub T, pub T, pub T, pub T);
-}
-
-pub type u64x2 = Simd2<u64>;
-
-pub type u32x4 = Simd4<u32>;
-pub type u64x4 = Simd4<u64>;
-
-pub type u16x8 = Simd8<u16>;
-pub type u32x8 = Simd8<u32>;
-
-pub type u8x16 = Simd16<u8>;
-pub type u16x16 = Simd16<u16>;
-
-pub type u8x32 = Simd32<u8>;
-
-impl<T> Simd4<T> {
- #[inline(always)]
- pub fn new(e0: T, e1: T, e2: T, e3: T) -> Simd4<T> {
- Simd4(e0, e1, e2, e3)
- }
-}
-
-unsafe impl<T: Safe> Safe for Simd2<T> {}
-unsafe impl<T: Safe> Safe for Simd4<T> {}
-unsafe impl<T: Safe> Safe for Simd8<T> {}
-unsafe impl<T: Safe> Safe for Simd16<T> {}
-unsafe impl<T: Safe> Safe for Simd32<T> {}
### external/vendor/blake2/tests/data/blake2b/fixed.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b/variable.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_mac_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2b_variable_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s/variable.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s_mac_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/data/blake2s_variable_kat.blb
[binary or diff unavailable]
### external/vendor/blake2/tests/mac.rs
@@ -1,22 +1,24 @@
#[cfg(not(feature = "reset"))]
-use digest::new_mac_test as new_test;
+use digest::dev::mac_test as test_fn;
#[cfg(feature = "reset")]
-use digest::new_resettable_mac_test as new_test;
+use digest::dev::reset_mac_test as test_fn;
-new_test!(blake2b_mac, "blake2b/mac", blake2::Blake2bMac512);
-new_test!(blake2s_mac, "blake2s/mac", blake2::Blake2sMac256);
+use digest::new_mac_test;
+
+new_mac_test!(blake2b_mac_kat, blake2::Blake2bMac512, test_fn);
+new_mac_test!(blake2s_mac_kat, blake2::Blake2sMac256, test_fn);
#[test]
fn blake2b_new_test() {
- use blake2::digest::{generic_array::GenericArray, KeyInit, Mac};
+ use blake2::digest::{KeyInit, Mac, array::Array};
fn run<T: Mac + KeyInit>(key: &[u8]) {
const DATA: &[u8] = &[42; 300];
- let res1 = <T as Mac>::new(GenericArray::from_slice(key))
+ let res1 = T::new(&Array::try_from(key).unwrap())
.chain_update(DATA)
.finalize()
.into_bytes();
- let res2 = <T as Mac>::new_from_slice(&key)
+ let res2 = T::new_from_slice(key)
.unwrap()
.chain_update(DATA)
.finalize()
@@ -27,3 +29,13 @@ fn blake2b_new_test() {
run::<blake2::Blake2sMac256>(&[0x42; 32]);
run::<blake2::Blake2bMac512>(&[0x42; 64]);
}
+
+#[test]
+fn mac_refuses_empty_keys() {
+ assert!(
+ blake2::Blake2bMac512::new_with_salt_and_personal(Some(&[]), b"salt", b"persona").is_err()
+ );
+ assert!(
+ blake2::Blake2sMac256::new_with_salt_and_personal(Some(&[]), b"salt", b"persona").is_err()
+ );
+}
### external/vendor/blake2/tests/mod.rs
@@ -1,19 +1,7 @@
#[cfg(feature = "reset")]
-use digest::dev::{fixed_reset_test as fixed_fn, variable_reset_test as varaible_fn};
+use digest::dev::fixed_reset_test as fixed_test;
#[cfg(not(feature = "reset"))]
-use digest::dev::{fixed_test as fixed_fn, variable_test as varaible_fn};
+use digest::dev::fixed_test;
use digest::new_test;
-new_test!(blake2b_fixed, "blake2b/fixed", blake2::Blake2b512, fixed_fn,);
-new_test!(
- blake2b_variable,
- "blake2b/variable",
- blake2::Blake2bVar,
- varaible_fn,
-);
-new_test!(
- blake2s_variable,
- "blake2s/variable",
- blake2::Blake2sVar,
- varaible_fn,
-);
+new_test!(blake2b_kat, blake2::Blake2b512, fixed_test);
### external/vendor/blake2/tests/persona.rs
@@ -1,40 +1,51 @@
-use blake2::{digest::FixedOutput, Blake2bMac512, Blake2sMac256};
+use blake2::digest::CustomizedInit;
+use blake2::{Blake2b128, Blake2bMac512, Blake2sMac256, digest::FixedOutput};
+use digest::Update;
use hex_literal::hex;
#[test]
-#[rustfmt::skip]
fn blake2s_persona() {
- let key= hex!("
- 000102030405060708090a0b0c0d0e0f
- 101112131415161718191a1b1c1d1e1f
- ");
+ let key = hex!(
+ "000102030405060708090a0b0c0d0e0f"
+ "101112131415161718191a1b1c1d1e1f"
+ );
let persona = b"personal";
- let ctx = Blake2sMac256::new_with_salt_and_personal(&key, &[], persona).unwrap();
+ let ctx = Blake2sMac256::new_with_salt_and_personal(Some(&key), &[], persona).unwrap();
assert_eq!(
- ctx.finalize_fixed()[..],
- hex!("
- 25a4ee63b594aed3f88a971e1877ef70
- 99534f9097291f88fb86c79b5e70d022
- ")[..],
+ ctx.finalize_fixed(),
+ hex!(
+ "25a4ee63b594aed3f88a971e1877ef70"
+ "99534f9097291f88fb86c79b5e70d022"
+ ),
);
}
#[test]
-#[rustfmt::skip]
fn blake2b_persona() {
- let key = hex!("
- 000102030405060708090a0b0c0d0e0f
- 101112131415161718191a1b1c1d1e1f
- ");
let persona = b"personal";
- let ctx = Blake2bMac512::new_with_salt_and_personal(&key, &[], persona).unwrap();
+ let mut ctx = Blake2b128::new_customized(persona);
+ ctx.update(b"hello");
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!("5a5eb0aecc053af1ce6de25354c1c761"),
+ );
+}
+
+#[test]
+fn blake2b_mac_persona() {
+ let key = hex!(
+ "000102030405060708090a0b0c0d0e0f"
+ "101112131415161718191a1b1c1d1e1f"
+ );
+ let persona = b"personal";
+ let ctx = Blake2bMac512::new_with_salt_and_personal(Some(&key), &[], persona).unwrap();
assert_eq!(
- ctx.finalize_fixed()[..],
- hex!("
- 03de3b295dcfc3b25b05abb09bc95fe3
- e9ff3073638badc68101d1e42019d077
- 1dd07525a3aae8318e92c5e5d967ba92
- e4810d0021d7bf3b49da0b4b4a8a4e1f
- ")[..],
+ ctx.finalize_fixed(),
+ hex!(
+ "03de3b295dcfc3b25b05abb09bc95fe3"
+ "e9ff3073638badc68101d1e42019d077"
+ "1dd07525a3aae8318e92c5e5d967ba92"
+ "e4810d0021d7bf3b49da0b4b4a8a4e1f"
+ ),
);
}
### external/vendor/blake2/tests/unkeyed.rs
@@ -0,0 +1,28 @@
+use blake2::{Blake2bMac512, Blake2sMac256, digest::FixedOutput};
+use hex_literal::hex;
+
+#[test]
+fn blake2s_unkeyed() {
+ let ctx = Blake2sMac256::new_with_salt_and_personal(None, b"salt", b"persona").unwrap();
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!(
+ "d7de83e2b1fedd9755db747235b7ba4b"
+ "f9773a16b91c6b241e4b1d926160d9eb"
+ ),
+ );
+}
+
+#[test]
+fn blake2b_unkeyed() {
+ let ctx = Blake2bMac512::new_with_salt_and_personal(None, b"salt", b"persona").unwrap();
+ assert_eq!(
+ ctx.finalize_fixed(),
+ hex!(
+ "fa3cd38902ae0602d8f0066f18c579fa"
+ "e8068074fbe91f9f5774f841f5ab51fe"
+ "39140ad78d6576f8a0b9f8f4c2642211"
+ "11c9911d8ba1dbefcd034acdbedb8cde"
+ ),
+ );
+}
### external/vendor/block-buffer/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"ff7b73e928510ade7bc98871aaae74feb00659d74def593c837ce19caa611661","CHANGELOG.md":"3876f3ab367ed87a7f7503c88974f6fd093110bf0a789045311a0add637d26ad","Cargo.toml":"962dea1846765a31fc94d41855ff83811ffdf63b581c4b5e66f115178a41db4f","Cargo.toml.orig":"59ab4cd406fb1bac488c873ca65628fbed0a18559fdd6dd7396a81a5a5ab22d8","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"d5c22aa3118d240e877ad41c5d9fa232f9c77d757d4aac0c2f943afc0a95e0ef","README.md":"9bf3545872bdad2fb41557be5cefc21a48f0c7804f8124e24b67760429036472","src/lib.rs":"0d03d0cff909f4dc6ba6899e7ac8c02f408213fdc9e8347a5147e1c88da18c98","src/sealed.rs":"65afa9015a3ddb8d1a56733ef3103b1459842f69155f00cefdb235dc73255d4e","tests/mod.rs":"a42403629557eea432a8797f2d81a4ab65de15ce9a2db933496c53f05669e1d7"},"package":"69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"50b907904eaa909701b4edd0778bd5db559eb2daae0f556c1d88ba7b1c632527","CHANGELOG.md":"d91f98ee0ff8d181f721ff2e50a14f45866853cbc5e33a399eb0b6dde6b127c3","Cargo.lock":"0d1213da8127e64c4a43264120140d5062b3a8da271a236a3f6ff5ff53ba776c","Cargo.toml":"f21191120ab1d04327657b7125f25b0e3f2bce34af5e921d3c66d24de11d5e60","Cargo.toml.orig":"6ccb29916ec67b7d6e3a86203a8296795e8f3e25ae94a307ede8fdc79f07aee1","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"98181e7249d0c01737645ec982499ce99a0f07eb8f7d625b8840d799d10dbc01","README.md":"745dfdacff2e7ed7321d5f859a7072dbac37675ca0d94554ee7ec6045e9b8ea7","src/lib.rs":"1e1f665e68a16b6a18ea547aec36d9855163bd79a27c2b293a7a7708dde68a28","src/read.rs":"790b7bc1d6e87c0ee797b41e18aa3c394aa561c3074047c72590b33c9cee0f8d","src/sealed.rs":"7ad84c528060c27e148e568dc4934ab7704259bdf0c41f1ab59043255d53da3f","tests/mod.rs":"543dab1816c288334cca9b9d61dbe89ee1b4862c15fee5fb028ad5c6bb4fa60f"},"package":"d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"}
\ No newline at end of file
### external/vendor/block-buffer/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "02a49a322dbadb27dc6c155f979ea7a1018ae9e4"
+ "sha1": "cbd0963c685df025c42bed31f78c50d1bada3805"
},
"path_in_vcs": "block-buffer"
}
\ No newline at end of file
### external/vendor/block-buffer/CHANGELOG.md
@@ -4,6 +4,46 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.12.1 (2026-06-11)
+### Fixed
+- Exception safety bug ([#1487])
+
+[#1487]: https://github.com/RustCrypto/utils/pull/1487
+
+## 0.12.0 (2026-02-24)
+### Added
+- `BlockSizes` trait implemented for sizes bigger than `U0` and smaller than `U256` ([#1455])
+
+### Changed
+- Block sizes used by `BlockBuffer` and `ReadBuffer` are now bound by `BlockSizes` ([#1455])
+
+[#1455]: https://github.com/RustCrypto/utils/pull/1455
+
+## 0.11.0 (2025-11-07)
+### Added
+- `ReadBuffer` type ([#823])
+- Optional implementation of the `Zeroize` trait ([#963])
+- Generic `serialize` and `deserialize` methods ([#1200])
+- `ReadBuffer::{read_cached, write_block, reset}` methods ([#1201])
+
+### Changed
+- Block sizes must be bigger than 0 and smaller than 256.
+ This is enforced using compile-time monomorphization errors. ([#1115])
+- Size of `EagerBuffer` is equal to buffer size, while previously it was equal
+ to buffer size plus one byte ([#823])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1149])
+
+### Removed
+- `EagerBuffer::set_data` method. Use the `ReadBuffer` type instead. ([#823])
+
+[#823]: https://github.com/RustCrypto/utils/pull/823
+[#963]: https://github.com/RustCrypto/utils/pull/963
+[#1115]: https://github.com/RustCrypto/utils/pull/1115
+[#1115]: https://github.com/RustCrypto/utils/pull/1116
+[#1149]: https://github.com/RustCrypto/utils/pull/1149
+[#1200]: https://github.com/RustCrypto/utils/pull/1200
+[#1201]: https://github.com/RustCrypto/utils/pull/1201
+
## 0.10.3 (2022-09-04)
### Added
- `try_new` method ([#799])
### external/vendor/block-buffer/Cargo.lock
@@ -0,0 +1,39 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+dependencies = [
+ "hex-literal",
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
### external/vendor/block-buffer/Cargo.toml
@@ -10,11 +10,18 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2018"
+edition = "2024"
+rust-version = "1.85"
name = "block-buffer"
-version = "0.10.3"
+version = "0.12.1"
authors = ["RustCrypto Developers"]
-description = "Buffer type for block processing of data"
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Buffer types for block processing of data"
documentation = "https://docs.rs/block-buffer"
readme = "README.md"
keywords = [
@@ -28,5 +35,61 @@ categories = [
license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/utils"
-[dependencies.generic-array]
-version = "0.14"
+[lib]
+name = "block_buffer"
+path = "src/lib.rs"
+
+[[test]]
+name = "mod"
+path = "tests/mod.rs"
+
+[dependencies.hybrid-array]
+version = "0.4"
+
+[dependencies.zeroize]
+version = "1.8"
+optional = true
+default-features = false
+
+[dev-dependencies.hex-literal]
+version = "1"
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+doc_markdown = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/block-buffer/Cargo.toml.orig
@@ -1,15 +1,23 @@
[package]
name = "block-buffer"
-version = "0.10.3"
+version = "0.12.1"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-description = "Buffer type for block processing of data"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/block-buffer"
+readme = "README.md"
repository = "https://github.com/RustCrypto/utils"
+license = "MIT OR Apache-2.0"
keywords = ["block", "buffer"]
categories = ["cryptography", "no-std"]
-edition = "2018"
-readme = "README.md"
+description = "Buffer types for block processing of data"
[dependencies]
-generic-array = "0.14"
+hybrid-array = "0.4"
+zeroize = { version = "1.8", optional = true, default-features = false }
+
+[dev-dependencies]
+hex-literal = "1"
+
+[lints]
+workspace = true
### external/vendor/block-buffer/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2018-2019 The RustCrypto Project Developers
+Copyright (c) 2018-2025 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/block-buffer/README.md
@@ -2,10 +2,10 @@
[![crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
Buffer type for block processing of data with minimized amount of unreachable panics.
@@ -29,11 +29,11 @@ Unless you explicitly state otherwise, any contribution intentionally submitted
[docs-image]: https://docs.rs/block-buffer/badge.svg
[docs-link]: https://docs.rs/block-buffer/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260052-utils
-[build-image]: https://github.com/RustCrypto/utils/workflows/block-buffer/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml
+[build-image]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/utils/actions/workflows/block-buffer.yml?query=branch:master
[//]: # (general links)
### external/vendor/block-buffer/src/lib.rs
@@ -1,23 +1,62 @@
//! Fixed size buffer for block processing of data.
+//!
+//! # Examples
+//! ```
+//! use block_buffer::{EagerBuffer, array::typenum::U4};
+//!
+//! let mut buf = EagerBuffer::<U4>::default();
+//!
+//! let mut accum = Vec::new();
+//! let msg1: &[u8] = &[0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
+//! let msg2: &[u8] = &[10, 11, 12];
+//!
+//! buf.digest_blocks(msg1, |blocks| accum.extend_from_slice(blocks));
+//! buf.digest_blocks(msg2, |blocks| accum.extend_from_slice(blocks));
+//!
+//! assert_eq!(accum.len(), 3);
+//! assert_eq!(accum[0], [0, 1, 2, 3]);
+//! assert_eq!(accum[1], [4, 5, 6, 7]);
+//! assert_eq!(accum[2], [8, 9, 10, 11]);
+//!
+//! let padded_block = buf.pad_with_zeros();
+//! assert_eq!(padded_block, [12, 0, 0, 0]);
+//! ```
+//!
+//! Note that block size used with buffers MUST be bigger than zero and smaller than 256.
+//! You will get a compilation error with an invalid block size:
+//!
+//! ```compile_fail
+//! use block_buffer::{EagerBuffer, array::typenum::U0};
+//! let buf = EagerBuffer::<U0>::default();
+//! ```
+//! ```compile_fail
+//! use block_buffer::{EagerBuffer, array::typenum::U256};
+//! let buf = EagerBuffer::<U256>::default();
+//! ```
#![no_std]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/6ee8e381/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
+#![allow(clippy::undocumented_unsafe_blocks)] // TODO(tarcieri): document all unsafe blocks
-pub use generic_array;
+pub use hybrid_array as array;
-use core::{fmt, marker::PhantomData, slice};
-use generic_array::{
- typenum::{IsLess, Le, NonZero, U256},
- ArrayLength, GenericArray,
-};
+use array::{Array, ArraySize, typenum::Sum};
+use core::{fmt, mem::MaybeUninit, ptr, slice};
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
+
+mod read;
mod sealed;
-/// Block on which `BlockBuffer` operates.
-pub type Block<BlockSize> = GenericArray<u8, BlockSize>;
+pub use read::ReadBuffer;
+
+/// Trait implemented for supported block sizes, i.e. for types from `U1` to `U255`.
+pub trait BlockSizes: ArraySize + sealed::BlockSizes {}
+
+impl<T: ArraySize + sealed::BlockSizes> BlockSizes for T {}
/// Trait for buffer kinds.
pub trait BufferKind: sealed::Sealed {}
@@ -33,6 +72,7 @@ pub struct Eager {}
pub struct Lazy {}
impl BufferKind for Eager {}
+
impl BufferKind for Lazy {}
/// Eager block buffer.
@@ -51,89 +91,73 @@ impl fmt::Display for Error {
}
/// Buffer for block processing of data.
-#[derive(Debug)]
-pub struct BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
- buffer: Block<BlockSize>,
- pos: u8,
- _pd: PhantomData<Kind>,
+pub struct BlockBuffer<BS: BlockSizes, K: BufferKind> {
+ buffer: MaybeUninit<Array<u8, BS>>,
+ pos: K::Pos,
}
-impl<BlockSize, Kind> Default for BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> Default for BlockBuffer<BS, K> {
+ #[inline]
fn default() -> Self {
- Self {
- buffer: Default::default(),
- pos: 0,
- _pd: PhantomData,
- }
+ let mut buffer = MaybeUninit::uninit();
+ let mut pos = Default::default();
+ K::set_pos(&mut buffer, &mut pos, 0);
+ Self { buffer, pos }
}
}
-impl<BlockSize, Kind> Clone for BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> Clone for BlockBuffer<BS, K> {
+ #[inline]
fn clone(&self) -> Self {
- Self {
- buffer: self.buffer.clone(),
- pos: self.pos,
- _pd: PhantomData,
- }
+ // SAFETY: `BlockBuffer` does not implement `Drop` (i.e. it could be a `Copy` type),
+ // so we can safely clone it using `ptr::read`.
+ unsafe { ptr::read(self) }
}
}
-impl<BlockSize, Kind> BlockBuffer<BlockSize, Kind>
-where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
- Kind: BufferKind,
-{
+impl<BS: BlockSizes, K: BufferKind> fmt::Debug for BlockBuffer<BS, K> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
+ f.debug_struct(K::NAME)
+ .field("pos", &self.get_pos())
+ .field("block_size", &BS::USIZE)
+ .field("data", &self.get_data())
+ .finish()
+ }
+}
+
+impl<BS: BlockSizes, K: BufferKind> BlockBuffer<BS, K> {
/// Create new buffer from slice.
///
/// # Panics
/// If slice length is not valid for used buffer kind.
#[inline(always)]
+ #[must_use]
+ #[track_caller]
pub fn new(buf: &[u8]) -> Self {
- Self::try_new(buf).unwrap()
+ Self::try_new(buf).expect("invalid slice length for buffer kind")
}
/// Create new buffer from slice.
///
- /// Returns an error if slice length is not valid for used buffer kind.
+ /// # Errors
+ /// If slice length is not valid for used buffer kind.
#[inline(always)]
pub fn try_new(buf: &[u8]) -> Result<Self, Error> {
- let pos = buf.len();
- if !Kind::invariant(pos, BlockSize::USIZE) {
+ if !K::invariant(buf.len(), BS::USIZE) {
return Err(Error);
}
- let mut buffer = Block::<BlockSize>::default();
- buffer[..pos].copy_from_slice(buf);
- Ok(Self {
- buffer,
- pos: pos as u8,
- _pd: PhantomData,
- })
+ let mut res = Self::default();
+ // SAFETY: we have checked that buffer length satisfies the buffer kind invariant
+ unsafe {
+ res.set_data_unchecked(buf);
+ }
+ Ok(res)
}
/// Digest data in `input` in blocks of size `BlockSize` using
/// the `compress` function, which accepts slice of blocks.
#[inline]
- pub fn digest_blocks(
- &mut self,
- mut input: &[u8],
- mut compress: impl FnMut(&[Block<BlockSize>]),
- ) {
+ pub fn digest_blocks(&mut self, mut input: &[u8], mut compress: impl FnMut(&[Array<u8, BS>])) {
let pos = self.get_pos();
// using `self.remaining()` for some reason
// prevents panic elimination
@@ -146,49 +170,72 @@ where
// `pos + n` which results in it inserting unreachable
// panic branches. Using `unreachable_unchecked` in `get_pos`
// we convince compiler that `BlockSize - pos` never underflows.
- if Kind::invariant(n, rem) {
- // double slicing allows to remove panic branches
- self.buffer[pos..][..n].copy_from_slice(input);
- self.set_pos_unchecked(pos + n);
+ if K::invariant(n, rem) {
+ // SAFETY: we have checked that length of `input` is smaller than
+ // number of remaining bytes in `buffer`, so we can safely write data
+ // into them and update cursor position.
+ unsafe {
+ let buf_ptr = self.buffer.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::copy_nonoverlapping(input.as_ptr(), buf_ptr, input.len());
+ self.set_pos_unchecked(pos + input.len());
+ }
return;
}
if pos != 0 {
let (left, right) = input.split_at(rem);
input = right;
- self.buffer[pos..].copy_from_slice(left);
- compress(slice::from_ref(&self.buffer));
+
+ let g = ResetGuard(self);
+ let buf = &mut g.0.buffer;
+ // SAFETY: length of `left` is equal to number of remaining bytes in `buffer`,
+ // so we can copy data into it and process `buffer` as fully initialized block.
+ // Note that this code can temporarily break the eager buffer invariant,
+ // but we reset the buffer immediately after `compress` using `Drop` impl of
+ // `ResetGuard`, so this code is safe even if `compress` panics.
+ let block = unsafe {
+ let buf_ptr = buf.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::copy_nonoverlapping(left.as_ptr(), buf_ptr, left.len());
+ buf.assume_init_ref()
+ };
+ compress(slice::from_ref(block));
}
- let (blocks, leftover) = Kind::split_blocks(input);
+ let (blocks, leftover) = K::split_blocks(input);
if !blocks.is_empty() {
compress(blocks);
}
- let n = leftover.len();
- self.buffer[..n].copy_from_slice(leftover);
- self.set_pos_unchecked(n);
+ // SAFETY: `leftover` is always smaller than block size,
+ // so it satisfies the method's safety requirements for all buffer kinds
+ unsafe {
+ self.set_data_unchecked(leftover);
+ }
}
/// Reset buffer by setting cursor position to zero.
#[inline(always)]
pub fn reset(&mut self) {
- self.set_pos_unchecked(0);
+ // SAFETY: 0 is always valid position
+ unsafe {
+ self.set_pos_unchecked(0);
+ }
}
/// Pad remaining data with zeros and return resulting block.
#[inline(always)]
- pub fn pad_with_zeros(&mut self) -> &mut Block<BlockSize> {
- let pos = self.get_pos();
- self.buffer[pos..].iter_mut().for_each(|b| *b = 0);
- self.set_pos_unchecked(0);
- &mut self.buffer
+ pub fn pad_with_zeros(&mut self) -> Array<u8, BS> {
+ let mut res = Array::<u8, BS>::default();
+ let data = self.get_data();
+ res[..data.len()].copy_from_slice(data);
+ self.reset();
+ res
}
/// Return current cursor position.
#[inline(always)]
pub fn get_pos(&self) -> usize {
- let pos = self.pos as usize;
- if !Kind::invariant(pos, BlockSize::USIZE) {
+ let pos = K::get_pos(&self.buffer, &self.pos);
+ if !K::invariant(pos, BS::USIZE) {
debug_assert!(false);
// SAFETY: `pos` never breaks the invariant
unsafe {
@@ -201,79 +248,114 @@ where
/// Return slice of data stored inside the buffer.
#[inline(always)]
pub fn get_data(&self) -> &[u8] {
- &self.buffer[..self.get_pos()]
+ // SAFETY: the `buffer` field is properly initialized up to `self.get_pos()`.
+ // `get_pos` never returns position bigger than buffer size.
+ unsafe { slice::from_raw_parts(self.buffer.as_ptr().cast(), self.get_pos()) }
}
/// Set buffer content and cursor position.
///
/// # Panics
/// If `pos` is bigger or equal to block size.
#[inline]
- pub fn set(&mut self, buf: Block<BlockSize>, pos: usize) {
- assert!(Kind::invariant(pos, BlockSize::USIZE));
- self.buffer = buf;
- self.set_pos_unchecked(pos);
+ pub fn set(&mut self, buf: Array<u8, BS>, pos: usize) {
+ assert!(K::invariant(pos, BS::USIZE));
+ self.buffer = MaybeUninit::new(buf);
+ // SAFETY: we have asserted that `pos` satisfies the invariant and
+ // the `buffer` field is fully initialized
+ unsafe {
+ self.set_pos_unchecked(pos);
+ }
}
- /// Return size of the internall buffer in bytes.
+ /// Return size of the internal buffer in bytes.
#[inline(always)]
pub fn size(&self) -> usize {
- BlockSize::USIZE
+ BS::USIZE
}
- /// Return number of remaining bytes in the internall buffer.
+ /// Return number of remaining bytes in the internal buffer.
#[inline(always)]
pub fn remaining(&self) -> usize {
self.size() - self.get_pos()
}
+ /// Set buffer position.
+ ///
+ /// # Safety
+ /// Bytes in the range of `0..pos` in the `buffer` field must be properly initialized.
+ ///
+ /// `pos` must satisfy invariant of buffer kind, i.e. for eager hashes it must be
+ /// strictly smaller than block size and for lazy hashes it must be smaller or equal
+ /// to block size.
+ #[inline(always)]
+ unsafe fn set_pos_unchecked(&mut self, pos: usize) {
+ debug_assert!(K::invariant(pos, BS::USIZE));
+ K::set_pos(&mut self.buffer, &mut self.pos, pos);
+ }
+
+ /// Set buffer data.
+ ///
+ /// # Safety
+ /// Length of `buf` must satisfy invariant of buffer kind, i.e. for eager hashes it must be
+ /// strictly smaller than block size and for lazy hashes it must be smaller or equal
+ /// to block size.
#[inline(always)]
- fn set_pos_unchecked(&mut self, pos: usize) {
- debug_assert!(Kind::invariant(pos, BlockSize::USIZE));
- self.pos = pos as u8;
+ unsafe fn set_data_unchecked(&mut self, buf: &[u8]) {
+ unsafe {
+ self.set_pos_unchecked(buf.len());
+ let dst_ptr: *mut u8 = self.buffer.as_mut_ptr().cast();
+ ptr::copy_nonoverlapping(buf.as_ptr(), dst_ptr, buf.len());
+ }
}
}
-impl<BlockSize> BlockBuffer<BlockSize, Eager>
+/// Size of serialized `BlockBuffer` in bytes.
+pub type SerializedBufferSize<BS, K> = Sum<BS, <K as sealed::Sealed>::Overhead>;
+/// `BlockBuffer` serialized as a byte array.
+pub type SerializedBuffer<BS, K> = Array<u8, SerializedBufferSize<BS, K>>;
+
+impl<BS: BlockSizes, K: BufferKind> BlockBuffer<BS, K>
where
- BlockSize: ArrayLength<u8> + IsLess<U256>,
- Le<BlockSize, U256>: NonZero,
+ BS: core::ops::Add<K::Overhead>,
+ Sum<BS, K::Overhead>: ArraySize,
{
- /// Set `data` to generated blocks.
- #[inline]
- pub fn set_data(
- &mut self,
- mut data: &mut [u8],
- mut process_blocks: impl FnMut(&mut [Block<BlockSize>]),
- ) {
- let pos = self.get_pos();
- let r = self.remaining();
- let n = data.len();
- if pos != 0 {
- if n < r {
- // double slicing allows to remove panic branches
- data.copy_from_slice(&self.buffer[pos..][..n]);
- self.set_pos_unchecked(pos + n);
- return;
- }
- let (left, right) = data.split_at_mut(r);
- data = right;
- left.copy_from_slice(&self.buffer[pos..]);
+ /// Serialize buffer into a byte array.
+ #[allow(clippy::missing_panics_doc)]
+ pub fn serialize(&self) -> SerializedBuffer<BS, K> {
+ let mut buf = SerializedBuffer::<BS, K>::default();
+ let data = self.get_data();
+ let (pos, block) = buf.split_at_mut(1);
+ pos[0] = u8::try_from(data.len()).expect("buffer size is smaller than 256");
+ block[..data.len()].copy_from_slice(data);
+ buf
+ }
+
+ /// Deserialize buffer from a byte array.
+ ///
+ /// # Errors
+ /// If `buf` does not represent a valid serialization of `BlockBuffer`.
+ pub fn deserialize(buf: &SerializedBuffer<BS, K>) -> Result<Self, Error> {
+ let (pos, block) = buf.split_at(1);
+ let pos = usize::from(pos[0]);
+
+ if !<K as sealed::Sealed>::invariant(pos, BS::USIZE) {
+ return Err(Error);
}
- let (blocks, leftover) = to_blocks_mut(data);
- process_blocks(blocks);
+ let (data, tail) = block.split_at(pos);
- let n = leftover.len();
- if n != 0 {
- let mut block = Default::default();
- process_blocks(slice::from_mut(&mut block));
- leftover.copy_from_slice(&block[..n]);
- self.buffer = block;
+ if tail.iter().any(|&b| b != 0) {
+ return Err(Error);
}
- self.set_pos_unchecked(n);
+
+ let mut res = Self::default();
+ unsafe { res.set_data_unchecked(data) };
+ Ok(res)
}
+}
+impl<BS: BlockSizes> BlockBuffer<BS, Eager> {
/// Compress remaining data after padding it with `delim`, zeros and
/// the `suffix` bytes. If there is not enough unused space, `compress`
/// will be called twice.
@@ -285,60 +367,85 @@ where
&mut self,
delim: u8,
suffix: &[u8],
- mut compress: impl FnMut(&Block<BlockSize>),
+ mut compress: impl FnMut(&Array<u8, BS>),
) {
- if suffix.len() > BlockSize::USIZE {
- panic!("suffix is too long");
- }
let pos = self.get_pos();
- self.buffer[pos] = delim;
- for b in &mut self.buffer[pos + 1..] {
- *b = 0;
+ let size = self.size();
+ // Number of bytes remaining in the buffer after `delim` is written to it
+ // This never underflows since for eager buffers `size` is always greater than `pos`.
+ let pad_len = size - pos - 1;
+
+ let suffix_dst_pos = size
+ .checked_sub(suffix.len())
+ .expect("suffix must be smaller than buffer block size");
+
+ let g = ResetGuard(self);
+ // SAFETY: we fully initialize the buffer. Note that we may temporarily break
+ // the buffer invariant, but we restore it using `ResetGuard`,
+ // which works even if `compress` panics.
+ let buf = unsafe {
+ let p: *mut u8 = g.0.buffer.as_mut_ptr().cast::<u8>().add(pos);
+ ptr::write(p, delim);
+ ptr::write_bytes(p.add(1), 0, pad_len);
+ g.0.buffer.assume_init_mut()
+ };
+
+ if pad_len < suffix.len() {
+ compress(buf);
+ buf.fill(0);
}
- let n = self.size() - suffix.len();
- if self.size() - pos - 1 < suffix.len() {
- compress(&self.buffer);
- let mut block = Block::<BlockSize>::default();
- block[n..].copy_from_slice(suffix);
- compress(&block);
- } else {
- self.buffer[n..].copy_from_slice(suffix);
- compress(&self.buffer);
- }
- self.set_pos_unchecked(0)
+ buf[suffix_dst_pos..].copy_from_slice(suffix);
+ compress(buf);
}
/// Pad message with 0x80, zeros and 64-bit message length using
/// big-endian byte order.
#[inline]
- pub fn len64_padding_be(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len64_padding_be(&mut self, data_len: u64, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
}
/// Pad message with 0x80, zeros and 64-bit message length using
/// little-endian byte order.
#[inline]
- pub fn len64_padding_le(&mut self, data_len: u64, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len64_padding_le(&mut self, data_len: u64, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_le_bytes(), compress);
}
/// Pad message with 0x80, zeros and 128-bit message length using
/// big-endian byte order.
#[inline]
- pub fn len128_padding_be(&mut self, data_len: u128, compress: impl FnMut(&Block<BlockSize>)) {
+ pub fn len128_padding_be(&mut self, data_len: u128, compress: impl FnMut(&Array<u8, BS>)) {
self.digest_pad(0x80, &data_len.to_be_bytes(), compress);
}
}
-/// Split message into mutable slice of parallel blocks, blocks, and leftover bytes.
-#[inline(always)]
-fn to_blocks_mut<N: ArrayLength<u8>>(data: &mut [u8]) -> (&mut [Block<N>], &mut [u8]) {
- let nb = data.len() / N::USIZE;
- let (left, right) = data.split_at_mut(nb * N::USIZE);
- let p = left.as_mut_ptr() as *mut Block<N>;
- // SAFETY: we guarantee that `blocks` does not point outside of `data`, and `p` is valid for
- // mutation
- let blocks = unsafe { slice::from_raw_parts_mut(p, nb) };
- (blocks, right)
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes, K: BufferKind> Zeroize for BlockBuffer<BS, K> {
+ #[inline]
+ fn zeroize(&mut self) {
+ self.buffer.zeroize();
+ self.pos.zeroize();
+ }
+}
+
+impl<BS: BlockSizes, K: BufferKind> Drop for BlockBuffer<BS, K> {
+ #[inline]
+ fn drop(&mut self) {
+ #[cfg(feature = "zeroize")]
+ self.zeroize();
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes, K: BufferKind> ZeroizeOnDrop for BlockBuffer<BS, K> {}
+
+/// Resets the referenced buffer on drop.
+struct ResetGuard<'a, BS: BlockSizes, K: BufferKind>(&'a mut BlockBuffer<BS, K>);
+
+impl<BS: BlockSizes, K: BufferKind> Drop for ResetGuard<'_, BS, K> {
+ fn drop(&mut self) {
+ self.0.reset();
+ }
}
### external/vendor/block-buffer/src/read.rs
@@ -0,0 +1,199 @@
+use super::{Array, BlockSizes, Error};
+use core::fmt;
+
+/// Buffer for reading block-generated data.
+pub struct ReadBuffer<BS: BlockSizes> {
+ /// The first byte of the block is used as cursor position.
+ /// `&buffer[usize::from(buffer[0])..]` is interpreted as unread bytes.
+ /// The cursor position is always bigger than zero and smaller than or equal to block size.
+ buffer: Array<u8, BS>,
+}
+
+impl<BS: BlockSizes> fmt::Debug for ReadBuffer<BS> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ReadBuffer")
+ .field("remaining_data", &self.remaining())
+ .finish_non_exhaustive()
+ }
+}
+
+impl<BS: BlockSizes> Default for ReadBuffer<BS> {
+ #[inline]
+ fn default() -> Self {
+ let buffer = Default::default();
+ let mut res = Self { buffer };
+ // SAFETY: `BS::USIZE` satisfies the `set_pos_unchecked` safety contract
+ unsafe { res.set_pos_unchecked(BS::USIZE) };
+ res
+ }
+}
+
+impl<BS: BlockSizes> Clone for ReadBuffer<BS> {
+ #[inline]
+ fn clone(&self) -> Self {
+ let buffer = self.buffer.clone();
+ Self { buffer }
+ }
+}
+
+impl<BS: BlockSizes> ReadBuffer<BS> {
+ /// Return current cursor position, i.e. how many bytes were read from the buffer.
+ #[inline(always)]
+ pub fn get_pos(&self) -> usize {
+ let pos = self.buffer[0];
+ if pos == 0 || pos > BS::U8 {
+ debug_assert!(false);
+ // SAFETY: `pos` never breaks the invariant
+ unsafe {
+ core::hint::unreachable_unchecked();
+ }
+ }
+ pos as usize
+ }
+
+ /// Return size of the internal buffer in bytes.
+ #[inline(always)]
+ pub fn size(&self) -> usize {
+ BS::USIZE
+ }
+
+ /// Return number of remaining bytes in the internal buffer.
+ #[inline(always)]
+ pub fn remaining(&self) -> usize {
+ self.size() - self.get_pos()
+ }
+
+ /// Set cursor position.
+ ///
+ /// # Safety
+ /// `pos` must be smaller than or equal to the buffer block size and be bigger than zero.
+ #[inline(always)]
+ #[allow(clippy::cast_possible_truncation)]
+ unsafe fn set_pos_unchecked(&mut self, pos: usize) {
+ debug_assert!(pos != 0 && pos <= BS::USIZE);
+ self.buffer[0] = pos as u8;
+ }
+
+ /// Read up to `len` bytes of remaining data in the buffer.
+ ///
+ /// Returns slice with length of `ret_len = min(len, buffer.remaining())` bytes
+ /// and sets the cursor position to `buffer.get_pos() + ret_len`.
+ #[inline(always)]
+ pub fn read_cached(&mut self, len: usize) -> &[u8] {
+ let rem = self.remaining();
+ let new_len = core::cmp::min(rem, len);
+ let pos = self.get_pos();
+
+ // SAFETY: `pos + new_len` is not equal to zero and not bigger than block size
+ unsafe { self.set_pos_unchecked(pos + new_len) };
+ &self.buffer[pos..][..new_len]
+ }
+
+ /// Write new block and consume `read_len` bytes from it.
+ ///
+ /// If `read_len` is equal to zero, immediately returns without calling the closures.
+ /// Otherwise, the method calls `gen_block` to fill the internal buffer,
+ /// passes to `read_fn` slice with first `read_len` bytes of the block,
+ /// and sets the cursor position to `read_len`.
+ ///
+ /// # Panics
+ /// If `read_len` is bigger than block size.
+ #[inline(always)]
+ pub fn write_block(
+ &mut self,
+ read_len: usize,
+ gen_block: impl FnOnce(&mut Array<u8, BS>),
+ read_fn: impl FnOnce(&[u8]),
+ ) {
+ if read_len == 0 {
+ return;
+ }
+ assert!(read_len < BS::USIZE);
+
+ let g = ResetGuard(self);
+ let buf = &mut g.0.buffer;
+
+ // Note that generated block is likely to break the `ReadBuffer` invariant.
+ // We restore it using `set_pos_unchecked` below and in case if one of the closures
+ // panic the buffer gets reset by the guard.
+ gen_block(buf);
+ read_fn(&buf[..read_len]);
+
+ core::mem::forget(g);
+
+ // We checked that `read_len` satisfies the `set_pos_unchecked` safety contract
+ unsafe { self.set_pos_unchecked(read_len) };
+ }
+
+ /// Reset buffer into exhausted state.
+ pub fn reset(&mut self) {
+ self.buffer[0] = BS::U8;
+ }
+
+ /// Write remaining data inside buffer into `buf`, fill remaining space
+ /// in `buf` with blocks generated by `gen_block`, and save leftover data
+ /// from the last generated block into the buffer for future use.
+ #[inline]
+ pub fn read(&mut self, buf: &mut [u8], mut gen_block: impl FnMut(&mut Array<u8, BS>)) {
+ let head_ks = self.read_cached(buf.len());
+ let (head, buf) = buf.split_at_mut(head_ks.len());
+ let (blocks, tail) = Array::slice_as_chunks_mut(buf);
+
+ head.copy_from_slice(head_ks);
+ for block in blocks {
+ gen_block(block);
+ }
+
+ self.write_block(tail.len(), gen_block, |tail_ks| {
+ tail.copy_from_slice(tail_ks);
+ });
+ }
+
+ /// Serialize buffer into a byte array.
+ #[inline]
+ pub fn serialize(&self) -> Array<u8, BS> {
+ let pos = self.get_pos();
+ let mut res = self.buffer.clone();
+ // zeroize "garbage" data
+ for b in &mut res[1..pos] {
+ *b = 0;
+ }
+ res
+ }
+
+ /// Deserialize buffer from a byte array.
+ ///
+ /// # Errors
+ /// - If the first byte is `0`.
+ /// - If the first byte is bigger than `BS`.
+ #[inline]
+ pub fn deserialize(buffer: &Array<u8, BS>) -> Result<Self, Error> {
+ let pos = usize::from(buffer[0]);
+ if pos == 0 || pos > BS::USIZE || buffer[1..pos].iter().any(|&b| b != 0) {
+ Err(Error)
+ } else {
+ let buffer = buffer.clone();
+ Ok(Self { buffer })
+ }
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes> Drop for ReadBuffer<BS> {
+ fn drop(&mut self) {
+ use zeroize::Zeroize;
+ self.buffer.zeroize();
+ }
+}
+
+#[cfg(feature = "zeroize")]
+impl<BS: BlockSizes> zeroize::ZeroizeOnDrop for ReadBuffer<BS> {}
+
+/// Resets the referenced buffer on drop.
+struct ResetGuard<'a, BS: BlockSizes>(&'a mut ReadBuffer<BS>);
+
+impl<BS: BlockSizes> Drop for ResetGuard<'_, BS> {
+ fn drop(&mut self) {
+ self.0.reset();
+ }
+}
### external/vendor/block-buffer/src/sealed.rs
@@ -1,67 +1,106 @@
-use super::{ArrayLength, Block};
-use core::slice;
+use hybrid_array::{
+ sizes::{U0, U1, U256},
+ typenum::{IsLess, NonZero, True, Unsigned},
+};
+
+use super::{Array, ArraySize};
+use core::{mem::MaybeUninit, ptr};
+
+type Block<N> = MaybeUninit<Array<u8, N>>;
/// Sealed trait for buffer kinds.
pub trait Sealed {
+ #[cfg(not(feature = "zeroize"))]
+ type Pos: Default + Clone;
+ #[cfg(feature = "zeroize")]
+ type Pos: Default + Clone + zeroize::Zeroize;
+
+ type Overhead: ArraySize;
+
+ const NAME: &'static str;
+
+ fn get_pos<N: ArraySize>(buf: &Block<N>, pos: &Self::Pos) -> usize;
+
+ fn set_pos<N: ArraySize>(buf: &mut Block<N>, pos: &mut Self::Pos, val: usize);
+
/// Invariant guaranteed by a buffer kind, i.e. with correct
/// buffer code this function always returns true.
fn invariant(pos: usize, block_size: usize) -> bool;
- /// Split input data into slice fo blocks and tail.
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]);
+ /// Split input data into slice of blocks and tail.
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]);
}
impl Sealed for super::Eager {
+ type Pos = ();
+ type Overhead = U0;
+ const NAME: &'static str = "BlockBuffer<Eager>";
+
+ fn get_pos<N: ArraySize>(buf: &Block<N>, _pos: &Self::Pos) -> usize {
+ // SAFETY: last byte in `buf` for eager hashes is always properly initialized
+ let pos = unsafe {
+ let buf_ptr = buf.as_ptr().cast::<u8>();
+ let last_byte_ptr = buf_ptr.add(N::USIZE - 1);
+ ptr::read(last_byte_ptr)
+ };
+ pos as usize
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ fn set_pos<N: ArraySize>(buf: &mut Block<N>, _pos: &mut Self::Pos, val: usize) {
+ debug_assert!(u8::try_from(val).is_ok());
+ // SAFETY: we write to the last byte of `buf` which is always safe
+ unsafe {
+ let buf_ptr = buf.as_mut_ptr().cast::<u8>();
+ let last_byte_ptr = buf_ptr.add(N::USIZE - 1);
+ ptr::write(last_byte_ptr, val as u8);
+ }
+ }
+
#[inline(always)]
fn invariant(pos: usize, block_size: usize) -> bool {
pos < block_size
}
#[inline(always)]
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]) {
- let nb = data.len() / N::USIZE;
- let blocks_len = nb * N::USIZE;
- let tail_len = data.len() - blocks_len;
- // SAFETY: we guarantee that created slices do not point
- // outside of `data`
- unsafe {
- let blocks_ptr = data.as_ptr() as *const Block<N>;
- let tail_ptr = data.as_ptr().add(blocks_len);
- (
- slice::from_raw_parts(blocks_ptr, nb),
- slice::from_raw_parts(tail_ptr, tail_len),
- )
- }
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]) {
+ Array::slice_as_chunks(data)
}
}
impl Sealed for super::Lazy {
+ type Pos = u8;
+ type Overhead = U1;
+ const NAME: &'static str = "BlockBuffer<Lazy>";
+
+ fn get_pos<N: ArraySize>(_buf_val: &Block<N>, pos: &Self::Pos) -> usize {
+ *pos as usize
+ }
+
+ #[allow(clippy::cast_possible_truncation)]
+ fn set_pos<N: ArraySize>(_: &mut Block<N>, pos: &mut Self::Pos, val: usize) {
+ debug_assert!(u8::try_from(val).is_ok());
+ *pos = val as u8;
+ }
+
#[inline(always)]
fn invariant(pos: usize, block_size: usize) -> bool {
pos <= block_size
}
#[inline(always)]
- fn split_blocks<N: ArrayLength<u8>>(data: &[u8]) -> (&[Block<N>], &[u8]) {
- if data.is_empty() {
- return (&[], &[]);
- }
- let (nb, tail_len) = if data.len() % N::USIZE == 0 {
- (data.len() / N::USIZE - 1, N::USIZE)
+ fn split_blocks<N: ArraySize>(data: &[u8]) -> (&[Array<u8, N>], &[u8]) {
+ let (blocks, tail) = Array::slice_as_chunks(data);
+ if data.is_empty() || !tail.is_empty() {
+ (blocks, tail)
} else {
- let nb = data.len() / N::USIZE;
- (nb, data.len() - nb * N::USIZE)
- };
- let blocks_len = nb * N::USIZE;
- // SAFETY: we guarantee that created slices do not point
- // outside of `data`
- unsafe {
- let blocks_ptr = data.as_ptr() as *const Block<N>;
- let tail_ptr = data.as_ptr().add(blocks_len);
- (
- slice::from_raw_parts(blocks_ptr, nb),
- slice::from_raw_parts(tail_ptr, tail_len),
- )
+ let (tail, blocks) = blocks.split_last().expect("`blocks` can not be empty");
+ (blocks, tail)
}
}
}
+
+/// Sealed trait implemented for sizes from `U1` to `U255`.
+pub trait BlockSizes {}
+
+impl<T: Unsigned> BlockSizes for T where Self: IsLess<U256, Output = True> + NonZero {}
### external/vendor/block-buffer/tests/mod.rs
@@ -1,10 +1,19 @@
+//! `block-buffer` tests.
+
use block_buffer::{
- generic_array::typenum::{U10, U16, U24, U4, U8},
- Block, EagerBuffer, LazyBuffer,
+ EagerBuffer, LazyBuffer, ReadBuffer,
+ array::{
+ Array,
+ typenum::{U4, U8, U10, U16, U24},
+ },
};
+use hex_literal::hex;
+
+use core::{array, panic::AssertUnwindSafe};
+use std::panic::catch_unwind;
#[test]
-fn test_eager_digest_pad() {
+fn test_eager_digest() {
let mut buf = EagerBuffer::<U4>::default();
let inputs = [
&b"01234567"[..],
@@ -39,7 +48,7 @@ fn test_eager_digest_pad() {
}
#[test]
-fn test_lazy_digest_pad() {
+fn test_lazy_digest() {
let mut buf = LazyBuffer::<U4>::default();
let inputs = [
&b"01234567"[..],
@@ -73,36 +82,82 @@ fn test_lazy_digest_pad() {
}
#[test]
-fn test_eager_set_data() {
- let mut buf = EagerBuffer::<U4>::default();
+fn digest_pad_combinations() {
+ let delim = 0x80;
+ let data: [u8; 7] = array::from_fn(|i| u8::try_from(i).unwrap());
+ let suffix: [u8; 7] = array::from_fn(|i| u8::try_from(i + 0x10).unwrap());
+
+ for data_len in 0..data.len() {
+ for suffix_len in 0..suffix.len() {
+ let data = &data[..data_len];
+ let suffix = &suffix[..suffix_len];
+ let mut buf = EagerBuffer::<U8>::default();
+
+ buf.digest_blocks(data, |_| panic!("should not be called"));
+
+ let mut accum = Vec::with_capacity(2 * buf.size());
+ buf.digest_pad(delim, suffix, |block| accum.extend_from_slice(block));
+
+ assert!(accum.len() <= 2 * buf.size());
+ assert_eq!(buf.get_pos(), 0);
+
+ let (res_data, rem) = accum.split_at(data_len);
+ let (res_delim, rem) = rem.split_at(1);
+ let (res_zeros, res_suffix) = rem.split_at(rem.len() - suffix_len);
+
+ assert_eq!(res_data, data);
+ assert_eq!(res_delim, &[delim]);
+ assert!(res_zeros.iter().all(|&b| b == 0));
+ assert_eq!(res_suffix, suffix);
+ }
+ }
+}
+
+#[test]
+fn test_read() {
+ type Buf = ReadBuffer<U4>;
+ let mut buf = Buf::default();
let mut n = 0u8;
- let mut gen = |blocks: &mut [Block<U4>]| {
- for block in blocks {
- block.iter_mut().for_each(|b| *b = n);
+ let mut g = |block: &mut Array<u8, U4>| {
+ block.iter_mut().for_each(|b| {
+ *b = n;
n += 1;
- }
+ });
};
- let mut out = [0u8; 6];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [0, 0, 0, 0, 1, 1]);
- assert_eq!(buf.get_pos(), 2);
+ let res = buf.read_cached(0);
+ assert!(res.is_empty());
+ let res = buf.read_cached(10);
+ assert!(res.is_empty());
- let mut out = [0u8; 3];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [1, 1, 2]);
- assert_eq!(buf.get_pos(), 1);
+ buf.write_block(2, &mut g, |buf| assert_eq!(buf, [0, 1]));
+ assert_eq!(buf.remaining(), 2);
- let mut out = [0u8; 3];
- buf.set_data(&mut out, &mut gen);
- assert_eq!(out, [2, 2, 2]);
- assert_eq!(n, 3);
- assert_eq!(buf.get_pos(), 0);
+ let res = buf.read_cached(1);
+ assert_eq!(res, [2]);
+ let res = buf.read_cached(10);
+ assert_eq!(res, [3]);
+ assert_eq!(buf.remaining(), 0);
+
+ buf.write_block(0, |_| unreachable!(), |_| unreachable!());
+ buf.write_block(3, &mut g, |buf| assert_eq!(buf, [4, 5, 6]));
+ assert_eq!(buf.remaining(), 1);
+
+ buf.write_block(0, |_| unreachable!(), |_| unreachable!());
+ assert_eq!(buf.remaining(), 1);
+ let res = buf.read_cached(10);
+ assert_eq!(res, [7]);
+
+ buf.write_block(1, &mut g, |buf| assert_eq!(buf, [8]));
+ assert_eq!(buf.remaining(), 3);
+
+ let res = buf.read_cached(10);
+ assert_eq!(res, [9, 10, 11]);
+ assert_eq!(buf.remaining(), 0);
}
#[test]
-#[rustfmt::skip]
fn test_eager_paddings() {
let mut buf_be = EagerBuffer::<U8>::new(&[0x42]);
let mut buf_le = buf_be.clone();
@@ -112,20 +167,8 @@ fn test_eager_paddings() {
buf_be.len64_padding_be(len, |block| out_be.extend(block));
buf_le.len64_padding_le(len, |block| out_le.extend(block));
- assert_eq!(
- out_be,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- ],
- );
- assert_eq!(
- out_le,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00,
- ],
- );
+ assert_eq!(out_be, hex!("4280000000000000 0001020304050607"));
+ assert_eq!(out_le, hex!("4280000000000000 0706050403020100"));
let mut buf_be = EagerBuffer::<U10>::new(&[0x42]);
let mut buf_le = buf_be.clone();
@@ -134,27 +177,19 @@ fn test_eager_paddings() {
buf_be.len64_padding_be(len, |block| out_be.extend(block));
buf_le.len64_padding_le(len, |block| out_le.extend(block));
- assert_eq!(
- out_be,
- [0x42, 0x80, 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07],
- );
- assert_eq!(
- out_le,
- [0x42, 0x80, 0x07, 0x06, 0x05, 0x04, 0x03, 0x02, 0x01, 0x00],
- );
+ assert_eq!(out_be, hex!("42800001020304050607"));
+ assert_eq!(out_le, hex!("42800706050403020100"));
let mut buf = EagerBuffer::<U16>::new(&[0x42]);
let mut out = Vec::<u8>::new();
let len = 0x0001_0203_0405_0607_0809_0a0b_0c0d_0e0f;
buf.len128_padding_be(len, |block| out.extend(block));
assert_eq!(
out,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- ],
+ hex!(
+ "42800000000000000000000000000000"
+ "000102030405060708090a0b0c0d0e0f"
+ ),
);
let mut buf = EagerBuffer::<U24>::new(&[0x42]);
@@ -163,28 +198,18 @@ fn test_eager_paddings() {
buf.len128_padding_be(len, |block| out.extend(block));
assert_eq!(
out,
- [
- 0x42, 0x80, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
- 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
- 0x08, 0x09, 0x0a, 0x0b, 0x0c, 0x0d, 0x0e, 0x0f,
- ],
+ hex!("4280000000000000 0001020304050607 08090a0b0c0d0e0f")
);
let mut buf = EagerBuffer::<U4>::new(&[0x42]);
let mut out = Vec::<u8>::new();
- buf.digest_pad(0xff, &[0x10, 0x11, 0x12], |block| out.extend(block));
- assert_eq!(
- out,
- [0x42, 0xff, 0x00, 0x00, 0x00, 0x10, 0x11, 0x12],
- );
+ buf.digest_pad(0xff, &hex!("101112"), |block| out.extend(block));
+ assert_eq!(out, hex!("42ff000000101112"));
let mut buf = EagerBuffer::<U4>::new(&[0x42]);
let mut out = Vec::<u8>::new();
- buf.digest_pad(0xff, &[0x10, 0x11], |block| out.extend(block));
- assert_eq!(
- out,
- [0x42, 0xff, 0x10, 0x11],
- );
+ buf.digest_pad(0xff, &hex!("1011"), |block| out.extend(block));
+ assert_eq!(out, hex!("42ff1011"));
}
#[test]
@@ -194,3 +219,217 @@ fn test_try_new() {
assert!(LazyBuffer::<U4>::try_new(&[0; 4]).is_ok());
assert!(LazyBuffer::<U4>::try_new(&[0; 5]).is_err());
}
+
+#[test]
+fn test_eager_serialize() {
+ type Buf = EagerBuffer<U4>;
+
+ let mut buf1 = Buf::default();
+ let ser0 = buf1.serialize();
+ assert_eq!(&ser0[..], &[0, 0, 0, 0]);
+ assert_eq!(Buf::deserialize(&ser0).unwrap().serialize(), ser0);
+
+ buf1.digest_blocks(&[41, 42], |_| {});
+
+ let ser1 = buf1.serialize();
+ assert_eq!(&ser1[..], &[2, 41, 42, 0]);
+
+ let mut buf2 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+
+ buf1.digest_blocks(&[43], |_| {});
+ buf2.digest_blocks(&[43], |_| {});
+
+ let ser2 = buf1.serialize();
+ assert_eq!(&ser2[..], &[3, 41, 42, 43]);
+ assert_eq!(buf1.serialize(), ser2);
+
+ let mut buf3 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf3.serialize(), ser2);
+
+ buf1.digest_blocks(&[44], |_| {});
+ buf2.digest_blocks(&[44], |_| {});
+ buf3.digest_blocks(&[44], |_| {});
+
+ let ser3 = buf1.serialize();
+ assert_eq!(&ser3[..], &[0, 0, 0, 0]);
+ assert_eq!(buf2.serialize(), ser3);
+ assert_eq!(buf3.serialize(), ser3);
+
+ // Invalid position
+ let buf = Array([0, 0, 0, 4]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([0, 0, 0, 10]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([0, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([1, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([2, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn test_lazy_serialize() {
+ type Buf = LazyBuffer<U4>;
+
+ let mut buf1 = Buf::default();
+ let ser0 = buf1.serialize();
+ assert_eq!(&ser0[..], &[0, 0, 0, 0, 0]);
+ Buf::deserialize(&ser0).unwrap();
+ assert_eq!(Buf::deserialize(&ser0).unwrap().serialize(), ser0);
+
+ buf1.digest_blocks(&[41, 42], |_| {});
+
+ let ser1 = buf1.serialize();
+ assert_eq!(&ser1[..], &[2, 41, 42, 0, 0]);
+
+ let mut buf2 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+
+ buf1.digest_blocks(&[43], |_| {});
+ buf2.digest_blocks(&[43], |_| {});
+
+ let ser2 = buf1.serialize();
+ assert_eq!(&ser2[..], &[3, 41, 42, 43, 0]);
+ assert_eq!(buf1.serialize(), ser2);
+
+ let mut buf3 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf3.serialize(), ser2);
+
+ buf1.digest_blocks(&[44], |_| {});
+ buf2.digest_blocks(&[44], |_| {});
+ buf3.digest_blocks(&[44], |_| {});
+
+ let ser3 = buf1.serialize();
+ assert_eq!(&ser3[..], &[4, 41, 42, 43, 44]);
+ assert_eq!(buf2.serialize(), ser3);
+ assert_eq!(buf3.serialize(), ser3);
+
+ buf1.digest_blocks(&[45], |_| {});
+ buf2.digest_blocks(&[45], |_| {});
+ buf3.digest_blocks(&[45], |_| {});
+
+ let ser4 = buf1.serialize();
+ assert_eq!(&ser4[..], &[1, 45, 0, 0, 0]);
+ assert_eq!(buf2.serialize(), ser4);
+ assert_eq!(buf3.serialize(), ser4);
+
+ // Invalid position
+ let buf = Array([10, 0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([5, 0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([0, 1, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([1, 0, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([2, 0, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([3, 0, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn test_read_serialize() {
+ type Buf = ReadBuffer<U4>;
+
+ let mut n = 0u8;
+ let mut g = |block: &mut Array<u8, U4>| {
+ block.iter_mut().for_each(|b| {
+ *b = n;
+ n += 1;
+ });
+ };
+
+ let mut buf = Buf::default();
+ let ser1 = buf.serialize();
+ assert_eq!(&ser1[..], &[4, 0, 0, 0]);
+ assert_eq!(Buf::deserialize(&ser1).unwrap().serialize(), ser1);
+
+ let mut buf1 = Buf::deserialize(&ser1).unwrap();
+ assert_eq!(buf1.serialize(), ser1);
+ assert_eq!(buf1.remaining(), 0);
+ assert_eq!(buf1.read_cached(10), []);
+
+ buf.write_block(2, &mut g, |buf| assert_eq!(buf, [0, 1]));
+
+ let ser2 = buf.serialize();
+ assert_eq!(&ser2[..], &[2, 0, 2, 3]);
+
+ let mut buf2 = Buf::deserialize(&ser2).unwrap();
+ assert_eq!(buf2.serialize(), ser2);
+ assert_eq!(buf2.remaining(), 2);
+ assert_eq!(buf2.read_cached(10), [2, 3]);
+
+ // Invalid position
+ let buf = Array([0, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([5, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([10, 0, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ // "Garbage" bytes are not zeroized
+ let buf = Array([2, 1, 0, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([3, 0, 1, 0]);
+ assert!(Buf::deserialize(&buf).is_err());
+ let buf = Array([4, 0, 0, 1]);
+ assert!(Buf::deserialize(&buf).is_err());
+}
+
+#[test]
+fn eager_buffer_exception_safety() {
+ let mut buf = EagerBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.digest_blocks(b"ab", |_| {});
+ buf.digest_blocks(b"cd", |_| panic!("compression panic"));
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+
+ let mut buf = EagerBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.digest_pad(0x80, &[0xFF; 2], |_| panic!("compression panic"));
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+}
+
+#[test]
+fn read_buffer_exception_safety() {
+ let mut buf = ReadBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.write_block(
+ 1,
+ |block| {
+ block[0] = 0xFF;
+ panic!("block generation panic");
+ },
+ |_| {},
+ );
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+
+ let mut buf = ReadBuffer::<U4>::default();
+
+ let res = catch_unwind(AssertUnwindSafe(|| {
+ buf.write_block(
+ 1,
+ |block| block.0 = [0xFF; 4],
+ |_| panic!("data read panic"),
+ );
+ }));
+
+ assert!(res.is_err());
+ let _ = buf.get_pos();
+}
### external/vendor/chacha20/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"1e717a0a3af924ef26b5349baa318d74772df13682532289b569f771cca3bf08","CHANGELOG.md":"cc005edfbbe3e406f9b908cc1f4a25c0fddc862e3d01840052c4ba0e238e68cd","Cargo.toml":"ed1dc396afc4669bcefbd7b6b0fdb77db889e745be889454a10670c14c1a50d6","Cargo.toml.orig":"693a20d2603da94969ec53144742b23a6d3a5d8db3585593a86c9fb623d524e7","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b6f6f01b03ee7e93c0ae96d62ed39527e98a120fb951afc9de456a741ef3f204","README.md":"a801378a1347d00327a45b1cdeddf3f0dac0ad577bc70d313114daebc8ac5b7b","benches/mod.rs":"ef9cff285db7037458f550f40b7c6e7f7f0d9e687bf61d796a83cbc034db57ae","src/backends.rs":"497002020de5081a68736e9a86c73d68dcfe66ae77354f42e6041256bcd8ca68","src/backends/avx2.rs":"21a0955e674e510996ddaea8de9e17d8fc67bd1da8f386203b9a3cf9cb82fe9d","src/backends/neon.rs":"5530258e3113dbcba6dbbda189621b5a3993fbdc0e1b88e342e27895274c9138","src/backends/soft.rs":"c6d6fbf33f80262eb77a5a171ade2b06365cd84501479aec97a4e932046f0a14","src/backends/sse2.rs":"3a0a1c08728e3641cf98f3e59b7fe6063df569ebfe3fa1817583dcff85655fbb","src/legacy.rs":"67345897d9ba3815879a3ccd7970920de11bfbb988aa79b925893e4d84ed202c","src/lib.rs":"4112893bb7a5eb6cdb269200c816befaeadecf7e932ab2612c0941b7f7d7c6c3","src/xchacha.rs":"f1599eedd6b2db835939d96bb65b647e9279c045592858f270ead3a4a77b360a","tests/data/chacha20-legacy.blb":"439fed37a60f1a56f5c343df168998ec8fe7fe6dcaeb07f8992a5602590aa73b","tests/data/chacha20.blb":"da4ce597c2c73b2e1827bfc2b992b856c5581afeb22deeab58fc3c2092da0c6b","tests/mod.rs":"79684247bf681350c6784af0b042cd519fd24af80904af35252f3bdb10178476"},"package":"c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"69523f9d6c632db59fc022665e18e658a339c3f5579a8435526f536a7241123c","CHANGELOG.md":"62b490baa02637dc7810a52716a1b7c2cdbce591fab695df87d843857cdd47cd","Cargo.lock":"700dfe85f890b63ad04e31fa68e2102b72f034fd8bc3216780a7b5875a762c31","Cargo.toml":"b48970318446b5a41b06b1e27f2e691b6fc9245ee82beabde925f0a0889d58ba","Cargo.toml.orig":"ce1889452c49e116d1e4e3b1af355947a57852804ec9687220d1e1579983b8c4","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b8c6939380a400f53e11923d50fcc4dd2fa1ba8339fd9d04cda38a0251b6c9b0","README.md":"e5495c78bf5270bcca880e0f68c552d435dabd92764c9cc2f62b574b2d75588d","benches/mod.rs":"93ca43362e31d6707f131e8c4484cfb3aaa209058510b40ff7805601f57c68ab","src/backends.rs":"a5b51ab7b20fdb7d99c29b231bfbc8fc643f1002ad2155f4e6757be9cc990105","src/backends/avx2.rs":"c44c34d86ab9d896ac8b863e611f496cda31b5d731b1c860f70c0772426da918","src/backends/avx512.rs":"b4e945d887f0fb11e2dc6a757f7dc01e7553d486ae8d381964defaf8857d9ab6","src/backends/neon.rs":"5d29e3c2da18ea649f6e19fc339bb6253611db18cafcba4993155b70d096f102","src/backends/soft.rs":"120bcf4bc535c3fbcc3b4e2bdc0f021e44fae553bf5bb3a532271b2a08dc2149","src/backends/sse2.rs":"6e03915126187bf361567e39a0e0dc35366468b35b8f2bf87f11a62762e79d3f","src/chacha.rs":"323b76530ad49db28cb1764dbee7843908af21ae85918e4ade04abad8a4614bb","src/legacy.rs":"f5e9dc27cc2c911d087f198bcdbbbb9a1f55c873c5bbd6e79280d1628f72ab49","src/lib.rs":"b539477230a58abfa2e2ab8dd62c017ffc84f3a7680971c5496973185c543c20","src/rng.rs":"8f1367fed752857f0c6ec9c7a7bd154417a80b780b342c9346af4f16b3089bde","src/variants.rs":"79bb423dd0ef0ac690334915baea48db17f055797175c22b1bcbed0714dd9f88","src/xchacha.rs":"86de92973ea8701003c97994fb95fe33099dc0fe0938c27d10f20e95d4b94000","tests/data/chacha20-legacy.blb":"2405a7f849b5db6ae8f6ba79dd943632f7ba3f9839a9c4db86a79a1f069e5e30","tests/data/chacha20.blb":"2686172dba8dd9a5f20d37881b3bf8ef68a9a5106cb8178628ca892e2a5d9052","tests/kats.rs":"ea16474f269f1c5edb5551ecfbfb40bc0fac06b3f293c2365b1442b5338c684f","tests/rng.rs":"eb59c35b32f11e72a6dc04ca790b5efc35331c8315b4039222847eb3c6abcfe9"},"package":"65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06"}
\ No newline at end of file
### external/vendor/chacha20/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "b5d39c45c45df97335f4b6effb853cde97810de1"
+ "sha1": "6b236b758a0279f64d777797514813b2cb572c8b"
},
"path_in_vcs": "chacha20"
}
\ No newline at end of file
### external/vendor/chacha20/CHANGELOG.md
@@ -5,6 +5,56 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.10.2 (2026-08-27)
+### Fixed
+- Use of SSE4.1 intrinsic in SSE2 backend of RNG and legacy (64-bit counter) variants ([#580])
+
+[#580]: https://github.com/RustCrypto/stream-ciphers/pull/580
+
+## 0.10.1 (2026-06-24)
+### Added
+- `ChaCha20LegacyCore` type and `Nonce` type alias ([#570])
+
+[#570]: https://github.com/RustCrypto/stream-ciphers/pull/570
+
+## 0.10.0 (2026-02-07)
+### Added
+- `rand_core` v0.10 support ([#333], [#513])
+- 64-bit counter support ([#439])
+- `{get,set}_block_pos` inherent methods ([#516])
+- AVX-512 backend - requires `--cfg chacha20_avx512` to enable ([#477])
+- Inherent methods for RNG state (de)serialization ([#541])
+
+### Changed
+- Bump `cipher` from `0.4` to `0.5` - replaces `generic-array` with `hybrid-array` ([#338], [#521])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#397])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+- Bump `cpufeatures` to v0.3 ([#530])
+- `--cfg chacha20_backend="..."` replaces previous `chacha20_force*` ([#520])
+ - `chacha20_force_avx2` => `chacha20_backend="avx2"`
+ - `chacha20_force_avx512` => `chacha20_backend="avx512"`
+ - `chacha20_force_soft` => `chacha20_backend="soft"`
+ - `chacha20_force_sse2` => `chacha20_backend="sse2"`
+
+### Removed
+- `chacha20_force_neon` cfg attribute - now on-by-default for supported targets ([#361])
+- `std` feature ([#397])
+- `Clone` impls ([#462])
+
+[#333]: https://github.com/RustCrypto/stream-ciphers/pull/333
+[#338]: https://github.com/RustCrypto/stream-ciphers/pull/338
+[#361]: https://github.com/RustCrypto/stream-ciphers/pull/361
+[#397]: https://github.com/RustCrypto/stream-ciphers/pull/397
+[#439]: https://github.com/RustCrypto/stream-ciphers/pull/439
+[#462]: https://github.com/RustCrypto/stream-ciphers/pull/462
+[#477]: https://github.com/RustCrypto/stream-ciphers/pull/477
+[#513]: https://github.com/RustCrypto/stream-ciphers/pull/513
+[#516]: https://github.com/RustCrypto/stream-ciphers/pull/516
+[#520]: https://github.com/RustCrypto/stream-ciphers/pull/520
+[#521]: https://github.com/RustCrypto/stream-ciphers/pull/521
+[#530]: https://github.com/RustCrypto/stream-ciphers/pull/530
+[#541]: https://github.com/RustCrypto/stream-ciphers/pull/541
+
## 0.9.1 (2023-04-01)
### Added
- NEON support via `chacha20_force_neon` cfg attribute ([#310], [#317])
### external/vendor/chacha20/Cargo.lock
@@ -0,0 +1,114 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.2"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+ "hex-literal",
+ "rand_core",
+ "zeroize",
+]
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.14"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "707114b52a152fa7bdb290cd7cd5912d9467273b6d74e21b8d81aca1f8533f6b"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.189"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "3eaf3ede3fee6db1a4c2ee091bf8a8b4dccdc6d17f656fb07896ee72867612f2"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/chacha20/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "chacha20"
-version = "0.9.1"
+version = "0.10.2"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits
from the RustCrypto `cipher` crate, with optional architecture-specific
@@ -35,33 +41,107 @@ categories = [
"cryptography",
"no-std",
]
-license = "Apache-2.0 OR MIT"
+license = "MIT OR Apache-2.0"
repository = "https://github.com/RustCrypto/stream-ciphers"
-resolver = "1"
+resolver = "2"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
-]
+
+[features]
+default = ["cipher"]
+legacy = ["cipher"]
+rng = ["dep:rand_core"]
+xchacha = ["cipher"]
+
+[lib]
+name = "chacha20"
+path = "src/lib.rs"
+
+[[test]]
+name = "kats"
+path = "tests/kats.rs"
+
+[[test]]
+name = "rng"
+path = "tests/rng.rs"
+
+[[bench]]
+name = "mod"
+path = "benches/mod.rs"
[dependencies.cfg-if]
version = "1"
[dependencies.cipher]
-version = "0.4.4"
+version = "0.5"
+features = ["stream-wrapper"]
+optional = true
+
+[dependencies.rand_core]
+version = "0.10"
+optional = true
+default-features = false
+
+[dependencies.zeroize]
+version = "1.8.1"
+optional = true
+default-features = false
[dev-dependencies.cipher]
-version = "0.4.4"
+version = "0.5"
features = ["dev"]
[dev-dependencies.hex-literal]
-version = "0.3.3"
+version = "1"
-[features]
-std = ["cipher/std"]
-zeroize = ["cipher/zeroize"]
+[target.'cfg(any(target_arch = "x86_64", target_arch = "x86"))'.dependencies.cpufeatures]
+version = "0.3"
-[target."cfg(any(target_arch = \"x86_64\", target_arch = \"x86\"))".dependencies.cpufeatures]
-version = "0.2"
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unreachable_pub = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
+
+[lints.rust.unexpected_cfgs]
+level = "warn"
+priority = 0
+check-cfg = [
+ "cfg(chacha20_avx512)",
+ 'cfg(chacha20_backend, values("avx2", "avx512", "soft", "sse2"))',
+]
### external/vendor/chacha20/Cargo.toml.orig
@@ -1,38 +1,90 @@
[package]
name = "chacha20"
-version = "0.9.1"
+version = "0.10.2"
+authors = ["RustCrypto Developers"]
+edition = "2024"
+rust-version = "1.85"
+documentation = "https://docs.rs/chacha20"
+readme = "README.md"
+repository = "https://github.com/RustCrypto/stream-ciphers"
+license = "MIT OR Apache-2.0"
+keywords = ["crypto", "stream-cipher", "chacha8", "chacha12", "xchacha20"]
+categories = ["cryptography", "no-std"]
description = """
The ChaCha20 stream cipher (RFC 8439) implemented in pure Rust using traits
from the RustCrypto `cipher` crate, with optional architecture-specific
hardware acceleration (AVX2, SSE2). Additionally provides the ChaCha8, ChaCha12,
XChaCha20, XChaCha12 and XChaCha8 stream ciphers, and also optional
rand_core-compatible RNGs based on those ciphers.
"""
-authors = ["RustCrypto Developers"]
-license = "Apache-2.0 OR MIT"
-edition = "2021"
-rust-version = "1.56"
-readme = "README.md"
-documentation = "https://docs.rs/chacha20"
-repository = "https://github.com/RustCrypto/stream-ciphers"
-keywords = ["crypto", "stream-cipher", "chacha8", "chacha12", "xchacha20"]
-categories = ["cryptography", "no-std"]
[dependencies]
cfg-if = "1"
-cipher = "0.4.4"
+cipher = { version = "0.5", optional = true, features = ["stream-wrapper"] }
+rand_core = { version = "0.10", optional = true, default-features = false }
+
+# `zeroize` is an explicit dependency because this crate may be used without the `cipher` crate
+zeroize = { version = "1.8.1", optional = true, default-features = false }
[target.'cfg(any(target_arch = "x86_64", target_arch = "x86"))'.dependencies]
-cpufeatures = "0.2"
+cpufeatures = "0.3"
[dev-dependencies]
-cipher = { version = "0.4.4", features = ["dev"] }
-hex-literal = "0.3.3"
+cipher = { version = "0.5", features = ["dev"] }
+hex-literal = "1"
[features]
-std = ["cipher/std"]
-zeroize = ["cipher/zeroize"]
+default = ["cipher"]
+legacy = ["cipher"]
+rng = ["dep:rand_core"]
+xchacha = ["cipher"]
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unreachable_pub = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
+
+[lints.rust.unexpected_cfgs]
+level = "warn"
+check-cfg = [
+ 'cfg(chacha20_avx512)',
+ 'cfg(chacha20_backend, values("avx2", "avx512", "soft", "sse2"))'
+]
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+trivially_copy_pass_by_ref = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/chacha20/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019-2023 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/chacha20/README.md
@@ -2,44 +2,24 @@
[![Crate][crate-image]][crate-link]
[![Docs][docs-image]][docs-link]
+[![Build Status][build-image]][build-link]
![Apache2/MIT licensed][license-image]
![Rust Version][rustc-image]
[![Project Chat][chat-image]][chat-link]
-[![Build Status][build-image]][build-link]
[![HAZMAT][hazmat-image]][hazmat-link]
-Pure Rust implementation of the [ChaCha20 Stream Cipher][1].
-
-[Documentation][docs-link]
-
-<img src="https://raw.githubusercontent.com/RustCrypto/meta/master/img/stream-ciphers/chacha20.png" width="300px">
-
-## About
+Implementation of the [ChaCha] family of stream ciphers.
-[ChaCha20][1] is a [stream cipher][2] which is designed to support
-high-performance software implementations.
+ChaCha improves upon the previous [Salsa] family of stream ciphers
+with increased per-round diffusion at no cost to performance.
-It improves upon the previous [Salsa20][3] stream cipher with increased
-per-round diffusion at no cost to performance.
+This crate also contains an implementation of the [XChaCha] family of stream ciphers
+with an extended 192-bit (24-byte) nonce, gated under the `xchacha` Cargo feature,
+and "legacy" (a.k.a "djb") variant with 64-bit nonce, gated under the `legacy` crate feature.
-This crate also contains an implementation of [XChaCha20][4]: a variant
-of ChaCha20 with an extended 192-bit (24-byte) nonce, gated under the
-`chacha20` Cargo feature (on-by-default).
-
-## Implementations
-
-This crate contains the following implementations of ChaCha20, all of which
-work on stable Rust with the following `RUSTFLAGS`:
-
-- `x86` / `x86_64`
- - `avx2`: (~1.4cpb) `-Ctarget-cpu=haswell -Ctarget-feature=+avx2`
- - `sse2`: (~2.5cpb) `-Ctarget-feature=+sse2` (on by default on x86 CPUs)
-- `aarch64`
- - `neon` (~2-3x faster than `soft`) requires Rust 1.61+ and the `neon` feature enabled
-- Portable
- - `soft`: (~5 cpb on x86/x86_64)
-
-NOTE: cpb = cycles per byte (smaller is better)
+**WARNING:** This implementation internally uses 32-bit counter,
+while the original "legacy" variant implementation uses 64-bit counter.
+In other words, it does not allow encryption of more than 256 GiB of data.
## Security
@@ -49,30 +29,79 @@ This crate does not ensure ciphertexts are authentic (i.e. by using a MAC to
verify ciphertext integrity), which can lead to serious vulnerabilities
if used incorrectly!
-To avoid this, use an [AEAD][5] mode based on ChaCha20, i.e. [ChaCha20Poly1305][6].
-See the [RustCrypto/AEADs][7] repository for more information.
+To avoid this, use an [AEAD] mode based on ChaCha20, e.g. [`chacha20poly1305`].
+See the [RustCrypto/AEADs] repository for more information.
USE AT YOUR OWN RISK!
### Notes
-This crate has received one [security audit by NCC Group][8], with no significant
-findings. We would like to thank [MobileCoin][9] for funding the audit.
+This crate has received one [security audit by NCC Group][NCC-AUDIT], with no significant
+findings. We would like to thank [MobileCoin] for funding the audit.
All implementations contained in the crate (along with the underlying ChaCha20
stream cipher itself) are designed to execute in constant time.
-## Minimum Supported Rust Version
+## Examples
+
+```rust
+// This example requires `cipher` crate feature
+#[cfg(feature = "cipher")] {
+
+use chacha20::ChaCha20;
+use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
+use hex_literal::hex;
+
+let key = [0x42; 32];
+let nonce = [0x24; 12];
+let plaintext = hex!("000102030405060708090A0B0C0D0E0F");
+let ciphertext = hex!("e405626e4f1236b3670ee428332ea20e");
+
+// Key and IV must be references to the `Array` type.
+// Here we use the `Into` trait to convert arrays into it.
+let mut cipher = ChaCha20::new(&key.into(), &nonce.into());
+
+let mut buffer = plaintext;
+
+// apply keystream (encrypt)
+cipher.apply_keystream(&mut buffer);
+assert_eq!(buffer, ciphertext);
+
+let ciphertext = buffer;
+
+// ChaCha ciphers support seeking
+cipher.seek(0u32);
+
+// decrypt ciphertext by applying keystream again
+cipher.apply_keystream(&mut buffer);
+assert_eq!(buffer, plaintext);
+
+// stream ciphers can be used with streaming messages
+cipher.seek(0u32);
+for chunk in buffer.chunks_mut(3) {
+ cipher.apply_keystream(chunk);
+}
+assert_eq!(buffer, ciphertext);
+}
+```
+
+## Configuration Flags
-Rust **1.56** or higher.
+You can modify crate using the following configuration flags:
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+- `chacha20_backend="avx2"`: force AVX2 backend on x86/x86_64 targets.
+ Requires enabled AVX2 target feature. Ignored on non-x86(_64) targets.
+- `chacha20_backend="avx512"`: force AVX-512 backend on x86/x86_64 targets.
+ Requires enabled AVX-512 target feature (MSRV 1.89). Ignored on non-x86(_64) targets.
+- `chacha20_backend="soft"`: force software backend.
+- `chacha20_backend="sse2"`: force SSE2 backend on x86/x86_64 targets.
+ Requires enabled SSE2 target feature. Ignored on non-x86(-64) targets.
-## SemVer Policy
+To use the MSRV 1.89 AVX-512 support with autodetection, you must enable it using
+`chacha20_avx512` configuration flag.
-- All on-by-default features of this library are covered by SemVer
-- MSRV is considered exempt from SemVer as noted above
+The flags can be enabled using `RUSTFLAGS` environmental variable
+(e.g. `RUSTFLAGS='--cfg chacha20_backend="avx2"'`) or by modifying `.cargo/config.toml`.
## License
@@ -95,23 +124,22 @@ dual licensed as above, without any additional terms or conditions.
[crate-link]: https://crates.io/crates/chacha20
[docs-image]: https://docs.rs/chacha20/badge.svg
[docs-link]: https://docs.rs/chacha20/
+[build-image]: https://github.com/RustCrypto/stream-ciphers/actions/workflows/chacha20.yml/badge.svg
+[build-link]: https://github.com/RustCrypto/stream-ciphers/actions/workflows/chacha20.yml
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260049-stream-ciphers
-[build-image]: https://github.com/RustCrypto/stream-ciphers/workflows/chacha20/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/stream-ciphers/actions?query=workflow%3Achacha20
[hazmat-image]: https://img.shields.io/badge/crypto-hazmat%E2%9A%A0-red.svg
[hazmat-link]: https://github.com/RustCrypto/meta/blob/master/HAZMAT.md
[//]: # (footnotes)
-[1]: https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant
-[2]: https://en.wikipedia.org/wiki/Stream_cipher
-[3]: https://en.wikipedia.org/wiki/Salsa20
-[4]: https://tools.ietf.org/html/draft-arciszewski-xchacha-02
-[5]: https://en.wikipedia.org/wiki/Authenticated_encryption
-[6]: https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305
-[7]: https://github.com/RustCrypto/AEADs
-[8]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
-[9]: https://www.mobilecoin.com/
+[ChaCha]: https://en.wikipedia.org/wiki/Salsa20#ChaCha_variant
+[Salsa]: https://en.wikipedia.org/wiki/Salsa20
+[XChaCha]: https://tools.ietf.org/html/draft-arciszewski-xchacha-02
+[AEAD]: https://en.wikipedia.org/wiki/Authenticated_encryption
+[`chacha20poly1305`]: https://docs.rs/chacha20poly1305
+[RustCrypto/AEADs]: https://github.com/RustCrypto/AEADs
+[NCC-AUDIT]: https://web.archive.org/web/20240108154854/https://research.nccgroup.com/wp-content/uploads/2020/02/NCC_Group_MobileCoin_RustCrypto_AESGCM_ChaCha20Poly1305_Implementation_Review_2020-02-12_v1.0.pdf
+[MobileCoin]: https://www.mobilecoin.com/
### external/vendor/chacha20/benches/mod.rs
@@ -1,3 +1,4 @@
+//! Basic benchmarks
#![feature(test)]
extern crate test;
### external/vendor/chacha20/src/backends.rs
@@ -1,21 +1,30 @@
+#![cfg(any(feature = "cipher", feature = "rng"))]
+
use cfg_if::cfg_if;
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
pub(crate) mod soft;
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ pub(crate) mod avx512;
+ // AVX-2 backend needed for RNG if enabled
+ #[cfg(feature = "rng")]
+ pub(crate) mod avx2;
+ } else if #[cfg(chacha20_backend = "avx2")] {
pub(crate) mod avx2;
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
pub(crate) mod sse2;
} else {
pub(crate) mod soft;
+ #[cfg(chacha20_avx512)]
+ pub(crate) mod avx512;
pub(crate) mod avx2;
pub(crate) mod sse2;
}
}
- } else if #[cfg(all(chacha20_force_neon, target_arch = "aarch64", target_feature = "neon"))] {
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
pub(crate) mod neon;
} else {
pub(crate) mod soft;
### external/vendor/chacha20/src/backends/avx2.rs
@@ -1,9 +1,25 @@
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+//! AVX2 backend.
+
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::cast_possible_wrap, reason = "needs triage")]
+#![allow(clippy::cast_sign_loss, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use crate::{Rounds, Variant};
+use core::marker::PhantomData;
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::{STATE_WORDS, chacha::Block};
+
+#[cfg(feature = "cipher")]
use cipher::{
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
consts::{U4, U64},
- BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamBackend,
};
-use core::marker::PhantomData;
#[cfg(target_arch = "x86")]
use core::arch::x86::*;
@@ -17,25 +33,36 @@ const N: usize = PAR_BLOCKS / 2;
#[inline]
#[target_feature(enable = "avx2")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
+#[cfg(feature = "cipher")]
+#[cfg_attr(chacha20_backend = "avx512", expect(unused))]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
{
- let state_ptr = state.as_ptr() as *const __m128i;
+ let state_ptr = state.as_ptr().cast::<__m128i>();
let v = [
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(0))),
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(1))),
_mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(2))),
];
let mut c = _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(3)));
- c = _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0));
+ c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0)),
+ 8 => _mm256_add_epi64(c, _mm256_set_epi64x(0, 1, 0, 0)),
+ _ => unreachable!(),
+ };
let mut ctr = [c; N];
for i in 0..N {
ctr[i] = c;
- c = _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 2, 0, 0, 0, 2));
+ c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(c, _mm256_set_epi32(0, 0, 0, 2, 0, 0, 0, 2)),
+ 8 => _mm256_add_epi64(c, _mm256_set_epi64x(0, 2, 0, 2)),
+ _ => unreachable!(),
+ };
}
- let mut backend = Backend::<R> {
+ let mut backend = Backend::<R, V> {
v,
ctr,
_pd: PhantomData,
@@ -44,34 +71,79 @@ where
f.call(&mut backend);
state[12] = _mm256_extract_epi32(backend.ctr[0], 0) as u32;
+ match size_of::<V::Counter>() {
+ 4 => {}
+ 8 => state[13] = _mm256_extract_epi32(backend.ctr[0], 1) as u32,
+ _ => unreachable!(),
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx2")]
+#[cfg(feature = "rng")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let state_ptr = core.state.as_ptr().cast::<__m128i>();
+ let v = [
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(0))),
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(1))),
+ _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(2))),
+ ];
+ let mut c = _mm256_broadcastsi128_si256(_mm_loadu_si128(state_ptr.add(3)));
+ c = _mm256_add_epi64(c, _mm256_set_epi64x(0, 1, 0, 0));
+ let mut ctr = [c; N];
+ for i in 0..N {
+ ctr[i] = c;
+ c = _mm256_add_epi64(c, _mm256_set_epi64x(0, 2, 0, 2));
+ }
+ let mut backend = Backend::<R, V> {
+ v,
+ ctr,
+ _pd: PhantomData,
+ };
+
+ backend.rng_gen_par_ks_blocks(buffer);
+
+ core.state[12] = _mm256_extract_epi32(backend.ctr[0], 0) as u32;
+ core.state[13] = _mm256_extract_epi32(backend.ctr[0], 1) as u32;
}
-struct Backend<R: Unsigned> {
+struct Backend<R: Rounds, V: Variant> {
v: [__m256i; 3],
ctr: [__m256i; N],
- _pd: PhantomData<R>,
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
type ParBlocksSize = U4;
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
unsafe {
let res = rounds::<R>(&self.v, &self.ctr);
for c in self.ctr.iter_mut() {
- *c = _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 1));
+ *c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 1)),
+ 8 => _mm256_add_epi64(*c, _mm256_set_epi64x(0, 1, 0, 1)),
+ _ => unreachable!(),
+ };
}
let res0: [__m128i; 8] = core::mem::transmute(res[0]);
- let block_ptr = block.as_mut_ptr() as *mut __m128i;
+ let block_ptr = block.as_mut_ptr().cast::<__m128i>();
for i in 0..4 {
_mm_storeu_si128(block_ptr.add(i), res0[2 * i]);
}
@@ -85,10 +157,41 @@ impl<R: Unsigned> StreamBackend for Backend<R> {
let pb = PAR_BLOCKS as i32;
for c in self.ctr.iter_mut() {
- *c = _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, pb, 0, 0, 0, pb));
+ *c = match size_of::<V::Counter>() {
+ 4 => _mm256_add_epi32(*c, _mm256_set_epi32(0, 0, 0, pb, 0, 0, 0, pb)),
+ 8 => {
+ _mm256_add_epi64(*c, _mm256_set_epi64x(0, i64::from(pb), 0, i64::from(pb)))
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ let mut block_ptr = blocks.as_mut_ptr().cast::<__m128i>();
+ for v in vs {
+ let t: [__m128i; 8] = core::mem::transmute(v);
+ for i in 0..4 {
+ _mm_storeu_si128(block_ptr.add(i), t[2 * i]);
+ _mm_storeu_si128(block_ptr.add(4 + i), t[2 * i + 1]);
+ }
+ block_ptr = block_ptr.add(8);
+ }
+ }
+ }
+}
+
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ fn rng_gen_par_ks_blocks(&mut self, blocks: &mut [u32; 64]) {
+ unsafe {
+ let vs = rounds::<R>(&self.v, &self.ctr);
+
+ let pb = PAR_BLOCKS as i32;
+ for c in self.ctr.iter_mut() {
+ *c = _mm256_add_epi64(*c, _mm256_set_epi64x(0, i64::from(pb), 0, i64::from(pb)));
}
- let mut block_ptr = blocks.as_mut_ptr() as *mut __m128i;
+ let mut block_ptr = blocks.as_mut_ptr().cast::<__m128i>();
for v in vs {
let t: [__m128i; 8] = core::mem::transmute(v);
for i in 0..4 {
@@ -103,12 +206,12 @@ impl<R: Unsigned> StreamBackend for Backend<R> {
#[inline]
#[target_feature(enable = "avx2")]
-unsafe fn rounds<R: Unsigned>(v: &[__m256i; 3], c: &[__m256i; N]) -> [[__m256i; 4]; N] {
+unsafe fn rounds<R: Rounds>(v: &[__m256i; 3], c: &[__m256i; N]) -> [[__m256i; 4]; N] {
let mut vs: [[__m256i; 4]; N] = [[_mm256_setzero_si256(); 4]; N];
for i in 0..N {
vs[i] = [v[0], v[1], v[2], c[i]];
}
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
double_quarter_round(&mut vs);
}
### external/vendor/chacha20/src/backends/avx512.rs
@@ -0,0 +1,625 @@
+#![allow(unsafe_op_in_unsafe_fn)]
+use crate::{Rounds, Variant};
+use core::marker::PhantomData;
+
+#[cfg(feature = "cipher")]
+use crate::{STATE_WORDS, chacha::Block};
+
+#[cfg(feature = "cipher")]
+use cipher::{
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U16, U64},
+};
+
+#[cfg(target_arch = "x86")]
+use core::arch::x86::*;
+#[cfg(target_arch = "x86_64")]
+use core::arch::x86_64::*;
+
+/// Maximum number of blocks processed in parallel.
+/// We also support 8 and 4 in gen_tail_blocks.
+const MAX_PAR_BLOCKS: usize = 16;
+
+/// Divisor to compute `N`, the number of __m512i needed
+/// to represent a number of parallel blocks.
+const BLOCKS_PER_VECTOR: usize = 4;
+
+const MAX_N: usize = MAX_PAR_BLOCKS / BLOCKS_PER_VECTOR;
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+#[cfg(feature = "cipher")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
+where
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
+{
+ let simd_state = state.as_mut_ptr().cast::<i32>();
+
+ let mut backend = Backend::<R, V> {
+ state: [
+ _mm_loadu_epi32(simd_state),
+ _mm_loadu_epi32(simd_state.add(4)),
+ _mm_loadu_epi32(simd_state.add(8)),
+ ],
+ ctr: _mm_loadu_epi32(simd_state.add(12)),
+ _pd: PhantomData,
+ };
+
+ f.call(&mut backend);
+
+ // Update counter in the persistent state
+ state[12] = _mm_extract_epi32::<0>(backend.ctr) as u32;
+ if size_of::<V::Counter>() == 8 {
+ state[13] = _mm_extract_epi32::<1>(backend.ctr) as u32;
+ }
+}
+
+struct Backend<R: Rounds, V: Variant> {
+ state: [__m128i; 3],
+ ctr: __m128i,
+ _pd: PhantomData<(R, V)>,
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn increment_ctr(&mut self, amount: usize) {
+ match size_of::<V::Counter>() {
+ 4 => {
+ self.ctr = _mm_add_epi32(self.ctr, _mm_set_epi32(0, 0, 0, amount as i32));
+ }
+ 8 => {
+ self.ctr = _mm_add_epi64(self.ctr, _mm_set_epi64x(0, amount as i64));
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ /// Generates blocks using the 512-bit-wide dispatch
+ /// with up to `N` vectors processed in parallel, producing
+ /// `N * BLOCKS_PER_VECTOR` blocks.
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn gen_blocks_fullwidth<const N: usize>(&mut self, blocks: &mut [Block]) {
+ let par_blocks = N * BLOCKS_PER_VECTOR;
+ assert!(blocks.len() <= par_blocks);
+
+ let mut ctrs = [_mm512_broadcast_i32x4(self.ctr); N];
+ for i in 0..ctrs.len() {
+ match size_of::<V::Counter>() {
+ 4 => {
+ ctrs[i] = _mm512_add_epi32(
+ ctrs[i],
+ _mm512_set_epi32(
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 3) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 2) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 1) as i32,
+ 0,
+ 0,
+ 0,
+ (i * BLOCKS_PER_VECTOR) as i32,
+ ),
+ );
+ }
+ 8 => {
+ ctrs[i] = _mm512_add_epi64(
+ ctrs[i],
+ _mm512_set_epi64(
+ 0,
+ (i * BLOCKS_PER_VECTOR + 3) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 2) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR + 1) as i64,
+ 0,
+ (i * BLOCKS_PER_VECTOR) as i64,
+ ),
+ );
+ }
+ _ => unreachable!(),
+ }
+ }
+
+ self.increment_ctr(blocks.len());
+
+ let result = rounds::<N, R>(&self.state.map(|v| _mm512_broadcast_i32x4(v)), &ctrs);
+
+ for i in 0..N {
+ let result_vectors = result[i];
+
+ // We have our data in SIMD vectors in the following layout
+ // (using a, b, c, and d to indicate the resp. 4 rows of each block,
+ // and Bn to denote the nth block):
+ // result_vectors[0]:
+ // B0a0 B0a1 B0a2 B0a3
+ // B1a0 B1a1 B1a2 B1a3
+ // ...
+ // B3a0 B3a1 B3a2 B3a2
+ //
+ // result_vectors[1]:
+ // B0b0 B0b1 B0b2 B0b3
+ // B1b0 B1b1 B1b2 B1b3
+ // ...
+ // B3b0 B3b1 B3b2 B3b2
+ //
+ // and so on for result_vectors[2] (storing c values) and result_vectors[3] (storing d values).
+ //
+ // To store to memory, we need to transpose to the following format:
+ // transposed[0]:
+ // B0a0 B0a1 B0a2 B0a3
+ // B0b0 B0b1 B0b2 B0b3
+ // B0c0 B0c1 B0c2 B0c3
+ // B0d0 B0d1 B0d2 B0d3
+ //
+ // and so on, such that each 512-bit SIMD vector
+ // contains a single contiguous block.
+ //
+ // We achieve this transposition using the following
+ // sequence of shuffles.
+
+ let temp_abab_block01 = _mm512_permutex2var_epi64(
+ result_vectors[0],
+ _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11),
+ result_vectors[1],
+ );
+ let temp_abab_block23 = _mm512_permutex2var_epi64(
+ result_vectors[0],
+ _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15),
+ result_vectors[1],
+ );
+
+ let temp_cdcd_block01 = _mm512_permutex2var_epi64(
+ result_vectors[2],
+ _mm512_setr_epi64(0, 1, 8, 9, 2, 3, 10, 11),
+ result_vectors[3],
+ );
+ let temp_cdcd_block23 = _mm512_permutex2var_epi64(
+ result_vectors[2],
+ _mm512_setr_epi64(4, 5, 12, 13, 6, 7, 14, 15),
+ result_vectors[3],
+ );
+
+ let block0 =
+ _mm512_shuffle_i32x4::<0b01_00_01_00>(temp_abab_block01, temp_cdcd_block01);
+ let block1 =
+ _mm512_shuffle_i32x4::<0b11_10_11_10>(temp_abab_block01, temp_cdcd_block01);
+ let block2 =
+ _mm512_shuffle_i32x4::<0b01_00_01_00>(temp_abab_block23, temp_cdcd_block23);
+ let block3 =
+ _mm512_shuffle_i32x4::<0b11_10_11_10>(temp_abab_block23, temp_cdcd_block23);
+
+ for (j, src_block) in [block0, block1, block2, block3].into_iter().enumerate() {
+ let dst_index = i * BLOCKS_PER_VECTOR + j;
+ if dst_index < blocks.len() {
+ _mm512_storeu_si512((&raw mut blocks[dst_index]).cast(), src_block);
+ }
+ }
+ }
+ }
+
+ /// Generates up to 2 blocks using 256-bit vectors.
+ #[inline]
+ #[target_feature(enable = "avx512f", enable = "avx512vl")]
+ unsafe fn gen_blocks_halfwidth(&mut self, blocks: &mut [Block]) {
+ assert!(blocks.len() <= 2);
+
+ let mut ctr = _mm256_broadcast_i32x4(self.ctr);
+
+ match size_of::<V::Counter>() {
+ 4 => {
+ ctr = _mm256_add_epi32(ctr, _mm256_set_epi32(0, 0, 0, 1, 0, 0, 0, 0));
+ }
+ 8 => {
+ ctr = _mm256_add_epi64(ctr, _mm256_set_epi64x(0, 1, 0, 0));
+ }
+ _ => unreachable!(),
+ }
+
+ self.increment_ctr(blocks.len());
+
+ let block_vectors = rounds_halfwide::<R>([
+ _mm256_broadcast_i32x4(self.state[0]),
+ _mm256_broadcast_i32x4(self.state[1]),
+ _mm256_broadcast_i32x4(self.state[2]),
+ ctr,
+ ]);
+
+ // Similar transpose operation as
+ // in gen_blocks_fullwidth.
+
+ let block0_ab = _mm256_permutex2var_epi64(
+ block_vectors[0],
+ _mm256_setr_epi64x(0, 1, 4, 5),
+ block_vectors[1],
+ );
+ let block0_cd = _mm256_permutex2var_epi64(
+ block_vectors[2],
+ _mm256_setr_epi64x(0, 1, 4, 5),
+ block_vectors[3],
+ );
+ let block1_ab = _mm256_permutex2var_epi64(
+ block_vectors[0],
+ _mm256_setr_epi64x(2, 3, 6, 7),
+ block_vectors[1],
+ );
+ let block1_cd = _mm256_permutex2var_epi64(
+ block_vectors[2],
+ _mm256_setr_epi64x(2, 3, 6, 7),
+ block_vectors[3],
+ );
+
+ for (i, (block_part_ab, block_part_cd)) in [(block0_ab, block0_cd), (block1_ab, block1_cd)]
+ .into_iter()
+ .enumerate()
+ {
+ if i < blocks.len() {
+ let dst = (&raw mut blocks[i]).cast::<i32>();
+ _mm256_storeu_epi32(dst, block_part_ab);
+ _mm256_storeu_epi32(
+ dst.add(size_of::<Block>() / 2 / size_of::<i32>()),
+ block_part_cd,
+ );
+ }
+ }
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
+ type BlockSize = U64;
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ type ParBlocksSize = U16;
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
+ #[inline]
+ fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks<Self>) {
+ unsafe { self.gen_blocks_fullwidth::<MAX_N>(blocks) }
+ }
+
+ #[inline(always)]
+ fn gen_ks_block(&mut self, block: &mut Block) {
+ // Fallback for generating a single block using quarter-width vectors
+ // (128).
+
+ unsafe {
+ let state = [self.state[0], self.state[1], self.state[2], self.ctr];
+
+ self.increment_ctr(1);
+
+ let result = rounds_quarterwide::<R>(state);
+
+ for row in 0..4 {
+ let dst = block.as_mut_ptr().cast::<i32>().add(row * 4);
+ _mm_storeu_epi32(dst, result[row]);
+ }
+ }
+ }
+
+ #[inline]
+ fn gen_tail_blocks(&mut self, blocks: &mut [cipher::Block<Self>]) {
+ assert!(blocks.len() < MAX_PAR_BLOCKS);
+
+ if blocks.is_empty() {
+ return;
+ }
+
+ // Fallback for generating a number of blocks less than
+ // MAX_PAR_BLOCKS.
+ unsafe {
+ if blocks.len() == 1 {
+ self.gen_ks_block(&mut blocks[0]);
+ } else if blocks.len() == 2 {
+ self.gen_blocks_halfwidth(blocks);
+ } else if blocks.len() <= 4 {
+ self.gen_blocks_fullwidth::<1>(blocks);
+ } else if blocks.len() <= 8 {
+ self.gen_blocks_fullwidth::<2>(blocks);
+ } else {
+ self.gen_blocks_fullwidth::<MAX_N>(blocks);
+ }
+ }
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn rounds<const N: usize, R: Rounds>(
+ v: &[__m512i; 3],
+ c: &[__m512i; N],
+) -> [[__m512i; 4]; N] {
+ let mut vs: [[__m512i; 4]; N] = [[_mm512_setzero_si512(); 4]; N];
+ for i in 0..N {
+ vs[i] = [v[0], v[1], v[2], c[i]];
+ }
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut vs);
+ }
+
+ for i in 0..N {
+ for j in 0..3 {
+ vs[i][j] = _mm512_add_epi32(vs[i][j], v[j]);
+ }
+ vs[i][3] = _mm512_add_epi32(vs[i][3], c[i]);
+ }
+
+ vs
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn double_quarter_round<const N: usize>(v: &mut [[__m512i; 4]; N]) {
+ add_xor_rot(v);
+ rows_to_cols(v);
+ add_xor_rot(v);
+ cols_to_rows(v);
+}
+
+/// The goal of this function is to transform the state words from:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c0, c1, c2, c3] [ 8, 9, 10, 11]
+/// [d0, d1, d2, d3] [12, 13, 14, 15]
+/// ```
+///
+/// to:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b1, b2, b3, b0] == [ 5, 6, 7, 4]
+/// [c2, c3, c0, c1] [10, 11, 8, 9]
+/// [d3, d0, d1, d2] [15, 12, 13, 14]
+/// ```
+///
+/// so that we can apply [`add_xor_rot`] to the resulting columns, and have it compute the
+/// "diagonal rounds" (as defined in RFC 7539) in parallel. In practice, this shuffle is
+/// non-optimal: the last state word to be altered in `add_xor_rot` is `b`, so the shuffle
+/// blocks on the result of `b` being calculated.
+///
+/// We can optimize this by observing that the four quarter rounds in `add_xor_rot` are
+/// data-independent: they only access a single column of the state, and thus the order of
+/// the columns does not matter. We therefore instead shuffle the other three state words,
+/// to obtain the following equivalent layout:
+/// ```text
+/// [a3, a0, a1, a2] [ 3, 0, 1, 2]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c1, c2, c3, c0] [ 9, 10, 11, 8]
+/// [d2, d3, d0, d1] [14, 15, 12, 13]
+/// ```
+///
+/// See https://github.com/sneves/blake2-avx2/pull/4 for additional details. The earliest
+/// known occurrence of this optimization is in floodyberry's SSE4 ChaCha code from 2014:
+/// - https://github.com/floodyberry/chacha-opt/blob/0ab65cb99f5016633b652edebaf3691ceb4ff753/chacha_blocks_ssse3-64.S#L639-L643
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn rows_to_cols<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ for [a, _, c, d] in vs {
+ *c = _mm512_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm512_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm512_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+ }
+}
+
+/// The goal of this function is to transform the state words from:
+/// ```text
+/// [a3, a0, a1, a2] [ 3, 0, 1, 2]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c1, c2, c3, c0] [ 9, 10, 11, 8]
+/// [d2, d3, d0, d1] [14, 15, 12, 13]
+/// ```
+///
+/// to:
+/// ```text
+/// [a0, a1, a2, a3] [ 0, 1, 2, 3]
+/// [b0, b1, b2, b3] == [ 4, 5, 6, 7]
+/// [c0, c1, c2, c3] [ 8, 9, 10, 11]
+/// [d0, d1, d2, d3] [12, 13, 14, 15]
+/// ```
+///
+/// reversing the transformation of [`rows_to_cols`].
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn cols_to_rows<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ for [a, _, c, d] in vs {
+ *c = _mm512_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm512_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm512_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+ }
+}
+
+#[inline]
+#[target_feature(enable = "avx512f")]
+unsafe fn add_xor_rot<const N: usize>(vs: &mut [[__m512i; 4]; N]) {
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ for [a, b, _, d] in vs.iter_mut() {
+ *a = _mm512_add_epi32(*a, *b);
+ *d = _mm512_xor_si512(*d, *a);
+ *d = _mm512_rol_epi32::<16>(*d);
+ }
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ for [_, b, c, d] in vs.iter_mut() {
+ *c = _mm512_add_epi32(*c, *d);
+ *b = _mm512_xor_si512(*b, *c);
+ *b = _mm512_rol_epi32::<12>(*b);
+ }
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ for [a, b, _, d] in vs.iter_mut() {
+ *a = _mm512_add_epi32(*a, *b);
+ *d = _mm512_xor_si512(*d, *a);
+ *d = _mm512_rol_epi32::<8>(*d);
+ }
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ for [_, b, c, d] in vs.iter_mut() {
+ *c = _mm512_add_epi32(*c, *d);
+ *b = _mm512_xor_si512(*b, *c);
+ *b = _mm512_rol_epi32::<7>(*b);
+ }
+}
+
+// Below is another implementation of the round application
+// that uses 256-bit vectors instead of 512-bit (but, unlike
+// the avx2 module, can use new AVX-512 instructions like rotates).
+// It is used for tail processing of shorter outputs,
+// since 256-bit instructions can be faster and lower latency
+// than 512-bit instructions on certain microarchitectures (e.g. Zen 4).
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn rounds_halfwide<R: Rounds>(v_in: [__m256i; 4]) -> [__m256i; 4] {
+ let mut v = v_in;
+
+ for _ in 0..R::COUNT {
+ double_quarter_round_halfwide(&mut v);
+ }
+
+ for (a, b) in v.iter_mut().zip(v_in) {
+ *a = _mm256_add_epi32(*a, b);
+ }
+
+ v
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn double_quarter_round_halfwide(v: &mut [__m256i; 4]) {
+ add_xor_rot_halfwide(v);
+ rows_to_cols_halfwide(v);
+ add_xor_rot_halfwide(v);
+ cols_to_rows_halfwide(v);
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn rows_to_cols_halfwide(v: &mut [__m256i; 4]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ let [a, _, c, d] = v;
+ *c = _mm256_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm256_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm256_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn cols_to_rows_halfwide(v: &mut [__m256i; 4]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ let [a, _, c, d] = v;
+ *c = _mm256_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm256_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm256_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+}
+
+#[inline]
+#[target_feature(enable = "avx512f", enable = "avx512vl")]
+unsafe fn add_xor_rot_halfwide(v: &mut [__m256i; 4]) {
+ let [a, b, c, d] = v;
+
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm256_add_epi32(*a, *b);
+ *d = _mm256_xor_si256(*d, *a);
+ *d = _mm256_rol_epi32::<16>(*d);
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm256_add_epi32(*c, *d);
+ *b = _mm256_xor_si256(*b, *c);
+ *b = _mm256_rol_epi32::<12>(*b);
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm256_add_epi32(*a, *b);
+ *d = _mm256_xor_si256(*d, *a);
+ *d = _mm256_rol_epi32::<8>(*d);
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm256_add_epi32(*c, *d);
+ *b = _mm256_xor_si256(*b, *c);
+ *b = _mm256_rol_epi32::<7>(*b);
+}
+
+// Finally, below is an implementation using 128-bit vectors
+// for the case of generating a single block.
+
+#[inline(always)]
+unsafe fn rounds_quarterwide<R: Rounds>(v_in: [__m128i; 4]) -> [__m128i; 4] {
+ let mut v = v_in;
+
+ for _ in 0..R::COUNT {
+ double_quarter_round_quarterwide(&mut v);
+ }
+
+ for (a, b) in v.iter_mut().zip(v_in) {
+ *a = _mm_add_epi32(*a, b);
+ }
+
+ v
+}
+
+#[inline(always)]
+unsafe fn double_quarter_round_quarterwide(v: &mut [__m128i; 4]) {
+ add_xor_rot_quarterwide(v);
+ rows_to_cols_quarterwide(v);
+ add_xor_rot_quarterwide(v);
+ cols_to_rows_quarterwide(v);
+}
+
+#[inline(always)]
+unsafe fn rows_to_cols_quarterwide(v: &mut [__m128i; 4]) {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ let [a, _, c, d] = v;
+ *c = _mm_shuffle_epi32::<0b_00_11_10_01>(*c); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32::<0b_10_01_00_11>(*a); // _MM_SHUFFLE(2, 1, 0, 3)
+}
+
+#[inline(always)]
+unsafe fn cols_to_rows_quarterwide(v: &mut [__m128i; 4]) {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ let [a, _, c, d] = v;
+ *c = _mm_shuffle_epi32::<0b_10_01_00_11>(*c); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm_shuffle_epi32::<0b_01_00_11_10>(*d); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32::<0b_00_11_10_01>(*a); // _MM_SHUFFLE(0, 3, 2, 1)
+}
+
+#[inline(always)]
+unsafe fn add_xor_rot_quarterwide(v: &mut [__m128i; 4]) {
+ let [a, b, c, d] = v;
+
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_rol_epi32::<16>(*d);
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_rol_epi32::<12>(*b);
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_rol_epi32::<8>(*d);
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_rol_epi32::<7>(*b);
+}
### external/vendor/chacha20/src/backends/neon.rs
@@ -1,356 +1,364 @@
//! NEON-optimized implementation for aarch64 CPUs.
//!
//! Adapted from the Crypto++ `chacha_simd` implementation by Jack Lloyd and
-//! Jeffrey Walton (public domain).
+//! Jeffrey Walton (public domain), but uses **8-block** outer batches for
+//! bulk paths (see `ChaCha20_512_neon` in OpenSSL).
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+
+use crate::{Rounds, STATE_WORDS, Variant};
+use core::{arch::aarch64::*, marker::PhantomData};
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+
+#[cfg(feature = "cipher")]
use cipher::{
- consts::{U4, U64},
- BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamBackend,
+ BlockSizeUser, ParBlocks, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U8, U64},
};
-use core::{arch::aarch64::*, marker::PhantomData};
-#[inline]
-#[target_feature(enable = "neon")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
-where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
-{
- let mut backend = Backend::<R> {
- state: [
+struct Backend<R: Rounds, V: Variant> {
+ state: [uint32x4_t; 4],
+ ctrs: [uint32x4_t; 8],
+ _pd: PhantomData<(R, V)>,
+}
+
+macro_rules! add_counter {
+ ($a:expr, $b:expr, $variant:ty) => {
+ match size_of::<<$variant>::Counter>() {
+ 4 => vaddq_u32($a, $b),
+ 8 => vreinterpretq_u32_u64(vaddq_u64(
+ vreinterpretq_u64_u32($a),
+ vreinterpretq_u64_u32($b),
+ )),
+ _ => unreachable!(),
+ }
+ };
+}
+
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline]
+ unsafe fn new(state: &mut [u32; STATE_WORDS]) -> Self {
+ let state = [
vld1q_u32(state.as_ptr().offset(0)),
vld1q_u32(state.as_ptr().offset(4)),
vld1q_u32(state.as_ptr().offset(8)),
vld1q_u32(state.as_ptr().offset(12)),
- ],
- _pd: PhantomData,
- };
+ ];
+ let ctrs = [
+ vld1q_u32([1, 0, 0, 0].as_ptr()),
+ vld1q_u32([2, 0, 0, 0].as_ptr()),
+ vld1q_u32([3, 0, 0, 0].as_ptr()),
+ vld1q_u32([4, 0, 0, 0].as_ptr()),
+ vld1q_u32([5, 0, 0, 0].as_ptr()),
+ vld1q_u32([6, 0, 0, 0].as_ptr()),
+ vld1q_u32([7, 0, 0, 0].as_ptr()),
+ vld1q_u32([8, 0, 0, 0].as_ptr()),
+ ];
+ Backend::<R, V> {
+ state,
+ ctrs,
+ _pd: PhantomData,
+ }
+ }
+}
+
+#[inline]
+#[cfg(feature = "cipher")]
+#[target_feature(enable = "neon")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
+where
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(state);
f.call(&mut backend);
- vst1q_u32(state.as_mut_ptr().offset(12), backend.state[3]);
+ match size_of::<V::Counter>() {
+ 4 => state[12] = vgetq_lane_u32(backend.state[3], 0),
+ 8 => vst1q_u64(
+ state.as_mut_ptr().offset(12).cast::<u64>(),
+ vreinterpretq_u64_u32(backend.state[3]),
+ ),
+ _ => unreachable!(),
+ }
}
-struct Backend<R: Unsigned> {
- state: [uint32x4_t; 4],
- _pd: PhantomData<R>,
+/// Sets up backend and blindly writes 4 blocks to dest_ptr.
+#[cfg(feature = "rng")]
+#[inline]
+#[target_feature(enable = "neon")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(&mut core.state);
+
+ backend.write_par_ks_blocks(buffer);
+
+ vst1q_u64(
+ core.state.as_mut_ptr().offset(12).cast::<u64>(),
+ vreinterpretq_u64_u32(backend.state[3]),
+ );
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
- type ParBlocksSize = U4;
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ /// Match OpenSSL's large-buffer path: 8 blocks
+ type ParBlocksSize = U8;
}
-macro_rules! add64 {
+/// Evaluates to `a = a + b`, where the operands are u32x4s
+macro_rules! add_assign_vec {
($a:expr, $b:expr) => {
- vreinterpretq_u32_u64(vaddq_u64(
- vreinterpretq_u64_u32($a),
- vreinterpretq_u64_u32($b),
- ))
+ $a = vaddq_u32($a, $b)
};
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
let state3 = self.state[3];
let mut par = ParBlocks::<Self>::default();
self.gen_par_ks_blocks(&mut par);
*block = par[0];
+
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- self.state[3] = add64!(state3, vld1q_u32([1, 0, 0, 0].as_ptr()));
+ self.state[3] = add_counter!(state3, vld1q_u32([1, 0, 0, 0].as_ptr()), V);
}
}
#[inline(always)]
- fn gen_par_ks_blocks(&mut self, blocks: &mut ParBlocks<Self>) {
- macro_rules! rotate_left {
- ($v:ident, 8) => {{
- let maskb = [3u8, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14];
- let mask = vld1q_u8(maskb.as_ptr());
-
- vreinterpretq_u32_u8(vqtbl1q_u8(vreinterpretq_u8_u32($v), mask))
- }};
- ($v:ident, 16) => {
- vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32($v)))
- };
- ($v:ident, $r:literal) => {
- vorrq_u32(vshlq_n_u32($v, $r), vshrq_n_u32($v, 32 - $r))
- };
- }
-
- macro_rules! extract {
- ($v:ident, $s:literal) => {
- vextq_u32($v, $v, $s)
- };
- }
-
+ fn gen_par_ks_blocks(&mut self, dest: &mut ParBlocks<Self>) {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- let ctrs = [
- vld1q_u32([1, 0, 0, 0].as_ptr()),
- vld1q_u32([2, 0, 0, 0].as_ptr()),
- vld1q_u32([3, 0, 0, 0].as_ptr()),
- vld1q_u32([4, 0, 0, 0].as_ptr()),
+ let mut blocks = [
+ [self.state[0], self.state[1], self.state[2], self.state[3]],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[0], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[1], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[2], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[3], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[4], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[5], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[6], V),
+ ],
];
- let mut r0_0 = self.state[0];
- let mut r0_1 = self.state[1];
- let mut r0_2 = self.state[2];
- let mut r0_3 = self.state[3];
-
- let mut r1_0 = self.state[0];
- let mut r1_1 = self.state[1];
- let mut r1_2 = self.state[2];
- let mut r1_3 = add64!(r0_3, ctrs[0]);
-
- let mut r2_0 = self.state[0];
- let mut r2_1 = self.state[1];
- let mut r2_2 = self.state[2];
- let mut r2_3 = add64!(r0_3, ctrs[1]);
-
- let mut r3_0 = self.state[0];
- let mut r3_1 = self.state[1];
- let mut r3_2 = self.state[2];
- let mut r3_3 = add64!(r0_3, ctrs[2]);
-
- for _ in 0..R::USIZE {
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 16);
- r1_3 = rotate_left!(r1_3, 16);
- r2_3 = rotate_left!(r2_3, 16);
- r3_3 = rotate_left!(r3_3, 16);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 12);
- r1_1 = rotate_left!(r1_1, 12);
- r2_1 = rotate_left!(r2_1, 12);
- r3_1 = rotate_left!(r3_1, 12);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 8);
- r1_3 = rotate_left!(r1_3, 8);
- r2_3 = rotate_left!(r2_3, 8);
- r3_3 = rotate_left!(r3_3, 8);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 7);
- r1_1 = rotate_left!(r1_1, 7);
- r2_1 = rotate_left!(r2_1, 7);
- r3_1 = rotate_left!(r3_1, 7);
-
- r0_1 = extract!(r0_1, 1);
- r0_2 = extract!(r0_2, 2);
- r0_3 = extract!(r0_3, 3);
-
- r1_1 = extract!(r1_1, 1);
- r1_2 = extract!(r1_2, 2);
- r1_3 = extract!(r1_3, 3);
-
- r2_1 = extract!(r2_1, 1);
- r2_2 = extract!(r2_2, 2);
- r2_3 = extract!(r2_3, 3);
-
- r3_1 = extract!(r3_1, 1);
- r3_2 = extract!(r3_2, 2);
- r3_3 = extract!(r3_3, 3);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 16);
- r1_3 = rotate_left!(r1_3, 16);
- r2_3 = rotate_left!(r2_3, 16);
- r3_3 = rotate_left!(r3_3, 16);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 12);
- r1_1 = rotate_left!(r1_1, 12);
- r2_1 = rotate_left!(r2_1, 12);
- r3_1 = rotate_left!(r3_1, 12);
-
- r0_0 = vaddq_u32(r0_0, r0_1);
- r1_0 = vaddq_u32(r1_0, r1_1);
- r2_0 = vaddq_u32(r2_0, r2_1);
- r3_0 = vaddq_u32(r3_0, r3_1);
-
- r0_3 = veorq_u32(r0_3, r0_0);
- r1_3 = veorq_u32(r1_3, r1_0);
- r2_3 = veorq_u32(r2_3, r2_0);
- r3_3 = veorq_u32(r3_3, r3_0);
-
- r0_3 = rotate_left!(r0_3, 8);
- r1_3 = rotate_left!(r1_3, 8);
- r2_3 = rotate_left!(r2_3, 8);
- r3_3 = rotate_left!(r3_3, 8);
-
- r0_2 = vaddq_u32(r0_2, r0_3);
- r1_2 = vaddq_u32(r1_2, r1_3);
- r2_2 = vaddq_u32(r2_2, r2_3);
- r3_2 = vaddq_u32(r3_2, r3_3);
-
- r0_1 = veorq_u32(r0_1, r0_2);
- r1_1 = veorq_u32(r1_1, r1_2);
- r2_1 = veorq_u32(r2_1, r2_2);
- r3_1 = veorq_u32(r3_1, r3_2);
-
- r0_1 = rotate_left!(r0_1, 7);
- r1_1 = rotate_left!(r1_1, 7);
- r2_1 = rotate_left!(r2_1, 7);
- r3_1 = rotate_left!(r3_1, 7);
-
- r0_1 = extract!(r0_1, 3);
- r0_2 = extract!(r0_2, 2);
- r0_3 = extract!(r0_3, 1);
-
- r1_1 = extract!(r1_1, 3);
- r1_2 = extract!(r1_2, 2);
- r1_3 = extract!(r1_3, 1);
-
- r2_1 = extract!(r2_1, 3);
- r2_2 = extract!(r2_2, 2);
- r2_3 = extract!(r2_3, 1);
-
- r3_1 = extract!(r3_1, 3);
- r3_2 = extract!(r3_2, 2);
- r3_3 = extract!(r3_3, 1);
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut blocks);
}
- r0_0 = vaddq_u32(r0_0, self.state[0]);
- r0_1 = vaddq_u32(r0_1, self.state[1]);
- r0_2 = vaddq_u32(r0_2, self.state[2]);
- r0_3 = vaddq_u32(r0_3, self.state[3]);
-
- r1_0 = vaddq_u32(r1_0, self.state[0]);
- r1_1 = vaddq_u32(r1_1, self.state[1]);
- r1_2 = vaddq_u32(r1_2, self.state[2]);
- r1_3 = vaddq_u32(r1_3, self.state[3]);
- r1_3 = add64!(r1_3, ctrs[0]);
-
- r2_0 = vaddq_u32(r2_0, self.state[0]);
- r2_1 = vaddq_u32(r2_1, self.state[1]);
- r2_2 = vaddq_u32(r2_2, self.state[2]);
- r2_3 = vaddq_u32(r2_3, self.state[3]);
- r2_3 = add64!(r2_3, ctrs[1]);
-
- r3_0 = vaddq_u32(r3_0, self.state[0]);
- r3_1 = vaddq_u32(r3_1, self.state[1]);
- r3_2 = vaddq_u32(r3_2, self.state[2]);
- r3_3 = vaddq_u32(r3_3, self.state[3]);
- r3_3 = add64!(r3_3, ctrs[2]);
-
- vst1q_u8(blocks[0].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r0_0));
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r0_1),
- );
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r0_2),
- );
- vst1q_u8(
- blocks[0].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r0_3),
- );
-
- vst1q_u8(blocks[1].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r1_0));
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r1_1),
- );
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r1_2),
- );
- vst1q_u8(
- blocks[1].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r1_3),
- );
-
- vst1q_u8(blocks[2].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r2_0));
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r2_1),
- );
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r2_2),
- );
- vst1q_u8(
- blocks[2].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r2_3),
- );
-
- vst1q_u8(blocks[3].as_mut_ptr().offset(0), vreinterpretq_u8_u32(r3_0));
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(16),
- vreinterpretq_u8_u32(r3_1),
- );
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(2 * 16),
- vreinterpretq_u8_u32(r3_2),
- );
- vst1q_u8(
- blocks[3].as_mut_ptr().offset(3 * 16),
- vreinterpretq_u8_u32(r3_3),
- );
-
- self.state[3] = add64!(self.state[3], ctrs[3]);
+ for block in 0..8 {
+ // add state to block
+ for state_row in 0..3 {
+ add_assign_vec!(blocks[block][state_row], self.state[state_row]);
+ }
+ if block > 0 {
+ add_assign_vec!(
+ blocks[block][3],
+ add_counter!(self.state[3], self.ctrs[block - 1], V)
+ );
+ } else {
+ add_assign_vec!(blocks[block][3], self.state[3]);
+ }
+ // write blocks to dest
+ for state_row in 0..4 {
+ vst1q_u8(
+ dest[block].as_mut_ptr().add(state_row << 4),
+ vreinterpretq_u8_u32(blocks[block][state_row]),
+ );
+ }
+ }
+ self.state[3] = add_counter!(self.state[3], self.ctrs[7], V);
}
}
}
+
+macro_rules! rotate_left {
+ ($v:expr, 8) => {{
+ let maskb = [3u8, 0, 1, 2, 7, 4, 5, 6, 11, 8, 9, 10, 15, 12, 13, 14];
+ let mask = vld1q_u8(maskb.as_ptr());
+
+ $v = vreinterpretq_u32_u8(vqtbl1q_u8(vreinterpretq_u8_u32($v), mask))
+ }};
+ ($v:expr, 16) => {
+ $v = vreinterpretq_u32_u16(vrev32q_u16(vreinterpretq_u16_u32($v)))
+ };
+ ($v:expr, $r:literal) => {
+ $v = vorrq_u32(vshlq_n_u32($v, $r), vshrq_n_u32($v, 32 - $r))
+ };
+}
+
+macro_rules! extract {
+ ($v:expr, $s:literal) => {
+ $v = vextq_u32($v, $v, $s)
+ };
+}
+
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ /// Generates `num_blocks` blocks and blindly writes them to `dest_ptr`
+ ///
+ /// `num_blocks` must be greater than 0, and less than or equal to 4.
+ ///
+ /// # Safety
+ /// `dest_ptr` must have at least `64 * num_blocks` bytes available to be
+ /// overwritten, or else it could produce undefined behavior
+ #[cfg(feature = "rng")]
+ unsafe fn write_par_ks_blocks(&mut self, buffer: &mut [u32; 64]) {
+ let mut blocks = [
+ [self.state[0], self.state[1], self.state[2], self.state[3]],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[0], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[1], V),
+ ],
+ [
+ self.state[0],
+ self.state[1],
+ self.state[2],
+ add_counter!(self.state[3], self.ctrs[2], V),
+ ],
+ ];
+
+ for _ in 0..R::COUNT {
+ double_quarter_round(&mut blocks);
+ }
+
+ let mut dest_ptr = buffer.as_mut_ptr().cast::<u8>();
+ for block in 0..4 {
+ // add state to block
+ for state_row in 0..3 {
+ add_assign_vec!(blocks[block][state_row], self.state[state_row]);
+ }
+ if block > 0 {
+ add_assign_vec!(
+ blocks[block][3],
+ add_counter!(self.state[3], self.ctrs[block - 1], V)
+ );
+ } else {
+ add_assign_vec!(blocks[block][3], self.state[3]);
+ }
+ // write blocks to buffer
+ for state_row in 0..4 {
+ #[allow(clippy::cast_sign_loss)]
+ vst1q_u8(
+ dest_ptr.offset(state_row << 4),
+ vreinterpretq_u8_u32(blocks[block][state_row as usize]),
+ );
+ }
+ dest_ptr = dest_ptr.add(64);
+ }
+ self.state[3] = add_counter!(self.state[3], self.ctrs[3], V);
+ }
+}
+
+#[inline]
+unsafe fn double_quarter_round<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ add_xor_rot(blocks);
+ rows_to_cols(blocks);
+ add_xor_rot(blocks);
+ cols_to_rows(blocks);
+}
+
+#[inline]
+unsafe fn add_xor_rot<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ /// Evaluates to `a = a ^ b`, where the operands are u32x4s
+ macro_rules! xor_assign_vec {
+ ($a:expr, $b:expr) => {
+ $a = veorq_u32($a, $b)
+ };
+ }
+ for block in blocks.iter_mut() {
+ // this part of the code cannot be reduced much more without having
+ // to deal with some problems regarding `rotate_left` requiring the second
+ // argument to be a const, and const arrays cannot be indexed by non-consts
+ add_assign_vec!(block[0], block[1]);
+ xor_assign_vec!(block[3], block[0]);
+ rotate_left!(block[3], 16);
+
+ add_assign_vec!(block[2], block[3]);
+ xor_assign_vec!(block[1], block[2]);
+ rotate_left!(block[1], 12);
+
+ add_assign_vec!(block[0], block[1]);
+ xor_assign_vec!(block[3], block[0]);
+ rotate_left!(block[3], 8);
+
+ add_assign_vec!(block[2], block[3]);
+ xor_assign_vec!(block[1], block[2]);
+ rotate_left!(block[1], 7);
+ }
+}
+
+#[inline]
+unsafe fn rows_to_cols<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ for block in blocks.iter_mut() {
+ extract!(block[1], 1);
+ extract!(block[2], 2);
+ extract!(block[3], 3);
+ }
+}
+
+#[inline]
+unsafe fn cols_to_rows<const N: usize>(blocks: &mut [[uint32x4_t; 4]; N]) {
+ for block in blocks.iter_mut() {
+ extract!(block[1], 3);
+ extract!(block[2], 2);
+ extract!(block[3], 1);
+ }
+}
### external/vendor/chacha20/src/backends/soft.rs
@@ -1,39 +1,72 @@
-//! Portable implementation which does not rely on architecture-specific
-//! intrinsics.
+//! Portable implementation which does not rely on architecture-specific intrinsics.
-use crate::{Block, ChaChaCore, Unsigned, STATE_WORDS};
+#![allow(clippy::cast_possible_truncation)]
+
+use crate::{ChaChaCore, Rounds, STATE_WORDS, Variant, quarter_round};
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+#[cfg(feature = "cipher")]
use cipher::{
+ BlockSizeUser, ParBlocksSizeUser, StreamCipherBackend,
consts::{U1, U64},
- BlockSizeUser, ParBlocksSizeUser, StreamBackend,
};
-pub(crate) struct Backend<'a, R: Unsigned>(pub(crate) &'a mut ChaChaCore<R>);
+#[cfg(feature = "rng")]
+use crate::rng::BLOCK_WORDS;
-impl<'a, R: Unsigned> BlockSizeUser for Backend<'a, R> {
+pub(crate) struct Backend<'a, R: Rounds, V: Variant>(pub(crate) &'a mut ChaChaCore<R, V>);
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<'_, R, V> {
type BlockSize = U64;
}
-impl<'a, R: Unsigned> ParBlocksSizeUser for Backend<'a, R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<'_, R, V> {
type ParBlocksSize = U1;
}
-impl<'a, R: Unsigned> StreamBackend for Backend<'a, R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<'_, R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
let res = run_rounds::<R>(&self.0.state);
- self.0.state[12] = self.0.state[12].wrapping_add(1);
+ let mut ctr = (u64::from(self.0.state[13]) << 32) | u64::from(self.0.state[12]);
+ ctr = ctr.wrapping_add(1);
+ self.0.state[12] = ctr as u32;
+ if size_of::<V::Counter>() == 8 {
+ self.0.state[13] = (ctr >> 32) as u32;
+ }
for (chunk, val) in block.chunks_exact_mut(4).zip(res.iter()) {
chunk.copy_from_slice(&val.to_le_bytes());
}
}
}
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<'_, R, V> {
+ #[inline(always)]
+ pub(crate) fn gen_ks_blocks(&mut self, buffer: &mut [u32; 64]) {
+ for block in 0..4 {
+ let res = run_rounds::<R>(&self.0.state);
+ let mut ctr = (u64::from(self.0.state[13]) << 32) | u64::from(self.0.state[12]);
+ ctr = ctr.wrapping_add(1);
+ self.0.state[12] = ctr as u32;
+ self.0.state[13] = (ctr >> 32) as u32;
+
+ buffer[block * BLOCK_WORDS as usize..(block + 1) * BLOCK_WORDS as usize]
+ .copy_from_slice(&res);
+ }
+ }
+}
+
#[inline(always)]
-fn run_rounds<R: Unsigned>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
+fn run_rounds<R: Rounds>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
let mut res = *state;
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
// column rounds
quarter_round(0, 4, 8, 12, &mut res);
quarter_round(1, 5, 9, 13, &mut res);
@@ -52,22 +85,3 @@ fn run_rounds<R: Unsigned>(state: &[u32; STATE_WORDS]) -> [u32; STATE_WORDS] {
}
res
}
-
-/// The ChaCha20 quarter round function
-fn quarter_round(a: usize, b: usize, c: usize, d: usize, state: &mut [u32; STATE_WORDS]) {
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(16);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(12);
-
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(8);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(7);
-}
### external/vendor/chacha20/src/backends/sse2.rs
@@ -1,7 +1,22 @@
-use crate::{Block, StreamClosure, Unsigned, STATE_WORDS};
+//! SSE2 backend.
+
+#![allow(unsafe_op_in_unsafe_fn, reason = "needs triage")]
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::cast_possible_wrap, reason = "needs triage")]
+#![allow(clippy::cast_sign_loss, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use crate::{Rounds, STATE_WORDS, Variant};
+
+#[cfg(feature = "rng")]
+use crate::ChaChaCore;
+
+#[cfg(feature = "cipher")]
+use crate::chacha::Block;
+#[cfg(feature = "cipher")]
use cipher::{
- consts::{U1, U64},
- BlockSizeUser, ParBlocksSizeUser, StreamBackend,
+ BlockSizeUser, ParBlocksSizeUser, StreamCipherBackend, StreamCipherClosure,
+ consts::{U4, U64},
};
use core::marker::PhantomData;
@@ -10,75 +25,157 @@ use core::arch::x86::*;
#[cfg(target_arch = "x86_64")]
use core::arch::x86_64::*;
+const PAR_BLOCKS: usize = 4;
+
#[inline]
#[target_feature(enable = "sse2")]
-pub(crate) unsafe fn inner<R, F>(state: &mut [u32; STATE_WORDS], f: F)
+#[cfg(feature = "cipher")]
+pub(crate) unsafe fn inner<R, F, V>(state: &mut [u32; STATE_WORDS], f: F)
where
- R: Unsigned,
- F: StreamClosure<BlockSize = U64>,
+ R: Rounds,
+ F: StreamCipherClosure<BlockSize = U64>,
+ V: Variant,
{
- let state_ptr = state.as_ptr() as *const __m128i;
- let mut backend = Backend::<R> {
- v: [
- _mm_loadu_si128(state_ptr.add(0)),
- _mm_loadu_si128(state_ptr.add(1)),
- _mm_loadu_si128(state_ptr.add(2)),
- _mm_loadu_si128(state_ptr.add(3)),
- ],
- _pd: PhantomData,
- };
-
+ let mut backend = Backend::<R, V>::new(state);
f.call(&mut backend);
+ backend.save_ctr(state);
+}
- state[12] = _mm_cvtsi128_si32(backend.v[3]) as u32;
+#[inline]
+#[target_feature(enable = "sse2")]
+#[cfg(feature = "rng")]
+pub(crate) unsafe fn rng_inner<R, V>(core: &mut ChaChaCore<R, V>, buffer: &mut [u32; 64])
+where
+ R: Rounds,
+ V: Variant,
+{
+ let mut backend = Backend::<R, V>::new(&core.state);
+ backend.gen_ks_blocks(buffer);
+ backend.save_ctr(&mut core.state);
}
-struct Backend<R: Unsigned> {
+struct Backend<R: Rounds, V: Variant> {
v: [__m128i; 4],
- _pd: PhantomData<R>,
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> BlockSizeUser for Backend<R> {
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ unsafe fn new(state: &[u32; STATE_WORDS]) -> Self {
+ let state_ptr = state.as_ptr().cast::<__m128i>();
+ Self {
+ v: core::array::from_fn(|i| _mm_loadu_si128(state_ptr.add(i))),
+ _pd: PhantomData,
+ }
+ }
+
+ unsafe fn save_ctr(self, state: &mut [u32; STATE_WORDS]) {
+ let state_ptr = state.as_mut_ptr().cast::<__m128i>();
+ _mm_storeu_si128(state_ptr.add(3), self.v[3]);
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for Backend<R, V> {
type BlockSize = U64;
}
-impl<R: Unsigned> ParBlocksSizeUser for Backend<R> {
- type ParBlocksSize = U1;
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> ParBlocksSizeUser for Backend<R, V> {
+ type ParBlocksSize = U4;
}
-impl<R: Unsigned> StreamBackend for Backend<R> {
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherBackend for Backend<R, V> {
#[inline(always)]
fn gen_ks_block(&mut self, block: &mut Block) {
unsafe {
- let res = rounds::<R>(&self.v);
- self.v[3] = _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, 1));
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, 1)),
+ 8 => _mm_add_epi64(self.v[3], _mm_set_epi64x(0, 1)),
+ _ => unreachable!(),
+ };
- let block_ptr = block.as_mut_ptr() as *mut __m128i;
+ let block_ptr = block.as_mut_ptr().cast::<__m128i>();
for i in 0..4 {
- _mm_storeu_si128(block_ptr.add(i), res[i]);
+ _mm_storeu_si128(block_ptr.add(i), res[0][i]);
+ }
+ }
+ }
+
+ #[inline(always)]
+ fn gen_par_ks_blocks(&mut self, blocks: &mut cipher::ParBlocks<Self>) {
+ unsafe {
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(self.v[3], _mm_set_epi32(0, 0, 0, PAR_BLOCKS as i32)),
+ 8 => _mm_add_epi64(self.v[3], _mm_set_epi64x(0, PAR_BLOCKS as i64)),
+ _ => unreachable!(),
+ };
+
+ let blocks_ptr = blocks.as_mut_ptr().cast::<__m128i>();
+ for block in 0..PAR_BLOCKS {
+ for i in 0..4 {
+ _mm_storeu_si128(blocks_ptr.add(i + block * PAR_BLOCKS), res[block][i]);
+ }
+ }
+ }
+ }
+}
+
+#[cfg(feature = "rng")]
+impl<R: Rounds, V: Variant> Backend<R, V> {
+ #[inline(always)]
+ fn gen_ks_blocks(&mut self, block: &mut [u32; 64]) {
+ const _: () = assert!(4 * PAR_BLOCKS * size_of::<__m128i>() == size_of::<[u32; 64]>());
+ unsafe {
+ let res = rounds::<R, V>(&self.v);
+ self.v[3] = _mm_add_epi64(self.v[3], _mm_set_epi64x(0, PAR_BLOCKS as i64));
+
+ let blocks_ptr = block.as_mut_ptr().cast::<__m128i>();
+ for block in 0..PAR_BLOCKS {
+ for i in 0..4 {
+ _mm_storeu_si128(blocks_ptr.add(i + block * PAR_BLOCKS), res[block][i]);
+ }
}
}
}
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn rounds<R: Unsigned>(v: &[__m128i; 4]) -> [__m128i; 4] {
- let mut res = *v;
- for _ in 0..R::USIZE {
+unsafe fn rounds<R: Rounds, V: Variant>(v: &[__m128i; 4]) -> [[__m128i; 4]; PAR_BLOCKS] {
+ let mut res = [*v; 4];
+ for block in 1..PAR_BLOCKS {
+ res[block][3] = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(res[block][3], _mm_set_epi32(0, 0, 0, block as i32)),
+ 8 => _mm_add_epi64(res[block][3], _mm_set_epi64x(0, block as i64)),
+ _ => unreachable!(),
+ }
+ }
+
+ for _ in 0..R::COUNT {
double_quarter_round(&mut res);
}
- for i in 0..4 {
- res[i] = _mm_add_epi32(res[i], v[i]);
+ for block in 0..PAR_BLOCKS {
+ for i in 0..3 {
+ res[block][i] = _mm_add_epi32(res[block][i], v[i]);
+ }
+ let ctr = match size_of::<V::Counter>() {
+ 4 => _mm_add_epi32(v[3], _mm_set_epi32(0, 0, 0, block as i32)),
+ 8 => _mm_add_epi64(v[3], _mm_set_epi64x(0, block as i64)),
+ _ => unreachable!(),
+ };
+ res[block][3] = _mm_add_epi32(res[block][3], ctr);
}
res
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn double_quarter_round(v: &mut [__m128i; 4]) {
+unsafe fn double_quarter_round(v: &mut [[__m128i; 4]; PAR_BLOCKS]) {
add_xor_rot(v);
rows_to_cols(v);
add_xor_rot(v);
@@ -122,11 +219,13 @@ unsafe fn double_quarter_round(v: &mut [__m128i; 4]) {
/// - https://github.com/floodyberry/chacha-opt/blob/0ab65cb99f5016633b652edebaf3691ceb4ff753/chacha_blocks_ssse3-64.S#L639-L643
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn rows_to_cols([a, _, c, d]: &mut [__m128i; 4]) {
- // c >>>= 32; d >>>= 64; a >>>= 96;
- *c = _mm_shuffle_epi32(*c, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
- *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
- *a = _mm_shuffle_epi32(*a, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+unsafe fn rows_to_cols(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, _, c, d] in blocks.iter_mut() {
+ // c >>>= 32; d >>>= 64; a >>>= 96;
+ *c = _mm_shuffle_epi32(*c, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+ *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32(*a, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+ }
}
/// The goal of this function is to transform the state words from:
@@ -148,33 +247,37 @@ unsafe fn rows_to_cols([a, _, c, d]: &mut [__m128i; 4]) {
/// reversing the transformation of [`rows_to_cols`].
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn cols_to_rows([a, _, c, d]: &mut [__m128i; 4]) {
- // c <<<= 32; d <<<= 64; a <<<= 96;
- *c = _mm_shuffle_epi32(*c, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
- *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
- *a = _mm_shuffle_epi32(*a, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+unsafe fn cols_to_rows(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, _, c, d] in blocks.iter_mut() {
+ // c <<<= 32; d <<<= 64; a <<<= 96;
+ *c = _mm_shuffle_epi32(*c, 0b_10_01_00_11); // _MM_SHUFFLE(2, 1, 0, 3)
+ *d = _mm_shuffle_epi32(*d, 0b_01_00_11_10); // _MM_SHUFFLE(1, 0, 3, 2)
+ *a = _mm_shuffle_epi32(*a, 0b_00_11_10_01); // _MM_SHUFFLE(0, 3, 2, 1)
+ }
}
#[inline]
#[target_feature(enable = "sse2")]
-unsafe fn add_xor_rot([a, b, c, d]: &mut [__m128i; 4]) {
- // a += b; d ^= a; d <<<= (16, 16, 16, 16);
- *a = _mm_add_epi32(*a, *b);
- *d = _mm_xor_si128(*d, *a);
- *d = _mm_xor_si128(_mm_slli_epi32(*d, 16), _mm_srli_epi32(*d, 16));
-
- // c += d; b ^= c; b <<<= (12, 12, 12, 12);
- *c = _mm_add_epi32(*c, *d);
- *b = _mm_xor_si128(*b, *c);
- *b = _mm_xor_si128(_mm_slli_epi32(*b, 12), _mm_srli_epi32(*b, 20));
-
- // a += b; d ^= a; d <<<= (8, 8, 8, 8);
- *a = _mm_add_epi32(*a, *b);
- *d = _mm_xor_si128(*d, *a);
- *d = _mm_xor_si128(_mm_slli_epi32(*d, 8), _mm_srli_epi32(*d, 24));
-
- // c += d; b ^= c; b <<<= (7, 7, 7, 7);
- *c = _mm_add_epi32(*c, *d);
- *b = _mm_xor_si128(*b, *c);
- *b = _mm_xor_si128(_mm_slli_epi32(*b, 7), _mm_srli_epi32(*b, 25));
+unsafe fn add_xor_rot(blocks: &mut [[__m128i; 4]; PAR_BLOCKS]) {
+ for [a, b, c, d] in blocks.iter_mut() {
+ // a += b; d ^= a; d <<<= (16, 16, 16, 16);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_xor_si128(_mm_slli_epi32(*d, 16), _mm_srli_epi32(*d, 16));
+
+ // c += d; b ^= c; b <<<= (12, 12, 12, 12);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_xor_si128(_mm_slli_epi32(*b, 12), _mm_srli_epi32(*b, 20));
+
+ // a += b; d ^= a; d <<<= (8, 8, 8, 8);
+ *a = _mm_add_epi32(*a, *b);
+ *d = _mm_xor_si128(*d, *a);
+ *d = _mm_xor_si128(_mm_slli_epi32(*d, 8), _mm_srli_epi32(*d, 24));
+
+ // c += d; b ^= c; b <<<= (7, 7, 7, 7);
+ *c = _mm_add_epi32(*c, *d);
+ *b = _mm_xor_si128(*b, *c);
+ *b = _mm_xor_si128(_mm_slli_epi32(*b, 7), _mm_srli_epi32(*b, 25));
+ }
}
### external/vendor/chacha20/src/chacha.rs
@@ -0,0 +1,38 @@
+use cipher::{
+ IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCoreWrapper,
+ array::Array,
+ consts::{U12, U32, U64},
+};
+
+use crate::{ChaChaCore, R8, R12, R20, Rounds, variants::Ietf};
+
+/// Key type used by all ChaCha variants.
+pub type Key = Array<u8, U32>;
+
+/// Nonce type used by ChaCha variants.
+pub type Nonce = Array<u8, U12>;
+
+/// ChaCha8 stream cipher (reduced-round variant of [`ChaCha20`] with 8 rounds)
+pub type ChaCha8 = StreamCipherCoreWrapper<ChaChaCore<R8, Ietf>>;
+
+/// ChaCha12 stream cipher (reduced-round variant of [`ChaCha20`] with 12 rounds)
+pub type ChaCha12 = StreamCipherCoreWrapper<ChaChaCore<R12, Ietf>>;
+
+/// ChaCha20 stream cipher (RFC 8439 version with 96-bit nonce)
+pub type ChaCha20 = StreamCipherCoreWrapper<ChaChaCore<R20, Ietf>>;
+
+pub(crate) type Block = Array<u8, U64>;
+
+impl<R: Rounds> KeySizeUser for ChaChaCore<R, Ietf> {
+ type KeySize = U32;
+}
+
+impl<R: Rounds> IvSizeUser for ChaChaCore<R, Ietf> {
+ type IvSize = U12;
+}
+impl<R: Rounds> KeyIvInit for ChaChaCore<R, Ietf> {
+ #[inline]
+ fn new(key: &Key, iv: &Nonce) -> Self {
+ ChaChaCore::<R, Ietf>::new_internal(key.as_ref(), iv.as_ref())
+ }
+}
### external/vendor/chacha20/src/legacy.rs
@@ -1,28 +1,20 @@
//! Legacy version of ChaCha20 with a 64-bit nonce
-use super::{ChaChaCore, Key, Nonce};
+use crate::{ChaChaCore, Key, R20, variants::Legacy};
use cipher::{
- consts::{U10, U32, U64, U8},
- generic_array::GenericArray,
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
+ IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCoreWrapper,
+ array::Array,
+ consts::{U8, U32},
};
-#[cfg(feature = "zeroize")]
-use cipher::zeroize::ZeroizeOnDrop;
-
/// Nonce type used by [`ChaCha20Legacy`].
-pub type LegacyNonce = GenericArray<u8, U8>;
+pub type LegacyNonce = Array<u8, U8>;
/// The ChaCha20 stream cipher (legacy "djb" construction with 64-bit nonce).
-///
-/// **WARNING:** this implementation uses 32-bit counter, while the original
-/// implementation uses 64-bit counter. In other words, it does
-/// not allow encrypting of more than 256 GiB of data.
pub type ChaCha20Legacy = StreamCipherCoreWrapper<ChaCha20LegacyCore>;
/// The ChaCha20 stream cipher (legacy "djb" construction with 64-bit nonce).
-pub struct ChaCha20LegacyCore(ChaChaCore<U10>);
+pub type ChaCha20LegacyCore = ChaChaCore<R20, Legacy>;
impl KeySizeUser for ChaCha20LegacyCore {
type KeySize = U32;
@@ -32,45 +24,9 @@ impl IvSizeUser for ChaCha20LegacyCore {
type IvSize = U8;
}
-impl BlockSizeUser for ChaCha20LegacyCore {
- type BlockSize = U64;
-}
-
impl KeyIvInit for ChaCha20LegacyCore {
#[inline(always)]
fn new(key: &Key, iv: &LegacyNonce) -> Self {
- let mut padded_iv = Nonce::default();
- padded_iv[4..].copy_from_slice(iv);
- ChaCha20LegacyCore(ChaChaCore::new(key, &padded_iv))
- }
-}
-
-impl StreamCipherCore for ChaCha20LegacyCore {
- #[inline(always)]
- fn remaining_blocks(&self) -> Option<usize> {
- self.0.remaining_blocks()
- }
-
- #[inline(always)]
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
- self.0.process_with_backend(f);
+ ChaChaCore::<R20, Legacy>::new_internal(key.as_ref(), iv.as_ref())
}
}
-
-impl StreamCipherSeekCore for ChaCha20LegacyCore {
- type Counter = u32;
-
- #[inline(always)]
- fn get_block_pos(&self) -> u32 {
- self.0.get_block_pos()
- }
-
- #[inline(always)]
- fn set_block_pos(&mut self, pos: u32) {
- self.0.set_block_pos(pos);
- }
-}
-
-#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl ZeroizeOnDrop for ChaCha20LegacyCore {}
### external/vendor/chacha20/src/lib.rs
@@ -1,177 +1,112 @@
-//! Implementation of the [ChaCha] family of stream ciphers.
-//!
-//! Cipher functionality is accessed using traits from re-exported [`cipher`] crate.
-//!
-//! ChaCha stream ciphers are lightweight and amenable to fast, constant-time
-//! implementations in software. It improves upon the previous [Salsa] design,
-//! providing increased per-round diffusion with no cost to performance.
-//!
-//! This crate contains the following variants of the ChaCha20 core algorithm:
-//!
-//! - [`ChaCha20`]: standard IETF variant with 96-bit nonce
-//! - [`ChaCha8`] / [`ChaCha12`]: reduced round variants of ChaCha20
-//! - [`XChaCha20`]: 192-bit extended nonce variant
-//! - [`XChaCha8`] / [`XChaCha12`]: reduced round variants of XChaCha20
-//! - [`ChaCha20Legacy`]: "djb" variant with 64-bit nonce.
-//! **WARNING:** This implementation internally uses 32-bit counter,
-//! while the original implementation uses 64-bit counter. In other words,
-//! it does not allow encryption of more than 256 GiB of data.
-//!
-//! # ⚠️ Security Warning: Hazmat!
-//!
-//! This crate does not ensure ciphertexts are authentic, which can lead to
-//! serious vulnerabilities if used incorrectly!
-//!
-//! If in doubt, use the [`chacha20poly1305`] crate instead, which provides
-//! an authenticated mode on top of ChaCha20.
-//!
-//! **USE AT YOUR OWN RISK!**
-//!
-//! # Diagram
-//!
-//! This diagram illustrates the ChaCha quarter round function.
-//! Each round consists of four quarter-rounds:
-//!
-//! <img src="https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/img/stream-ciphers/chacha20.png" width="300px">
-//!
-//! Legend:
-//!
-//! - ⊞ add
-//! - ‹‹‹ rotate
-//! - ⊕ xor
-//!
-//! # Example
-//! ```
-//! use chacha20::ChaCha20;
-//! // Import relevant traits
-//! use chacha20::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
-//! use hex_literal::hex;
-//!
-//! let key = [0x42; 32];
-//! let nonce = [0x24; 12];
-//! let plaintext = hex!("00010203 04050607 08090A0B 0C0D0E0F");
-//! let ciphertext = hex!("e405626e 4f1236b3 670ee428 332ea20e");
-//!
-//! // Key and IV must be references to the `GenericArray` type.
-//! // Here we use the `Into` trait to convert arrays into it.
-//! let mut cipher = ChaCha20::new(&key.into(), &nonce.into());
-//!
-//! let mut buffer = plaintext.clone();
-//!
-//! // apply keystream (encrypt)
-//! cipher.apply_keystream(&mut buffer);
-//! assert_eq!(buffer, ciphertext);
-//!
-//! let ciphertext = buffer.clone();
-//!
-//! // ChaCha ciphers support seeking
-//! cipher.seek(0u32);
-//!
-//! // decrypt ciphertext by applying keystream again
-//! cipher.apply_keystream(&mut buffer);
-//! assert_eq!(buffer, plaintext);
-//!
-//! // stream ciphers can be used with streaming messages
-//! cipher.seek(0u32);
-//! for chunk in buffer.chunks_mut(3) {
-//! cipher.apply_keystream(chunk);
-//! }
-//! assert_eq!(buffer, ciphertext);
-//! ```
-//!
-//! # Configuration Flags
-//!
-//! You can modify crate using the following configuration flags:
-//!
-//! - `chacha20_force_avx2`: force AVX2 backend on x86/x86_64 targets.
-//! Requires enabled AVX2 target feature. Ignored on non-x86(-64) targets.
-//! - `chacha20_force_neon`: force NEON backend on ARM targets.
-//! Requires enabled NEON target feature. Ignored on non-ARM targets. Nightly-only.
-//! - `chacha20_force_soft`: force software backend.
-//! - `chacha20_force_sse2`: force SSE2 backend on x86/x86_64 targets.
-//! Requires enabled SSE2 target feature. Ignored on non-x86(-64) targets.
-//!
-//! The flags can be enabled using `RUSTFLAGS` environmental variable
-//! (e.g. `RUSTFLAGS="--cfg chacha20_force_avx2"`) or by modifying `.cargo/config`.
-//!
-//! You SHOULD NOT enable several `force` flags simultaneously.
-//!
-//! [ChaCha]: https://tools.ietf.org/html/rfc8439
-//! [Salsa]: https://en.wikipedia.org/wiki/Salsa20
-//! [`chacha20poly1305`]: https://docs.rs/chacha20poly1305
-
#![no_std]
-#![cfg_attr(docsrs, feature(doc_cfg))]
+#![doc = include_str!("../README.md")]
#![doc(
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/media/8f1a9894/logo.svg"
)]
-#![allow(clippy::needless_range_loop)]
-#![warn(missing_docs, rust_2018_idioms, trivial_casts, unused_qualifications)]
-
-pub use cipher;
-
-use cfg_if::cfg_if;
-use cipher::{
- consts::{U10, U12, U32, U4, U6, U64},
- generic_array::{typenum::Unsigned, GenericArray},
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
-};
-use core::marker::PhantomData;
+#![cfg_attr(docsrs, feature(doc_cfg))]
-#[cfg(feature = "zeroize")]
-use cipher::zeroize::{Zeroize, ZeroizeOnDrop};
+pub mod variants;
mod backends;
+#[cfg(feature = "cipher")]
+mod chacha;
+#[cfg(feature = "legacy")]
mod legacy;
+#[cfg(feature = "rng")]
+mod rng;
+#[cfg(feature = "xchacha")]
mod xchacha;
+#[cfg(feature = "cipher")]
+pub use chacha::{ChaCha8, ChaCha12, ChaCha20, Key, Nonce};
+#[cfg(feature = "cipher")]
+pub use cipher;
+#[cfg(feature = "cipher")]
+pub use cipher::KeyIvInit;
+#[cfg(feature = "legacy")]
pub use legacy::{ChaCha20Legacy, ChaCha20LegacyCore, LegacyNonce};
-pub use xchacha::{hchacha, XChaCha12, XChaCha20, XChaCha8, XChaChaCore, XNonce};
+#[cfg(feature = "rng")]
+pub use rand_core;
+#[cfg(feature = "rng")]
+pub use rng::{ChaCha8Rng, ChaCha12Rng, ChaCha20Rng, Seed, SerializedRngState};
+#[cfg(feature = "xchacha")]
+pub use xchacha::{XChaCha8, XChaCha12, XChaCha20, XNonce, hchacha};
+
+use cfg_if::cfg_if;
+use core::{fmt, marker::PhantomData};
+use variants::Variant;
+
+#[cfg(feature = "cipher")]
+use cipher::{BlockSizeUser, StreamCipherCore, StreamCipherSeekCore, consts::U64};
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
/// State initialization constant ("expand 32-byte k")
+#[cfg(any(feature = "cipher", feature = "rng"))]
const CONSTANTS: [u32; 4] = [0x6170_7865, 0x3320_646e, 0x7962_2d32, 0x6b20_6574];
/// Number of 32-bit words in the ChaCha state
const STATE_WORDS: usize = 16;
-/// Block type used by all ChaCha variants.
-type Block = GenericArray<u8, U64>;
+/// Marker type for a number of ChaCha rounds to perform.
+pub trait Rounds: Copy {
+ /// The amount of rounds to perform
+ const COUNT: usize;
+}
+
+/// 8-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R8;
-/// Key type used by all ChaCha variants.
-pub type Key = GenericArray<u8, U32>;
+impl Rounds for R8 {
+ const COUNT: usize = 4;
+}
-/// Nonce type used by ChaCha variants.
-pub type Nonce = GenericArray<u8, U12>;
+/// 12-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R12;
-/// ChaCha8 stream cipher (reduced-round variant of [`ChaCha20`] with 8 rounds)
-pub type ChaCha8 = StreamCipherCoreWrapper<ChaChaCore<U4>>;
+impl Rounds for R12 {
+ const COUNT: usize = 6;
+}
-/// ChaCha12 stream cipher (reduced-round variant of [`ChaCha20`] with 12 rounds)
-pub type ChaCha12 = StreamCipherCoreWrapper<ChaChaCore<U6>>;
+/// 20-rounds
+#[derive(Copy, Clone, Debug)]
+pub struct R20;
-/// ChaCha20 stream cipher (RFC 8439 version with 96-bit nonce)
-pub type ChaCha20 = StreamCipherCoreWrapper<ChaChaCore<U10>>;
+impl Rounds for R20 {
+ const COUNT: usize = 10;
+}
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
type Tokens = ();
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ #[cfg(not(all(target_feature = "avx512f", target_feature = "avx512vl")))]
+ compile_error!("You must enable `avx512f` and `avx512vl` target features with \
+ `chacha20_backend = "avx512"` configuration option");
+ type Tokens = ();
+ } else if #[cfg(chacha20_backend = "avx2")] {
#[cfg(not(target_feature = "avx2"))]
compile_error!("You must enable `avx2` target feature with \
- `chacha20_force_avx2` configuration option");
+ `chacha20_backend = "avx2"` configuration option");
type Tokens = ();
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
#[cfg(not(target_feature = "sse2"))]
compile_error!("You must enable `sse2` target feature with \
- `chacha20_force_sse2` configuration option");
+ `chacha20_backend = "sse2"` configuration option");
type Tokens = ();
} else {
+ #[cfg(chacha20_avx512)]
+ cpufeatures::new!(avx512_cpuid, "avx512f", "avx512vl");
cpufeatures::new!(avx2_cpuid, "avx2");
cpufeatures::new!(sse2_cpuid, "sse2");
+ #[cfg(chacha20_avx512)]
+ type Tokens = (avx512_cpuid::InitToken, avx2_cpuid::InitToken, sse2_cpuid::InitToken);
+ #[cfg(not(chacha20_avx512))]
type Tokens = (avx2_cpuid::InitToken, sse2_cpuid::InitToken);
}
}
@@ -181,51 +116,64 @@ cfg_if! {
}
/// The ChaCha core function.
-pub struct ChaChaCore<R: Unsigned> {
+pub struct ChaChaCore<R: Rounds, V: Variant> {
/// Internal state of the core function
state: [u32; STATE_WORDS],
/// CPU target feature tokens
#[allow(dead_code)]
tokens: Tokens,
- /// Number of rounds to perform
- rounds: PhantomData<R>,
+ /// Number of rounds to perform and the cipher variant
+ _pd: PhantomData<(R, V)>,
}
-impl<R: Unsigned> KeySizeUser for ChaChaCore<R> {
- type KeySize = U32;
-}
+impl<R: Rounds, V: Variant> ChaChaCore<R, V> {
+ /// Constructs a ChaChaCore with the specified `key` and `iv`.
+ ///
+ /// You must ensure that the iv is of the correct size when using this method
+ /// directly.
+ ///
+ /// # Panics
+ /// If `iv.len()` is not equal to 4, 8, or 12.
+ #[must_use]
+ #[cfg(any(feature = "cipher", feature = "rng"))]
+ fn new_internal(key: &[u8; 32], iv: &[u8]) -> Self {
+ assert!(matches!(iv.len(), 4 | 8 | 12));
-impl<R: Unsigned> IvSizeUser for ChaChaCore<R> {
- type IvSize = U12;
-}
+ let mut state = [0u32; STATE_WORDS];
-impl<R: Unsigned> BlockSizeUser for ChaChaCore<R> {
- type BlockSize = U64;
-}
+ let ctr_size = size_of::<V::Counter>() / size_of::<u32>();
+ let (const_dst, state_rem) = state.split_at_mut(4);
+ let (key_dst, state_rem) = state_rem.split_at_mut(8);
+ let (_ctr_dst, iv_dst) = state_rem.split_at_mut(ctr_size);
-impl<R: Unsigned> KeyIvInit for ChaChaCore<R> {
- #[inline]
- fn new(key: &Key, iv: &Nonce) -> Self {
- let mut state = [0u32; STATE_WORDS];
- state[0..4].copy_from_slice(&CONSTANTS);
- let key_chunks = key.chunks_exact(4);
- for (val, chunk) in state[4..12].iter_mut().zip(key_chunks) {
- *val = u32::from_le_bytes(chunk.try_into().unwrap());
- }
- let iv_chunks = iv.chunks_exact(4);
- for (val, chunk) in state[13..16].iter_mut().zip(iv_chunks) {
- *val = u32::from_le_bytes(chunk.try_into().unwrap());
+ const_dst.copy_from_slice(&CONSTANTS);
+
+ // TODO(tarcieri): when MSRV 1.88, use `[T]::as_chunks` to avoid panic
+ #[allow(clippy::unwrap_used, reason = "MSRV TODO")]
+ {
+ for (src, dst) in key.chunks_exact(4).zip(key_dst) {
+ *dst = u32::from_le_bytes(src.try_into().unwrap());
+ }
+
+ assert_eq!(size_of_val(iv_dst), size_of_val(iv));
+ for (src, dst) in iv.chunks_exact(4).zip(iv_dst) {
+ *dst = u32::from_le_bytes(src.try_into().unwrap());
+ }
}
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
let tokens = ();
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(chacha20_backend = "avx512")] {
let tokens = ();
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "avx2")] {
let tokens = ();
+ } else if #[cfg(chacha20_backend = "sse2")] {
+ let tokens = ();
+ } else if #[cfg(chacha20_avx512)] {
+ let tokens = (avx512_cpuid::init(), avx2_cpuid::init(), sse2_cpuid::init());
} else {
let tokens = (avx2_cpuid::init(), sse2_cpuid::init());
}
@@ -234,54 +182,114 @@ impl<R: Unsigned> KeyIvInit for ChaChaCore<R> {
let tokens = ();
}
}
-
Self {
state,
tokens,
- rounds: PhantomData,
+ _pd: PhantomData,
}
}
+
+ /// Get the current block position.
+ #[inline(always)]
+ #[must_use]
+ pub fn get_block_pos(&self) -> V::Counter {
+ V::get_block_pos(&self.state[12..])
+ }
+
+ /// Set the block position.
+ #[inline(always)]
+ pub fn set_block_pos(&mut self, pos: V::Counter) {
+ V::set_block_pos(&mut self.state[12..], pos);
+ }
}
-impl<R: Unsigned> StreamCipherCore for ChaChaCore<R> {
+impl<R: Rounds, V: Variant> fmt::Debug for ChaChaCore<R, V> {
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ f,
+ "ChaChaCore<R: {}, V: {}-bit)> {{ ... }}",
+ R::COUNT,
+ size_of::<V::Counter>() * 8
+ )
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherSeekCore for ChaChaCore<R, V> {
+ type Counter = V::Counter;
+
+ #[inline(always)]
+ fn get_block_pos(&self) -> Self::Counter {
+ self.get_block_pos()
+ }
+
+ #[inline(always)]
+ fn set_block_pos(&mut self, pos: Self::Counter) {
+ self.set_block_pos(pos);
+ }
+}
+
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> StreamCipherCore for ChaChaCore<R, V> {
#[inline(always)]
fn remaining_blocks(&self) -> Option<usize> {
- let rem = u32::MAX - self.get_block_pos();
- rem.try_into().ok()
+ V::remaining_blocks(self.get_block_pos())
}
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
+ fn process_with_backend(
+ &mut self,
+ f: impl cipher::StreamCipherClosure<BlockSize = Self::BlockSize>,
+ ) {
cfg_if! {
- if #[cfg(chacha20_force_soft)] {
+ if #[cfg(chacha20_backend = "soft")] {
f.call(&mut backends::soft::Backend(self));
} else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
cfg_if! {
- if #[cfg(chacha20_force_avx2)] {
+ if #[cfg(all(chacha20_avx512, chacha20_backend = "avx512"))] {
+ unsafe {
+ backends::avx512::inner::<R, _, V>(&mut self.state, f);
+ }
+ } else if #[cfg(chacha20_backend = "avx2")] {
unsafe {
- backends::avx2::inner::<R, _>(&mut self.state, f);
+ backends::avx2::inner::<R, _, V>(&mut self.state, f);
}
- } else if #[cfg(chacha20_force_sse2)] {
+ } else if #[cfg(chacha20_backend = "sse2")] {
unsafe {
- backends::sse2::inner::<R, _>(&mut self.state, f);
+ backends::sse2::inner::<R, _, V>(&mut self.state, f);
}
} else {
+ #[cfg(chacha20_avx512)]
+ let (avx512_token, avx2_token, sse2_token) = self.tokens;
+ #[cfg(not(chacha20_avx512))]
let (avx2_token, sse2_token) = self.tokens;
+
+ #[cfg(chacha20_avx512)]
+ if avx512_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
+ unsafe {
+ backends::avx512::inner::<R, _, V>(&mut self.state, f);
+ }
+ return;
+ }
if avx2_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
unsafe {
- backends::avx2::inner::<R, _>(&mut self.state, f);
+ backends::avx2::inner::<R, _, V>(&mut self.state, f);
}
} else if sse2_token.get() {
+ // SAFETY: runtime CPU feature detection above ensures this is valid
unsafe {
- backends::sse2::inner::<R, _>(&mut self.state, f);
+ backends::sse2::inner::<R, _, V>(&mut self.state, f);
}
} else {
f.call(&mut backends::soft::Backend(self));
}
}
}
- } else if #[cfg(all(chacha20_force_neon, target_arch = "aarch64", target_feature = "neon"))] {
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
unsafe {
- backends::neon::inner::<R, _>(&mut self.state, f);
+ backends::neon::inner::<R, _, V>(&mut self.state, f);
}
} else {
f.call(&mut backends::soft::Backend(self));
@@ -290,28 +298,46 @@ impl<R: Unsigned> StreamCipherCore for ChaChaCore<R> {
}
}
-impl<R: Unsigned> StreamCipherSeekCore for ChaChaCore<R> {
- type Counter = u32;
-
- #[inline(always)]
- fn get_block_pos(&self) -> u32 {
- self.state[12]
- }
-
- #[inline(always)]
- fn set_block_pos(&mut self, pos: u32) {
- self.state[12] = pos;
- }
+#[cfg(feature = "cipher")]
+impl<R: Rounds, V: Variant> BlockSizeUser for ChaChaCore<R, V> {
+ type BlockSize = U64;
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> Drop for ChaChaCore<R> {
+impl<R: Rounds, V: Variant> Drop for ChaChaCore<R, V> {
fn drop(&mut self) {
self.state.zeroize();
}
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> ZeroizeOnDrop for ChaChaCore<R> {}
+impl<R: Rounds, V: Variant> ZeroizeOnDrop for ChaChaCore<R, V> {}
+
+/// The ChaCha20 quarter round function
+///
+/// We located this function in the root of the crate as we want it to be available
+/// for the soft backend and for xchacha.
+#[allow(dead_code)]
+pub(crate) fn quarter_round(
+ a: usize,
+ b: usize,
+ c: usize,
+ d: usize,
+ state: &mut [u32; STATE_WORDS],
+) {
+ state[a] = state[a].wrapping_add(state[b]);
+ state[d] ^= state[a];
+ state[d] = state[d].rotate_left(16);
+
+ state[c] = state[c].wrapping_add(state[d]);
+ state[b] ^= state[c];
+ state[b] = state[b].rotate_left(12);
+
+ state[a] = state[a].wrapping_add(state[b]);
+ state[d] ^= state[a];
+ state[d] = state[d].rotate_left(8);
+
+ state[c] = state[c].wrapping_add(state[d]);
+ state[b] ^= state[c];
+ state[b] = state[b].rotate_left(7);
+}
### external/vendor/chacha20/src/rng.rs
@@ -0,0 +1,344 @@
+#![allow(clippy::cast_possible_truncation, reason = "needs triage")]
+#![allow(clippy::undocumented_unsafe_blocks, reason = "TODO")]
+
+use core::fmt;
+
+use rand_core::{
+ Infallible, SeedableRng, TryCryptoRng, TryRng,
+ block::{BlockRng, Generator},
+};
+
+#[cfg(feature = "zeroize")]
+use zeroize::{Zeroize, ZeroizeOnDrop};
+
+use crate::{
+ ChaChaCore, R8, R12, R20, Rounds, backends,
+ variants::{Legacy, Variant},
+};
+
+use cfg_if::cfg_if;
+
+/// Seed value used to initialize ChaCha-based RNGs.
+pub type Seed = [u8; 32];
+
+/// Serialized RNG state.
+pub type SerializedRngState = [u8; 49];
+
+/// Number of 32-bit words per ChaCha block (fixed by algorithm definition).
+pub(crate) const BLOCK_WORDS: u8 = 16;
+
+/// Number of blocks generated by RNG core.
+const BUF_BLOCKS: u8 = 4;
+/// Buffer size in words used by buffered RNG.
+const BUFFER_SIZE: usize = (BLOCK_WORDS * BUF_BLOCKS) as usize;
+
+impl<R: Rounds, V: Variant> SeedableRng for ChaChaCore<R, V> {
+ type Seed = Seed;
+
+ #[inline]
+ fn from_seed(seed: Self::Seed) -> Self {
+ ChaChaCore::new_internal(&seed, &[0u8; 8])
+ }
+}
+
+impl<R: Rounds, V: Variant> Generator for ChaChaCore<R, V> {
+ type Output = [u32; BUFFER_SIZE];
+
+ /// Generates 4 blocks in parallel with avx2 & neon, but merely fills
+ /// 4 blocks with sse2 & soft
+ fn generate(&mut self, buffer: &mut [u32; BUFFER_SIZE]) {
+ cfg_if! {
+ if #[cfg(chacha20_backend = "soft")] {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ } else if #[cfg(any(target_arch = "x86", target_arch = "x86_64"))] {
+ cfg_if! {
+ // AVX-512 doesn't support RNG, so use AVX-2 instead
+ if #[cfg(any(chacha20_backend = "avx2", chacha20_backend = "avx512"))] {
+ unsafe {
+ backends::avx2::rng_inner::<R, V>(self, buffer);
+ }
+ } else if #[cfg(chacha20_backend = "sse2")] {
+ unsafe {
+ backends::sse2::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ #[cfg(chacha20_avx512)]
+ let (_avx512_token, avx2_token, sse2_token) = self.tokens;
+ #[cfg(not(chacha20_avx512))]
+ let (avx2_token, sse2_token) = self.tokens;
+
+ if avx2_token.get() {
+ unsafe {
+ backends::avx2::rng_inner::<R, V>(self, buffer);
+ }
+ } else if sse2_token.get() {
+ unsafe {
+ backends::sse2::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ }
+ }
+ }
+ } else if #[cfg(all(target_arch = "aarch64", target_feature = "neon"))] {
+ // SAFETY: we have used conditional compilation to ensure NEON is available
+ unsafe {
+ backends::neon::rng_inner::<R, V>(self, buffer);
+ }
+ } else {
+ backends::soft::Backend(self).gen_ks_blocks(buffer);
+ }
+ }
+ }
+
+ // `Drop` impl of `BlockRng` calls this method and passes reference to
+ // its internal buffer in `output`. So we zeroize its contents here.
+ #[cfg(feature = "zeroize")]
+ fn drop(&mut self, output: &mut Self::Output) {
+ output.zeroize();
+ }
+}
+
+macro_rules! impl_chacha_rng {
+ ($Rng:ident, $rounds:ident) => {
+ /// A cryptographically secure random number generator that uses the ChaCha stream cipher.
+ ///
+ /// See the [crate docs][crate] for more information about the underlying stream cipher.
+ ///
+ /// This RNG implementation uses a 64-bit counter and 64-bit stream identifier (a.k.a nonce).
+ /// A 64-bit counter over 64-byte (16 word) blocks allows 1 ZiB of output before cycling,
+ /// and the stream identifier allows 2<sup>64</sup> unique streams of output per seed.
+ /// Both counter and stream are initialized to zero but may be set via the [`set_word_pos`]
+ /// and [`set_stream`] methods.
+ ///
+ /// [`set_word_pos`]: Self::set_word_pos
+ /// [`set_stream`]: Self::set_stream
+ ///
+ /// # Example
+ ///
+ /// ```rust
+ #[doc = concat!("use chacha20::", stringify!($Rng), ";")]
+ /// use rand_core::{SeedableRng, Rng};
+ ///
+ /// let seed = [42u8; 32];
+ #[doc = concat!("let mut rng = ", stringify!($Rng), "::from_seed(seed);")]
+ ///
+ /// let random_u32 = rng.next_u32();
+ /// let random_u64 = rng.next_u64();
+ ///
+ /// let mut random_bytes = [0u8; 3];
+ /// rng.fill_bytes(&mut random_bytes);
+ /// ```
+ ///
+ /// See the [`rand`](https://docs.rs/rand/) crate for more advanced RNG functionality.
+ pub struct $Rng {
+ core: BlockRng<ChaChaCore<$rounds, Legacy>>,
+ }
+
+ impl SeedableRng for $Rng {
+ type Seed = Seed;
+
+ #[inline]
+ fn from_seed(seed: Self::Seed) -> Self {
+ let core = ChaChaCore::new_internal(&seed, &[0u8; 8]);
+ Self {
+ core: BlockRng::new(core),
+ }
+ }
+ }
+
+ impl TryRng for $Rng {
+ type Error = Infallible;
+
+ #[inline]
+ fn try_next_u32(&mut self) -> Result<u32, Self::Error> {
+ Ok(self.core.next_word())
+ }
+ #[inline]
+ fn try_next_u64(&mut self) -> Result<u64, Self::Error> {
+ Ok(self.core.next_u64_from_u32())
+ }
+ #[inline]
+ fn try_fill_bytes(&mut self, dest: &mut [u8]) -> Result<(), Self::Error> {
+ self.core.fill_bytes(dest);
+ Ok(())
+ }
+ }
+
+ impl TryCryptoRng for $Rng {}
+
+ #[cfg(feature = "zeroize")]
+ impl ZeroizeOnDrop for $Rng {}
+
+ // We use custom implementation of `PartialEq` because RNG states
+ // may buffer different parts of the same keystream, while keeping
+ // buffer cursor pointing towards the same keystream point.
+ impl PartialEq<$Rng> for $Rng {
+ fn eq(&self, rhs: &$Rng) -> bool {
+ (self.get_seed() == rhs.get_seed())
+ && (self.get_stream() == rhs.get_stream())
+ && (self.get_word_pos() == rhs.get_word_pos())
+ }
+ }
+
+ impl Eq for $Rng {}
+
+ // Custom Debug implementation that does not expose the internal state
+ impl fmt::Debug for $Rng {
+ fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
+ write!(f, concat!(stringify!($Rng), " {{ ... }}"))
+ }
+ }
+
+ impl $Rng {
+ /// Get the offset from the start of the stream, in 32-bit words.
+ ///
+ /// Since the generated blocks are 16 words (2<sup>4</sup>) long and the
+ /// counter is 64-bits, the offset is a 68-bit number. Sub-word offsets are
+ /// not supported, hence the result can simply be multiplied by 4 to get a
+ /// byte-offset.
+ #[inline]
+ #[must_use]
+ pub fn get_word_pos(&self) -> u128 {
+ let mut block_counter = (u64::from(self.core.core.state[13]) << 32)
+ | u64::from(self.core.core.state[12]);
+ if self.core.word_offset() != 0 {
+ block_counter = block_counter.wrapping_sub(u64::from(BUF_BLOCKS));
+ }
+ let word_pos = u128::from(block_counter) * u128::from(BLOCK_WORDS)
+ + self.core.word_offset() as u128;
+ // eliminate bits above the 68th bit
+ word_pos & ((1 << 68) - 1)
+ }
+
+ /// Set the offset from the start of the stream, in 32-bit words.
+ ///
+ /// **This value will be erased when calling `set_stream()`,
+ /// so call `set_stream()` before calling `set_word_pos()`**
+ /// if you intend on using both of them together.
+ ///
+ /// As with `get_word_pos`, we use a 68-bit number. Since the generator
+ /// simply cycles at the end of its period (1 ZiB), we ignore the upper
+ /// 60 bits.
+ #[inline]
+ pub fn set_word_pos(&mut self, word_offset: u128) {
+ let index = (word_offset % u128::from(BLOCK_WORDS)) as usize;
+ let counter = word_offset / u128::from(BLOCK_WORDS);
+ //self.set_block_pos(counter as u64);
+ self.core.core.state[12] = counter as u32;
+ self.core.core.state[13] = (counter >> 32) as u32;
+ self.core.reset_and_skip(index);
+ }
+
+ /// Sets the block pos and resets the RNG's index.
+ ///
+ /// **This value will be erased when calling `set_stream()`,
+ /// so call `set_stream()` before calling `set_block_pos()`**
+ /// if you intend on using both of them together.
+ ///
+ /// The word pos will be equal to `block_pos * 16 words per block`.
+ #[inline]
+ #[allow(unused)]
+ pub fn set_block_pos(&mut self, block_pos: u64) {
+ self.core.reset_and_skip(0);
+ self.core.core.set_block_pos(block_pos);
+ }
+
+ /// Get the block pos.
+ #[inline]
+ #[allow(unused)]
+ #[must_use]
+ pub fn get_block_pos(&self) -> u64 {
+ let counter = self.core.core.get_block_pos();
+ let offset = self.core.word_offset();
+ if offset != 0 {
+ counter - u64::from(BUF_BLOCKS) + offset as u64 / u64::from(BLOCK_WORDS)
+ } else {
+ counter
+ }
+ }
+
+ /// Set the stream ID and reset the `word_pos` to 0.
+ #[inline]
+ pub fn set_stream(&mut self, stream: u64) {
+ self.core.core.state[14] = stream as u32;
+ self.core.core.state[15] = (stream >> 32) as u32;
+ self.set_block_pos(0);
+ }
+
+ /// Get the stream number (nonce).
+ #[inline]
+ #[must_use]
+ pub fn get_stream(&self) -> u64 {
+ let mut result = [0u8; 8];
+ result[..4].copy_from_slice(&self.core.core.state[14].to_le_bytes());
+ result[4..].copy_from_slice(&self.core.core.state[15].to_le_bytes());
+ u64::from_le_bytes(result)
+ }
+
+ /// Get the RNG seed.
+ #[inline]
+ #[must_use]
+ pub fn get_seed(&self) -> [u8; 32] {
+ let seed = &self.core.core.state[4..12];
+ let mut result = [0u8; 32];
+ for (src, dst) in seed.iter().zip(result.chunks_exact_mut(4)) {
+ dst.copy_from_slice(&src.to_le_bytes())
+ }
+ result
+ }
+
+ /// Serialize RNG state.
+ ///
+ /// # Warning
+ /// Leaking serialized RNG state to an attacker defeats security properties
+ /// provided by the RNG.
+ #[inline]
+ pub fn serialize_state(&self) -> SerializedRngState {
+ let seed = self.get_seed();
+ let stream = self.get_stream().to_le_bytes();
+ let word_pos = self.get_word_pos().to_le_bytes();
+
+ let mut res = [0u8; 49];
+ let (seed_dst, res_rem) = res.split_at_mut(32);
+ let (stream_dst, word_pos_dst) = res_rem.split_at_mut(8);
+
+ seed_dst.copy_from_slice(&seed);
+ stream_dst.copy_from_slice(&stream);
+ word_pos_dst.copy_from_slice(&word_pos[..9]);
+
+ debug_assert_eq!(&word_pos[9..], &[0u8; 7]);
+
+ res
+ }
+
+ /// Deserialize RNG state.
+ #[inline]
+ pub fn deserialize_state(state: &SerializedRngState) -> Self {
+ let (seed, state_rem) = state.split_at(32);
+ let (stream, word_pos_raw) = state_rem.split_at(8);
+
+ let seed: &[u8; 32] = seed.try_into().expect("seed.len() is equal to 32");
+ let stream: &[u8; 8] = stream.try_into().expect("stream.len() is equal to 8");
+
+ // Note that we use only 68 bits from `word_pos_raw`, i.e. 4 remaining bits
+ // get ignored and should be equal to zero in practice.
+ let mut word_pos_buf = [0u8; 16];
+ word_pos_buf[..9].copy_from_slice(word_pos_raw);
+ let word_pos = u128::from_le_bytes(word_pos_buf);
+
+ let core = ChaChaCore::new_internal(seed, stream);
+ let mut res = Self {
+ core: BlockRng::new(core),
+ };
+
+ res.set_word_pos(word_pos);
+ res
+ }
+ }
+ };
+}
+
+impl_chacha_rng!(ChaCha8Rng, R8);
+impl_chacha_rng!(ChaCha12Rng, R12);
+impl_chacha_rng!(ChaCha20Rng, R20);
### external/vendor/chacha20/src/variants.rs
@@ -0,0 +1,84 @@
+//! ChaCha variant-specific configurations.
+
+mod sealed {
+ pub trait Sealed {}
+}
+
+/// A trait that distinguishes some ChaCha variants. Contains configurations
+/// for "Legacy" DJB variant and the IETF variant.
+pub trait Variant: sealed::Sealed {
+ /// The counter's type.
+ #[cfg(not(feature = "cipher"))]
+ type Counter: Copy;
+
+ /// The counter's type.
+ #[cfg(feature = "cipher")]
+ type Counter: cipher::StreamCipherCounter;
+
+ /// Takes a slice of `state[12..NONCE_INDEX]` to convert it into
+ /// `Self::Counter`.
+ fn get_block_pos(row: &[u32]) -> Self::Counter;
+
+ /// Breaks down the `Self::Counter` type into a u32 array for setting the
+ /// block pos.
+ fn set_block_pos(row: &mut [u32], pos: Self::Counter);
+
+ /// A helper method for calculating the remaining blocks using these types
+ fn remaining_blocks(block_pos: Self::Counter) -> Option<usize>;
+}
+
+/// IETF ChaCha configuration to use a 32-bit counter and 96-bit nonce.
+#[derive(Clone, Copy, Debug)]
+pub enum Ietf {}
+
+impl sealed::Sealed for Ietf {}
+
+impl Variant for Ietf {
+ type Counter = u32;
+
+ #[inline(always)]
+ fn get_block_pos(row: &[u32]) -> u32 {
+ row[0]
+ }
+
+ #[inline(always)]
+ fn set_block_pos(row: &mut [u32], pos: u32) {
+ row[0] = pos;
+ }
+
+ #[inline(always)]
+ fn remaining_blocks(block_pos: u32) -> Option<usize> {
+ let remaining = u32::MAX - block_pos;
+ remaining.try_into().ok()
+ }
+}
+
+/// DJB variant specific features: 64-bit counter and 64-bit nonce.
+#[cfg(any(feature = "legacy", feature = "rng"))]
+#[derive(Clone, Copy, Debug)]
+pub enum Legacy {}
+
+#[cfg(any(feature = "legacy", feature = "rng"))]
+impl sealed::Sealed for Legacy {}
+
+#[cfg(any(feature = "legacy", feature = "rng"))]
+impl Variant for Legacy {
+ type Counter = u64;
+
+ #[inline(always)]
+ fn get_block_pos(row: &[u32]) -> u64 {
+ (u64::from(row[1]) << 32) | u64::from(row[0])
+ }
+
+ #[inline(always)]
+ fn set_block_pos(row: &mut [u32], pos: u64) {
+ row[0] = (pos & 0xFFFF_FFFF) as u32;
+ row[1] = (pos >> 32) as u32;
+ }
+
+ #[inline(always)]
+ fn remaining_blocks(block_pos: u64) -> Option<usize> {
+ let remaining = u64::MAX - block_pos;
+ remaining.try_into().ok()
+ }
+}
### external/vendor/chacha20/src/xchacha.rs
@@ -1,18 +1,20 @@
//! XChaCha is an extended nonce variant of ChaCha
-use super::{ChaChaCore, Key, Nonce, CONSTANTS, STATE_WORDS};
+use crate::{
+ CONSTANTS, ChaChaCore, Key, R8, R12, R20, Rounds, STATE_WORDS, quarter_round, variants::Ietf,
+};
use cipher::{
- consts::{U10, U16, U24, U32, U4, U6, U64},
- generic_array::{typenum::Unsigned, GenericArray},
- BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherCore, StreamCipherCoreWrapper,
- StreamCipherSeekCore, StreamClosure,
+ BlockSizeUser, IvSizeUser, KeyIvInit, KeySizeUser, StreamCipherClosure, StreamCipherCore,
+ StreamCipherCoreWrapper, StreamCipherSeekCore,
+ array::Array,
+ consts::{U4, U16, U24, U32, U64},
};
#[cfg(feature = "zeroize")]
-use cipher::zeroize::ZeroizeOnDrop;
+use zeroize::ZeroizeOnDrop;
/// Nonce type used by XChaCha variants.
-pub type XNonce = GenericArray<u8, U24>;
+pub type XNonce = Array<u8, U24>;
/// XChaCha is a ChaCha20 variant with an extended 192-bit (24-byte) nonce.
///
@@ -28,50 +30,55 @@ pub type XNonce = GenericArray<u8, U24>;
/// several interoperable libraries and protocols (e.g. libsodium, WireGuard)
/// and is documented in an (expired) IETF draft:
///
-/// <https://tools.ietf.org/html/draft-arciszewski-xchacha-03>
-pub type XChaCha20 = StreamCipherCoreWrapper<XChaChaCore<U10>>;
+/// <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha>
+pub type XChaCha20 = StreamCipherCoreWrapper<XChaChaCore<R20>>;
/// XChaCha12 stream cipher (reduced-round variant of [`XChaCha20`] with 12 rounds)
-pub type XChaCha12 = StreamCipherCoreWrapper<XChaChaCore<U6>>;
+pub type XChaCha12 = StreamCipherCoreWrapper<XChaChaCore<R12>>;
/// XChaCha8 stream cipher (reduced-round variant of [`XChaCha20`] with 8 rounds)
-pub type XChaCha8 = StreamCipherCoreWrapper<XChaChaCore<U4>>;
+pub type XChaCha8 = StreamCipherCoreWrapper<XChaChaCore<R8>>;
/// The XChaCha core function.
-pub struct XChaChaCore<R: Unsigned>(ChaChaCore<R>);
+#[derive(Debug)]
+pub struct XChaChaCore<R: Rounds>(ChaChaCore<R, Ietf>);
-impl<R: Unsigned> KeySizeUser for XChaChaCore<R> {
+impl<R: Rounds> KeySizeUser for XChaChaCore<R> {
type KeySize = U32;
}
-impl<R: Unsigned> IvSizeUser for XChaChaCore<R> {
+impl<R: Rounds> IvSizeUser for XChaChaCore<R> {
type IvSize = U24;
}
-impl<R: Unsigned> BlockSizeUser for XChaChaCore<R> {
+impl<R: Rounds> BlockSizeUser for XChaChaCore<R> {
type BlockSize = U64;
}
-impl<R: Unsigned> KeyIvInit for XChaChaCore<R> {
+impl<R: Rounds> KeyIvInit for XChaChaCore<R> {
fn new(key: &Key, iv: &XNonce) -> Self {
- let subkey = hchacha::<R>(key, iv[..16].as_ref().into());
- let mut padded_iv = Nonce::default();
- padded_iv[4..].copy_from_slice(&iv[16..]);
- XChaChaCore(ChaChaCore::new(&subkey, &padded_iv))
+ #[allow(clippy::unwrap_used)]
+ let subkey = hchacha::<R>(key, iv[..16].as_ref().try_into().unwrap());
+
+ let mut nonce = [0u8; 12];
+ // first 4 bytes are 0, last 8 bytes are last 8 from the iv
+ // according to draft-arciszewski-xchacha-03
+ nonce[4..].copy_from_slice(&iv[16..]);
+ Self(ChaChaCore::<R, Ietf>::new_internal(subkey.as_ref(), &nonce))
}
}
-impl<R: Unsigned> StreamCipherCore for XChaChaCore<R> {
+impl<R: Rounds> StreamCipherCore for XChaChaCore<R> {
#[inline(always)]
fn remaining_blocks(&self) -> Option<usize> {
self.0.remaining_blocks()
}
#[inline(always)]
- fn process_with_backend(&mut self, f: impl StreamClosure<BlockSize = Self::BlockSize>) {
+ fn process_with_backend(&mut self, f: impl StreamCipherClosure<BlockSize = Self::BlockSize>) {
self.0.process_with_backend(f);
}
}
-impl<R: Unsigned> StreamCipherSeekCore for XChaChaCore<R> {
+impl<R: Rounds> StreamCipherSeekCore for XChaChaCore<R> {
type Counter = u32;
#[inline(always)]
@@ -86,8 +93,7 @@ impl<R: Unsigned> StreamCipherSeekCore for XChaChaCore<R> {
}
#[cfg(feature = "zeroize")]
-#[cfg_attr(docsrs, doc(cfg(feature = "zeroize")))]
-impl<R: Unsigned> ZeroizeOnDrop for XChaChaCore<R> {}
+impl<R: Rounds> ZeroizeOnDrop for XChaChaCore<R> {}
/// The HChaCha function: adapts the ChaCha core function in the same
/// manner that HSalsa adapts the Salsa function.
@@ -103,21 +109,23 @@ impl<R: Unsigned> ZeroizeOnDrop for XChaChaCore<R> {}
/// For more information on HSalsa on which HChaCha is based, see:
///
/// <http://cr.yp.to/snuffle/xsalsa-20110204.pdf>
-pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> GenericArray<u8, U32> {
+#[must_use]
+pub fn hchacha<R: Rounds>(key: &Key, input: &Array<u8, U16>) -> Array<u8, U32> {
let mut state = [0u32; STATE_WORDS];
state[..4].copy_from_slice(&CONSTANTS);
- let key_chunks = key.chunks_exact(4);
+ // TODO(tarcieri): use `[T]::as_chunks` when MSRV 1.88
+ let key_chunks = Array::<u8, U4>::slice_as_chunks(key).0;
for (v, chunk) in state[4..12].iter_mut().zip(key_chunks) {
- *v = u32::from_le_bytes(chunk.try_into().unwrap());
+ *v = u32::from_le_bytes(chunk.0);
}
- let input_chunks = input.chunks_exact(4);
+ let input_chunks = Array::<u8, U4>::slice_as_chunks(input).0;
for (v, chunk) in state[12..16].iter_mut().zip(input_chunks) {
- *v = u32::from_le_bytes(chunk.try_into().unwrap());
+ *v = u32::from_le_bytes(chunk.0);
}
// R rounds consisting of R/2 column rounds and R/2 diagonal rounds
- for _ in 0..R::USIZE {
+ for _ in 0..R::COUNT {
// column rounds
quarter_round(0, 4, 8, 12, &mut state);
quarter_round(1, 5, 9, 13, &mut state);
@@ -131,7 +139,7 @@ pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> Generic
quarter_round(3, 4, 9, 14, &mut state);
}
- let mut output = GenericArray::default();
+ let mut output = Array::default();
for (chunk, val) in output[..16].chunks_exact_mut(4).zip(&state[..4]) {
chunk.copy_from_slice(&val.to_le_bytes());
@@ -144,33 +152,13 @@ pub fn hchacha<R: Unsigned>(key: &Key, input: &GenericArray<u8, U16>) -> Generic
output
}
-/// The ChaCha20 quarter round function
-// for simplicity this function is copied from the software backend
-fn quarter_round(a: usize, b: usize, c: usize, d: usize, state: &mut [u32; STATE_WORDS]) {
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(16);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(12);
-
- state[a] = state[a].wrapping_add(state[b]);
- state[d] ^= state[a];
- state[d] = state[d].rotate_left(8);
-
- state[c] = state[c].wrapping_add(state[d]);
- state[b] ^= state[c];
- state[b] = state[b].rotate_left(7);
-}
-
#[cfg(test)]
mod hchacha20_tests {
use super::*;
use hex_literal::hex;
/// Test vectors from:
- /// https://tools.ietf.org/id/draft-arciszewski-xchacha-03.html#rfc.section.2.2.1
+ /// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#section-2.2.1
#[test]
fn test_vector() {
const KEY: [u8; 32] = hex!(
@@ -185,10 +173,7 @@ mod hchacha20_tests {
"a0f9e4d58a74a853c12ec41326d3ecdc"
);
- let actual = hchacha::<U10>(
- GenericArray::from_slice(&KEY),
- &GenericArray::from_slice(&INPUT),
- );
+ let actual = hchacha::<R20>(&KEY.into(), &INPUT.into());
assert_eq!(actual.as_slice(), &OUTPUT);
}
}
### external/vendor/chacha20/tests/data/chacha20-legacy.blb
[binary or diff unavailable]
### external/vendor/chacha20/tests/data/chacha20.blb
[binary or diff unavailable]
### external/vendor/chacha20/tests/kats.rs
@@ -1,15 +1,27 @@
//! Tests for ChaCha20 (IETF and "djb" versions) as well as XChaCha20
-use chacha20::{ChaCha20, ChaCha20Legacy, XChaCha20};
+#[cfg(feature = "cipher")]
+use chacha20::ChaCha20;
+
+#[cfg(feature = "legacy")]
+use chacha20::ChaCha20Legacy;
+
+#[cfg(feature = "xchacha")]
+use chacha20::XChaCha20;
// IETF version of ChaCha20 (96-bit nonce)
+#[cfg(feature = "cipher")]
cipher::stream_cipher_test!(chacha20_core, "chacha20", ChaCha20);
+#[cfg(feature = "cipher")]
cipher::stream_cipher_seek_test!(chacha20_seek, ChaCha20);
+#[cfg(feature = "xchacha")]
cipher::stream_cipher_seek_test!(xchacha20_seek, XChaCha20);
+#[cfg(feature = "legacy")]
cipher::stream_cipher_seek_test!(chacha20legacy_seek, ChaCha20Legacy);
+#[cfg(feature = "cipher")]
mod chacha20test {
- use chacha20::{ChaCha20, Key, Nonce};
- use cipher::{KeyIvInit, StreamCipher};
+ use chacha20::{ChaCha20, KeyIvInit};
+ use cipher::StreamCipher;
use hex_literal::hex;
//
@@ -59,7 +71,7 @@ mod chacha20test {
#[test]
fn chacha20_keystream() {
- let mut cipher = ChaCha20::new(&Key::from(KEY), &Nonce::from(IV));
+ let mut cipher = ChaCha20::new(&KEY.into(), &IV.into());
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -72,8 +84,8 @@ mod chacha20test {
#[test]
fn chacha20_encryption() {
- let mut cipher = ChaCha20::new(&Key::from(KEY), &Nonce::from(IV));
- let mut buf = PLAINTEXT.clone();
+ let mut cipher = ChaCha20::new(&KEY.into(), &IV.into());
+ let mut buf = PLAINTEXT;
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -85,6 +97,7 @@ mod chacha20test {
}
#[rustfmt::skip]
+#[cfg(feature = "xchacha")]
mod xchacha20 {
use chacha20::{Key, XChaCha20, XNonce};
use cipher::{KeyIvInit, StreamCipher};
@@ -94,7 +107,7 @@ mod xchacha20 {
//
// XChaCha20 test vectors from:
- // <https://tools.ietf.org/id/draft-arciszewski-xchacha-03.html#rfc.appendix.A.3.2>
+ // <https://datatracker.ietf.org/doc/html/draft-arciszewski-xchacha-03#appendix-A.2>
//
const KEY: [u8; 32] = hex!("
@@ -160,7 +173,7 @@ mod xchacha20 {
#[test]
fn xchacha20_encryption() {
let mut cipher = XChaCha20::new(&Key::from(KEY), &XNonce::from(IV));
- let mut buf = PLAINTEXT.clone();
+ let mut buf = PLAINTEXT;
// The test vectors omit the first 64-bytes of the keystream
let mut prefix = [0u8; 64];
@@ -175,11 +188,11 @@ mod xchacha20 {
#[cfg(feature = "legacy")]
#[rustfmt::skip]
mod legacy {
- use chacha20::{ChaCha20Legacy, Key, LegacyNonce};
- use cipher::{NewCipher, StreamCipher, StreamCipherSeek};
+ use chacha20::{ChaCha20Legacy, LegacyNonce};
+ use cipher::{StreamCipher, StreamCipherSeek, KeyIvInit};
use hex_literal::hex;
- cipher::stream_cipher_test!(chacha20_legacy_core, ChaCha20Legacy, "chacha20-legacy");
+ cipher::stream_cipher_test!(chacha20_legacy_core, "chacha20-legacy", ChaCha20Legacy);
cipher::stream_cipher_seek_test!(chacha20_legacy_seek, ChaCha20Legacy);
const KEY_LONG: [u8; 32] = hex!("
@@ -206,15 +219,15 @@ mod legacy {
for middle in idx..256 {
for last in middle..256 {
let mut cipher =
- ChaCha20Legacy::new(&Key::from(KEY_LONG), &LegacyNonce::from(IV_LONG));
+ ChaCha20Legacy::new(&KEY_LONG.into(), &LegacyNonce::from(IV_LONG));
let mut buf = [0; 256];
cipher.seek(idx as u64);
cipher.apply_keystream(&mut buf[idx..middle]);
cipher.apply_keystream(&mut buf[middle..last]);
for k in idx..last {
- assert_eq!(buf[k], EXPECTED_LONG[k])
+ assert_eq!(buf[k], EXPECTED_LONG[k]);
}
}
}
### external/vendor/chacha20/tests/rng.rs
@@ -0,0 +1,552 @@
+//! Random number generator tests.
+
+#![cfg(feature = "rng")]
+
+use chacha20::{
+ ChaCha8Rng, ChaCha12Rng, ChaCha20Rng, SerializedRngState,
+ rand_core::{Rng, SeedableRng},
+};
+use hex_literal::hex;
+
+const KEY: [u8; 32] = hex!("0102030405060708090A0B0C0D0E0F101112131415161718191A1B1C1D1E1F20");
+const STREAM: u64 = 0xF0F1F2F3_F4F5F6F7;
+const BLOCK_WORDS: u8 = 16;
+
+#[test]
+fn test_rng_output() {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ let mut bytes = [0u8; 13];
+
+ rng.fill_bytes(&mut bytes);
+ let expected = hex!("B1697E9FC6461E1983D131CF69");
+ assert_eq!(bytes, expected);
+
+ rng.fill_bytes(&mut bytes);
+ let expected = hex!("A7A3FC134F149880E8BB2B5D23");
+ assert_eq!(bytes, expected);
+}
+
+#[test]
+fn test_chacha_true_values_a() {
+ // Test vectors 1 and 2 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xade0b876, 0x903df1a0, 0xe56a5d40, 0x28bd8653, 0xb819d2bd, 0x1aed8da0, 0xccef36a8,
+ 0xc70d778b, 0x7c5941da, 0x8d485751, 0x3fe02477, 0x374ad8b8, 0xf4b8436a, 0x1ca11815,
+ 0x69b687c3, 0x8665eeb2,
+ ];
+ assert_eq!(results, expected);
+
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xbee7079f, 0x7a385155, 0x7c97ba98, 0x0d082d73, 0xa0290fcb, 0x6965e348, 0x3e53c612,
+ 0xed7aee32, 0x7621b729, 0x434ee69c, 0xb03371d5, 0xd539d874, 0x281fed31, 0x45fb0a51,
+ 0x1f0ae1ac, 0x6f4d794b,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_values_b() {
+ // Test vector 3 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = hex!("0000000000000000000000000000000000000000000000000000000000000001");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ // Skip block 0
+ for _ in 0..16 {
+ rng.next_u32();
+ }
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0x2452eb3a, 0x9249f8ec, 0x8d829d9b, 0xddd4ceb1, 0xe8252083, 0x60818b01, 0xf38422b8,
+ 0x5aaa49c9, 0xbb00ca8e, 0xda3ba7b4, 0xc4b592d1, 0xfdf2732f, 0x4436274e, 0x2561b3c8,
+ 0xebdd4aa6, 0xa0136c00,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_values_c() {
+ // Test vector 4 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ let seed = hex!("00FF000000000000000000000000000000000000000000000000000000000000");
+ let expected = [
+ 0xfb4dd572, 0x4bc42ef1, 0xdf922636, 0x327f1394, 0xa78dea8f, 0x5e269039, 0xa1bebbc1,
+ 0xcaf09aae, 0xa25ab213, 0x48a6b46c, 0x1b9d9bcb, 0x092c5be6, 0x546ca624, 0x1bec45d5,
+ 0x87f47473, 0x96f0992e,
+ ];
+ let expected_end = 3 * 16;
+ let mut results = [0u32; 16];
+
+ // Test block 2 by skipping block 0 and 1
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ for _ in 0..32 {
+ rng1.next_u32();
+ }
+ for i in results.iter_mut() {
+ *i = rng1.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng1.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_word_pos`
+ let mut rng2 = ChaCha20Rng::from_seed(seed);
+ rng2.set_word_pos(2 * 16);
+ for i in results.iter_mut() {
+ *i = rng2.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng2.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_block_pos` and u32
+ let mut rng3 = ChaCha20Rng::from_seed(seed);
+ rng3.set_block_pos(2);
+ results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng3.next_u32();
+ }
+ assert_eq!(results, expected);
+ assert_eq!(rng3.get_word_pos(), expected_end);
+
+ // Test block 2 by using `set_block_pos` and [u8; 8]
+ let mut rng4 = ChaCha20Rng::from_seed(seed);
+ rng4.set_block_pos(2);
+ let mut buf = [0u8; 8];
+ for chunk in expected.chunks_exact(2) {
+ rng4.fill_bytes(&mut buf);
+ assert_eq!(buf[..4], chunk[0].to_le_bytes());
+ assert_eq!(buf[4..], chunk[1].to_le_bytes());
+ }
+ assert_eq!(rng4.get_word_pos(), expected_end);
+
+ // Test skipping behaviour with other types
+ let mut buf = [0u8; 32];
+ rng2.fill_bytes(&mut buf[..]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 8);
+ rng2.fill_bytes(&mut buf[0..25]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 15);
+ rng2.next_u64();
+ assert_eq!(rng2.get_word_pos(), expected_end + 17);
+ rng2.next_u32();
+ rng2.next_u64();
+ assert_eq!(rng2.get_word_pos(), expected_end + 20);
+ rng2.fill_bytes(&mut buf[0..1]);
+ assert_eq!(rng2.get_word_pos(), expected_end + 21);
+}
+
+#[test]
+fn test_chacha_multiple_blocks() {
+ let seed = hex!("0000000001000000020000000300000004000000050000000600000007000000");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ // Store the 17*i-th 32-bit word,
+ // i.e., the i-th word of the i-th 16-word block
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ for _ in 0..16 {
+ rng.next_u32();
+ }
+ }
+ let expected = [
+ 0xf225c81a, 0x6ab1be57, 0x04d42951, 0x70858036, 0x49884684, 0x64efec72, 0x4be2d186,
+ 0x3615b384, 0x11cfa18e, 0xd3c50049, 0x75c775f6, 0x434c6530, 0x2c5bad8f, 0x898881dc,
+ 0x5f1c86d9, 0xc1f8e7f4,
+ ];
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_true_bytes() {
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+ let mut results = [0u8; 32];
+ rng.fill_bytes(&mut results);
+ let expected = hex!("76B8E0ADA0F13D90405D6AE55386BD28BDD219B8A08DED1AA836EFCC8B770DC7");
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_construction() {
+ let seed = hex!("0000000000000000010000000000000002000000000000000300000000000000");
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ assert_eq!(rng1.next_u32(), 137206642);
+
+ assert_eq!(rng1.get_seed(), seed);
+
+ let mut rng2 = ChaCha20Rng::from_rng(&mut rng1);
+ assert_eq!(rng2.next_u32(), 1325750369);
+}
+
+#[test]
+fn test_chacha_nonce() {
+ use hex_literal::hex;
+ // Test vector 5 from
+ // https://www.rfc-editor.org/rfc/rfc8439#section-2.3.2
+ let seed = hex!("000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f");
+ let mut rng = ChaCha20Rng::from_seed(seed);
+
+ rng.set_stream(0x000000004a000000);
+ rng.set_block_pos(u64::from_le_bytes(hex!("0000000000000009")));
+
+ // The test vectors omit the first 64-bytes of the keystream
+ let mut discard_first_64 = [0u8; 64];
+ rng.fill_bytes(&mut discard_first_64);
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0xe4e7f110, 0x15593bd1, 0x1fdd0f50, 0xc47120a3, 0xc7f4d1c7, 0x0368c033, 0x9aaa2204,
+ 0x4e6cd4c3, 0x466482d2, 0x09aa9f07, 0x05d7c214, 0xa2028bd9, 0xd19c12b5, 0xb94e16de,
+ 0xe883d0cb, 0x4e3c50a2,
+ ];
+
+ assert_eq!(results, expected);
+}
+
+#[test]
+fn test_chacha_nonce_2() {
+ // Test vector 5 from
+ // https://tools.ietf.org/html/draft-nir-cfrg-chacha20-poly1305-04
+ // Although we do not support setting a nonce, we try it here anyway so
+ // we can use this test vector.
+ let seed = [0u8; 32];
+ let mut rng = ChaCha20Rng::from_seed(seed);
+ // 96-bit nonce in LE order is: 0,0,0,0, 0,0,0,0, 0,0,0,2
+ rng.set_stream(2u64 << (24 + 32));
+
+ let mut results = [0u32; 16];
+ for i in results.iter_mut() {
+ *i = rng.next_u32();
+ }
+ let expected = [
+ 0x374dc6c2, 0x3736d58c, 0xb904e24a, 0xcd3f93ef, 0x88228b1a, 0x96a4dfb3, 0x5b76ab72,
+ 0xc727ee54, 0x0e0e978a, 0xf3145c95, 0x1b748ea8, 0xf786c297, 0x99c28f5f, 0x628314e8,
+ 0x398a19fa, 0x6ded1b53,
+ ];
+ assert_eq!(results, expected);
+}
+
+/// Test vector 9 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
+#[test]
+fn counter_wrap_1() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+ let block_pos = 18446744073709551615;
+ assert_eq!(block_pos, u64::MAX);
+ rng.set_block_pos(block_pos);
+
+ let mut output = [0u8; 64 * 3];
+ rng.fill_bytes(&mut output);
+ let expected = hex!(
+ "d7918cd8620cf832532652c04c01a553092cfb32e7b3f2f5467ae9674a2e9eec17368e"
+ "c8027a357c0c51e6ea747121fec45284be0f099d2b3328845607b1768976b8e0ada0f1"
+ "3d90405d6ae55386bd28bdd219b8a08ded1aa836efcc8b770dc7da41597c5157488d77"
+ "24e03fb8d84a376a43b8f41518a11cc387b669b2ee65869f07e7be5551387a98ba977c"
+ "732d080dcb0f29a048e3656912c6533e32ee7aed29b721769ce64e43d57133b074d839"
+ "d531ed1f28510afb45ace10a1f4b794d6f"
+ );
+ assert_eq!(expected, output);
+}
+
+/// Counts how many bytes were incorrect, and returns:
+///
+/// (`index_of_first_incorrect_word`, `num_incorrect_bytes`)
+fn count_incorrect_bytes(expected: &[u8], output: &[u8]) -> (Option<usize>, u32) {
+ assert_eq!(expected.len(), output.len());
+ let mut num_incorrect_bytes = 0;
+ let mut index_of_first_incorrect_word = None;
+ expected
+ .iter()
+ .enumerate()
+ .zip(output.iter())
+ .for_each(|((i, a), b)| {
+ if a.ne(b) {
+ if index_of_first_incorrect_word.is_none() {
+ index_of_first_incorrect_word = Some(i / 4);
+ }
+ num_incorrect_bytes += 1;
+ }
+ });
+ (index_of_first_incorrect_word, num_incorrect_bytes)
+}
+
+/// Test vector 8 from https://github.com/pyca/cryptography/blob/main/vectors/cryptography_vectors/ciphers/ChaCha20/counter-overflow.txt
+#[test]
+fn counter_overflow_and_diagnostics() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+ let block_pos = 4294967295;
+ assert_eq!(block_pos, u64::from(u32::MAX));
+ rng.set_block_pos(4294967295);
+
+ let mut output = [0u8; 64 * 4];
+ rng.fill_bytes(&mut output[..64 * 3]);
+ let block_before_overflow = hex!(
+ "ace4cd09e294d1912d4ad205d06f95d9c2f2bfcf453e8753f128765b62215f4d92c74f"
+ "2f626c6a640c0b1284d839ec81f1696281dafc3e684593937023b58b1d"
+ );
+ let first_block_after_overflow = hex!(
+ "3db41d3aa0d329285de6f225e6e24bd59c9a17006943d5c9b680e3873bdc683a581946"
+ "9899989690c281cd17c96159af0682b5b903468a61f50228cf09622b5a"
+ );
+ let second_block_after_overflow = hex!(
+ "46f0f6efee15c8f1b198cb49d92b990867905159440cc723916dc0012826981039ce17"
+ "66aa2542b05db3bd809ab142489d5dbfe1273e7399637b4b3213768aaa"
+ );
+ assert!(
+ output[..64].eq(&block_before_overflow),
+ "The first parblock was incorrect before overflow, indicating that ChaCha was not implemented correctly for this backend. Check the rounds() fn or the functions that it calls"
+ );
+
+ rng.set_block_pos(u64::from(u32::MAX) - 1);
+ let mut skipped_blocks = [0u8; 64 * 3];
+ rng.fill_bytes(&mut skipped_blocks);
+ rng.fill_bytes(&mut output[64 * 3..]);
+
+ output.chunks_exact(64).enumerate().skip(1).zip(&[first_block_after_overflow, second_block_after_overflow, second_block_after_overflow]).for_each(|((i, a), b)| {
+ let (index_of_first_incorrect_word, num_incorrect_bytes) = count_incorrect_bytes(a, b);
+ let msg = if num_incorrect_bytes == 0 {
+ "The block was correct and this will not be shown"
+ } else if num_incorrect_bytes > 32 {
+ "Most of the block was incorrect, indicating an issue with the counter using 32-bit addition towards the beginning of fn rounds()"
+ } else if num_incorrect_bytes <= 8 && matches!(index_of_first_incorrect_word, Some(12 | 13)) {
+ "When the state was added to the results/res buffer at the end of fn rounds, the counter was probably incremented in 32-bit fashion for this parblock"
+ } else {
+ // this is probably unreachable in the event of a failed assertion, but it depends on the seed
+ "Some of the block was incorrect"
+ };
+ assert!(a.eq(b), "PARBLOCK #{} uses incorrect counter addition\nDiagnostic = {}\nnum_incorrect_bytes = {}\nindex_of_first_incorrect_word = {:?}", i + 1, msg, num_incorrect_bytes, index_of_first_incorrect_word);
+ });
+}
+
+#[test]
+fn test_wrapping_add() {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ // test counter wrapping-add
+ rng.set_word_pos((1 << 68) - 65);
+ let mut output = [3u8; 1280];
+ rng.fill_bytes(&mut output);
+
+ assert_ne!(output, [0u8; 1280]);
+
+ assert!(rng.get_word_pos() < 2000);
+ assert!(rng.get_word_pos() != 0);
+}
+
+#[test]
+fn test_chacha_clone_streams() {
+ let seed = [
+ 0, 0, 0, 0, 1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0, 7, 0,
+ 0, 0,
+ ];
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ let mut rng2 = ChaCha20Rng::from_seed(seed);
+ for _ in 0..16 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+
+ rng1.set_stream(51);
+ assert_eq!(rng1.get_stream(), 51);
+ assert_eq!(rng2.get_stream(), 0);
+ let mut fill_1 = [0u8; 7];
+ rng1.fill_bytes(&mut fill_1);
+ let mut fill_2 = [0u8; 7];
+ rng2.fill_bytes(&mut fill_2);
+ assert_ne!(fill_1, fill_2);
+ for _ in 0..7 {
+ assert!(rng1.next_u64() != rng2.next_u64());
+ }
+ rng2.set_stream(51); // switch part way through block
+ for _ in 7..16 {
+ assert_ne!(rng1.next_u64(), rng2.next_u64());
+ }
+ rng1.set_stream(51);
+ rng2.set_stream(51);
+ for _ in 0..16 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+}
+
+#[test]
+fn test_chacha_word_pos_wrap_exact() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ // refilling the buffer in set_word_pos will wrap the block counter to 0
+ let last_block = (1 << 68) - u128::from(4 * BLOCK_WORDS);
+ rng.set_word_pos(last_block);
+ assert_eq!(rng.get_word_pos(), last_block);
+}
+
+#[test]
+fn test_chacha_word_pos_wrap_excess() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ // refilling the buffer in set_word_pos will wrap the block counter past 0
+ let last_block = (1 << 68) - u128::from(BLOCK_WORDS);
+ rng.set_word_pos(last_block);
+ assert_eq!(rng.get_word_pos(), last_block);
+}
+
+#[test]
+fn test_chacha_word_pos_zero() {
+ let mut rng = ChaCha20Rng::from_seed(Default::default());
+ assert_eq!(rng.get_word_pos(), 0);
+ rng.set_word_pos(0);
+ assert_eq!(rng.get_word_pos(), 0);
+}
+
+#[test]
+#[allow(trivial_casts)]
+fn test_trait_objects() {
+ use rand_core::CryptoRng;
+
+ let seed = Default::default();
+ let mut rng1 = ChaCha20Rng::from_seed(seed);
+ let rng2 = &mut ChaCha20Rng::from_seed(seed) as &mut dyn CryptoRng;
+ for _ in 0..1000 {
+ assert_eq!(rng1.next_u64(), rng2.next_u64());
+ }
+}
+
+/// If this test fails, the backend may not be
+/// performing 64-bit addition.
+#[test]
+fn counter_wrapping_64_bit_counter() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+
+ // get first four blocks and word pos
+ let mut first_blocks = [0u8; 64 * 4];
+ rng.fill_bytes(&mut first_blocks);
+ let first_blocks_end_word_pos = rng.get_word_pos();
+ let first_blocks_end_block_counter = rng.get_block_pos();
+
+ // get first four blocks after wrapping
+ rng.set_block_pos(u64::MAX);
+ let mut result = [0u8; 64 * 5];
+ rng.fill_bytes(&mut result);
+ assert_eq!(first_blocks_end_word_pos, rng.get_word_pos());
+ assert_eq!(first_blocks_end_block_counter, rng.get_block_pos());
+
+ if first_blocks[0..64 * 4].ne(&result[64..]) {
+ for (i, (a, b)) in first_blocks.iter().zip(result.iter().skip(64)).enumerate() {
+ assert!(!a.ne(b), "i = {}\na = {}\nb = {}", i, a, b);
+ }
+ }
+ assert_eq!(&first_blocks[0..64 * 4], &result[64..]);
+}
+
+/// If this test fails, the backend may be doing 32-bit addition.
+#[test]
+fn counter_not_wrapping_at_32_bits() {
+ let mut rng = ChaCha20Rng::from_seed([0u8; 32]);
+
+ // get first four blocks and word pos
+ let mut first_blocks = [0u8; 64 * 4];
+ rng.fill_bytes(&mut first_blocks);
+ let first_blocks_end_word_pos = rng.get_word_pos();
+
+ // get first four blocks after the supposed overflow
+ rng.set_block_pos(u64::from(u32::MAX));
+ let mut result = [0u8; 64 * 5];
+ rng.fill_bytes(&mut result);
+ assert_ne!(first_blocks_end_word_pos, rng.get_word_pos());
+ assert_eq!(
+ rng.get_word_pos(),
+ first_blocks_end_word_pos + (1 << 32) * u128::from(BLOCK_WORDS)
+ );
+ assert_ne!(&first_blocks[0..64 * 4], &result[64..]);
+}
+
+#[test]
+fn test_chacha8rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha8Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha8Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_chacha12rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha12Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha12Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_chacha20rng_serde_roundtrip() {
+ for skip_words in 0..100 {
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..skip_words {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ let mut rng2 = ChaCha20Rng::deserialize_state(&state);
+ for _ in 0..100 {
+ assert_eq!(rng.next_u32(), rng2.next_u32());
+ }
+ }
+}
+
+#[test]
+fn test_rng_serialized_state_stability() {
+ const EXPECTED: SerializedRngState = hex!(
+ "0102030405060708090A0B0C0D0E0F10"
+ "1112131415161718191A1B1C1D1E1F20"
+ "F7F6F5F4F3F2F1F06400000000000000"
+ "00"
+ );
+ let mut rng = ChaCha8Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+
+ let mut rng = ChaCha12Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+
+ let mut rng = ChaCha20Rng::from_seed(KEY);
+ rng.set_stream(STREAM);
+ for _ in 0..100 {
+ let _ = rng.next_u32();
+ }
+ let state = rng.serialize_state();
+ assert_eq!(state, EXPECTED);
+}
### external/vendor/chacha20poly1305/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"45a5fe10d6ba27fda2383958a2b2857fd8b55ce0ce4bea756d6eb065d5b9c6ce","CHANGELOG.md":"8643ef9b1f3920b7a210f0cd74fa93879c68e714cbd2ea45342729484f93e26b","Cargo.toml":"30017fe65d213d042250021badd66f323b8cbadbf95e693ef0c5e250799a0dd0","Cargo.toml.orig":"97a035c2f8eaf86bbcdedb4e74d1769741c3efe3324f5374308766e7aa657cf4","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"3c0dfa33fd2e6976038555b52095699452653b1fcabe113074f14e0848a6b11e","README.md":"cc9139618cff4acc0fb2cd09cefcd1c8a6f425bb4bc83668e07498c3202d9ee1","src/cipher.rs":"70f718a5fd9296f08b16fe42496103033b0150d7cfbb9baca012e2fb51fe8d4a","src/lib.rs":"e454914d6e98c3889cebc92c2eb9a1a43d23f60ca028df0954b55041bfed0d30","tests/data/wycheproof_chacha20poly1305.blb":"8bab32d17e5719eafdfca4adae8d85d5a67c800b7356647cd6b8f73eaa2459cb","tests/data/wycheproof_xchacha20poly1305.blb":"b1fcfcb93bc387431b390957214270e53a77746919c9fdfaf62c311d8836c687","tests/lib.rs":"00219ea42ae569919af93fe30a8c9ce1eb1aca2f26d44e011594850ab0b161c8"},"package":"10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"6c640f7d3c4b878f5efaee675685f09bbca18b84880d4b55f7b676165a81e33f","CHANGELOG.md":"58c36da6ae24394c5e39a2c494e93b88db4a22b6a4641d490bff59f025930064","Cargo.lock":"a66fb2e2410eaa5f94660d30cfad3eb172b43571f2bf4995b036ac237051063d","Cargo.toml":"7ec6e52abfdaf2440a83823ab022b76c366319bc4c610dd51e8b9d0b533b12dc","Cargo.toml.orig":"3b17182be9bcc2b818b6214a4a6fe18d0fa22492d23cdcaab4fc41251c3f9bed","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"b8c6939380a400f53e11923d50fcc4dd2fa1ba8339fd9d04cda38a0251b6c9b0","README.md":"3ef6cfd941096d8ce8dda11058eb59cb0252fa08ebc4dfbc7adb44e33c5f60ea","src/cipher.rs":"96c6c14e10f0c81b78b743a2f8f74db2c9325e78119f7ff81a467af2f65958ad","src/lib.rs":"c5735fcb58bdd9c03975a376eb40b4e8698790f3ad72282823cfbdc2aa90335f","tests/data/wycheproof_chacha20poly1305_fail.blb":"2f0905a07a45c1d7955c0777617c98b701664c8f021f40d1ab60e7f0c5f8daaf","tests/data/wycheproof_chacha20poly1305_pass.blb":"87695fa84e7d146aad3a8b3290bf19e3cebf4e774ce3a8b56156f9418c28886b","tests/data/wycheproof_xchacha20poly1305_fail.blb":"b2a1c5222b93a0222a3c3ac71c5e2d46be3ab94eab7a77c8a84ada129c47cfd7","tests/data/wycheproof_xchacha20poly1305_pass.blb":"62d0cc0e50c121f59ddc0eb47fb74efe02f743970cb6eacb823062084ed62362","tests/lib.rs":"02b398b55dd393d896e2f111f202e86c72779036527a2afbc662bd41e1a29006"},"package":"9b89e1c441e926b9c82a8d023f6e1b7ae0adcfaa7d621814e4d60789bac751cb"}
\ No newline at end of file
### external/vendor/chacha20poly1305/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "746f70a5f6c7371e723dc64e04f2115b56f24d27"
+ "sha1": "e37a978ccf0992d9053fbc039470d6527108e393"
},
"path_in_vcs": "chacha20poly1305"
}
\ No newline at end of file
### external/vendor/chacha20poly1305/CHANGELOG.md
@@ -4,6 +4,28 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.11.0 (2026-06-28)
+### Added
+- `bytes` feature passthrough ([#631])
+
+### Changed
+- Bump `aead` from `0.5` to `0.6` ([#831])
+- Bump `chacha20` from `0.9` to `0.10` ([#796])
+- Bump `cipher` from `0.4` to `0.5` ([#583])
+- Bump `poly1305` from `0.8` to `0.9` ([#823])
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#662])
+- Relax MSRV policy and allow MSRV bumps in patch releases
+
+### Removed
+- `std` and `stream` features ([#662])
+
+[#583]: https://github.com/RustCrypto/AEADs/pull/583
+[#631]: https://github.com/RustCrypto/AEADs/pull/631
+[#662]: https://github.com/RustCrypto/AEADs/pull/662
+[#796]: https://github.com/RustCrypto/AEADs/pull/796
+[#823]: https://github.com/RustCrypto/AEADs/pull/823
+[#831]: https://github.com/RustCrypto/AEADs/pull/831
+
## 0.10.1 (2022-08-09)
### Added
- `rand_core` feature ([#467])
### external/vendor/chacha20poly1305/Cargo.lock
@@ -0,0 +1,198 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "aead"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "1973cfbc1a2daf9cf550e74e1f088c28e7f7d8c1e1418fb6c9dc5184b7e84c99"
+dependencies = [
+ "arrayvec",
+ "blobby",
+ "bytes",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "arrayvec"
+version = "0.7.7"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f02882884d3e1bc524fb12c79f107f6ad0e1cfd498c536ffb494301740995dfe"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "bytes"
+version = "1.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "chacha20"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d524456ba66e72eb8b115ff89e01e497f8e6d11d78b70b1aa13c0fbd97540a81"
+dependencies = [
+ "cfg-if",
+ "cipher",
+ "cpufeatures",
+ "zeroize",
+]
+
+[[package]]
+name = "chacha20poly1305"
+version = "0.11.0"
+dependencies = [
+ "aead",
+ "chacha20",
+ "cipher",
+ "poly1305",
+ "zeroize",
+]
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"
+dependencies = [
+ "block-buffer",
+ "crypto-common",
+ "inout",
+]
+
+[[package]]
+name = "cmov"
+version = "0.5.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0c9ea0ac24bc397ab3c98583a3c9ba74fa56b09a4449bbe172b9b1ddb016027a"
+
+[[package]]
+name = "cpufeatures"
+version = "0.3.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201"
+dependencies = [
+ "libc",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[package]]
+name = "ctutils"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7d5515a3834141de9eafb9717ad39eea8247b5674e6066c404e8c4b365d2a29e"
+dependencies = [
+ "cmov",
+]
+
+[[package]]
+name = "getrandom"
+version = "0.4.3"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+]
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "libc"
+version = "0.2.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "poly1305"
+version = "0.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "a00baa632505d05512f48a963e16051c54fda9a95cc9acea1a4e3c90991c4a2e"
+dependencies = [
+ "cpufeatures",
+ "universal-hash",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "typenum"
+version = "1.20.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
+
+[[package]]
+name = "universal-hash"
+version = "0.6.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f4987bdc12753382e0bec4a65c50738ffaabc998b9cdd1f952fb5f39b0048a96"
+dependencies = [
+ "crypto-common",
+ "ctutils",
+]
+
+[[package]]
+name = "zeroize"
+version = "1.9.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
### external/vendor/chacha20poly1305/Cargo.toml
@@ -10,17 +10,25 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
+edition = "2024"
+rust-version = "1.85"
name = "chacha20poly1305"
-version = "0.10.1"
+version = "0.11.0"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = """
Pure Rust implementation of the ChaCha20Poly1305 Authenticated Encryption
with Additional Data Cipher (RFC 8439) with optional architecture-specific
hardware acceleration. Also contains implementations of the XChaCha20Poly1305
extended nonce variant of ChaCha20Poly1305, and the reduced-round
ChaCha8Poly1305 and ChaCha12Poly1305 lightweight variants.
"""
+homepage = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
documentation = "https://docs.rs/chacha20poly1305"
readme = "README.md"
keywords = [
@@ -35,53 +43,96 @@ categories = [
"no-std",
]
license = "Apache-2.0 OR MIT"
-repository = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+repository = "https://github.com/RustCrypto/AEADs"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = ["aead/alloc"]
+arrayvec = ["aead/arrayvec"]
+bytes = ["aead/bytes"]
+default = [
+ "alloc",
+ "getrandom",
]
+getrandom = ["aead/getrandom"]
+rand_core = ["aead/rand_core"]
+reduced-round = []
+zeroize = [
+ "dep:zeroize",
+ "chacha20/zeroize",
+]
+
+[lib]
+name = "chacha20poly1305"
+path = "src/lib.rs"
+
+[[test]]
+name = "lib"
+path = "tests/lib.rs"
[dependencies.aead]
-version = "0.5"
+version = "0.6"
default-features = false
[dependencies.chacha20]
-version = "0.9"
-features = ["zeroize"]
+version = "0.10"
+features = ["xchacha"]
+default-features = false
[dependencies.cipher]
-version = "0.4"
+version = "0.5"
[dependencies.poly1305]
-version = "0.8"
+version = "0.9"
[dependencies.zeroize]
-version = "1.5"
+version = "1.8"
+optional = true
default-features = false
[dev-dependencies.aead]
-version = "0.5"
+version = "0.6"
features = ["dev"]
default-features = false
-[features]
-alloc = ["aead/alloc"]
-default = [
- "alloc",
- "getrandom",
-]
-getrandom = [
- "aead/getrandom",
- "rand_core",
-]
-heapless = ["aead/heapless"]
-rand_core = ["aead/rand_core"]
-reduced-round = []
-std = [
- "aead/std",
- "alloc",
-]
-stream = ["aead/stream"]
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unsafe_code = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/chacha20poly1305/Cargo.toml.orig
@@ -1,6 +1,6 @@
[package]
name = "chacha20poly1305"
-version = "0.10.1"
+version = "0.11.0"
description = """
Pure Rust implementation of the ChaCha20Poly1305 Authenticated Encryption
with Additional Data Cipher (RFC 8439) with optional architecture-specific
@@ -9,34 +9,38 @@ extended nonce variant of ChaCha20Poly1305, and the reduced-round
ChaCha8Poly1305 and ChaCha12Poly1305 lightweight variants.
"""
authors = ["RustCrypto Developers"]
-edition = "2021"
+edition = "2024"
license = "Apache-2.0 OR MIT"
readme = "README.md"
documentation = "https://docs.rs/chacha20poly1305"
-repository = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+homepage = "https://github.com/RustCrypto/AEADs/tree/master/chacha20poly1305"
+repository = "https://github.com/RustCrypto/AEADs"
keywords = ["aead", "chacha20", "poly1305", "xchacha20", "xchacha20poly1305"]
categories = ["cryptography", "no-std"]
+rust-version = "1.85"
[dependencies]
-aead = { version = "0.5", default-features = false }
-chacha20 = { version = "0.9", features = ["zeroize"] }
-cipher = "0.4"
-poly1305 = "0.8"
-zeroize = { version = "1.5", default-features = false }
+aead = { version = "0.6", default-features = false }
+chacha20 = { version = "0.10", default-features = false, features = ["xchacha"] }
+cipher = "0.5"
+poly1305 = "0.9"
+zeroize = { version = "1.8", optional = true, default-features = false }
[dev-dependencies]
-aead = { version = "0.5", features = ["dev"], default-features = false }
+aead = { version = "0.6", features = ["dev"], default-features = false }
[features]
-default = ["alloc", "getrandom"]
-std = ["aead/std", "alloc"]
-alloc = ["aead/alloc"]
-getrandom = ["aead/getrandom", "rand_core"]
-heapless = ["aead/heapless"]
-rand_core = ["aead/rand_core"]
+default = ["alloc", "getrandom"]
+alloc = ["aead/alloc"]
+arrayvec = ["aead/arrayvec"]
+bytes = ["aead/bytes"]
+getrandom = ["aead/getrandom"]
+rand_core = ["aead/rand_core"]
reduced-round = []
-stream = ["aead/stream"]
+zeroize = ["dep:zeroize", "chacha20/zeroize"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/chacha20poly1305/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2019 The RustCrypto Project Developers
+Copyright (c) 2019-2026 The RustCrypto Project Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/chacha20poly1305/README.md
@@ -48,8 +48,8 @@ certain 32-bit PowerPC CPUs and some non-ARM microcontrollers).
Licensed under either of:
- * [Apache License, Version 2.0](http://www.apache.org/licenses/LICENSE-2.0)
- * [MIT license](http://opensource.org/licenses/MIT)
+ * [Apache License, Version 2.0](https://www.apache.org/licenses/LICENSE-2.0)
+ * [MIT license](https://opensource.org/licenses/MIT)
at your option.
@@ -61,12 +61,12 @@ dual licensed as above, without any additional terms or conditions.
[//]: # (badges)
-[crate-image]: https://buildstats.info/crate/chacha20poly1305
+[crate-image]: https://img.shields.io/crates/v/chacha20poly1305
[crate-link]: https://crates.io/crates/chacha20poly1305
[docs-image]: https://docs.rs/chacha20poly1305/badge.svg
[docs-link]: https://docs.rs/chacha20poly1305/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.56+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260038-AEADs
[downloads-image]: https://img.shields.io/crates/d/chacha20poly1305.svg
@@ -79,5 +79,5 @@ dual licensed as above, without any additional terms or conditions.
[2]: https://en.wikipedia.org/wiki/Authenticated_encryption
[3]: https://github.com/RustCrypto/stream-ciphers/tree/master/chacha20
[4]: https://github.com/RustCrypto/universal-hashes/tree/master/poly1305
-[5]: https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
+[5]: https://web.archive.org/web/20200606025324/https://research.nccgroup.com/2020/02/26/public-report-rustcrypto-aes-gcm-and-chacha20poly1305-implementation-review/
[6]: https://www.mobilecoin.com/
### external/vendor/chacha20poly1305/src/cipher.rs
@@ -1,13 +1,12 @@
//! Core AEAD cipher implementation for (X)ChaCha20Poly1305.
use ::cipher::{StreamCipher, StreamCipherSeek};
-use aead::generic_array::GenericArray;
use aead::Error;
+use aead::{array::Array, inout::InOutBuf};
use poly1305::{
- universal_hash::{KeyInit, UniversalHash},
Poly1305,
+ universal_hash::{KeyInit, UniversalHash},
};
-use zeroize::Zeroize;
use super::Tag;
@@ -16,7 +15,7 @@ const BLOCK_SIZE: usize = 64;
/// Maximum number of blocks that can be encrypted with ChaCha20 before the
/// counter overflows.
-const MAX_BLOCKS: usize = core::u32::MAX as usize;
+const MAX_BLOCKS: usize = u32::MAX as usize;
/// ChaCha20Poly1305 instantiated with a particular nonce
pub(crate) struct Cipher<C>
@@ -35,10 +34,14 @@ where
pub(crate) fn new(mut cipher: C) -> Self {
// Derive Poly1305 key from the first 32-bytes of the ChaCha20 keystream
let mut mac_key = poly1305::Key::default();
- cipher.apply_keystream(&mut *mac_key);
+ cipher.apply_keystream(&mut mac_key);
- let mac = Poly1305::new(GenericArray::from_slice(&*mac_key));
- mac_key.zeroize();
+ let mac = Poly1305::new(&mac_key);
+ #[cfg(feature = "zeroize")]
+ {
+ use zeroize::Zeroize;
+ mac_key.zeroize();
+ }
// Set ChaCha20 counter to 1
cipher.seek(BLOCK_SIZE as u64);
@@ -47,10 +50,10 @@ where
}
/// Encrypt the given message in-place, returning the authentication tag
- pub(crate) fn encrypt_in_place_detached(
+ pub(crate) fn encrypt_inout_detached(
mut self,
associated_data: &[u8],
- buffer: &mut [u8],
+ mut buffer: InOutBuf<'_, '_, u8>,
) -> Result<Tag, Error> {
if buffer.len() / BLOCK_SIZE >= MAX_BLOCKS {
return Err(Error);
@@ -60,34 +63,34 @@ where
// TODO(tarcieri): interleave encryption with Poly1305
// See: <https://github.com/RustCrypto/AEADs/issues/74>
- self.cipher.apply_keystream(buffer);
- self.mac.update_padded(buffer);
+ self.cipher.apply_keystream_inout(buffer.reborrow());
+ self.mac.update_padded(buffer.get_out());
- self.authenticate_lengths(associated_data, buffer)?;
+ self.authenticate_lengths(associated_data, buffer.get_out())?;
Ok(self.mac.finalize())
}
/// Decrypt the given message, first authenticating ciphertext integrity
/// and returning an error if it's been tampered with.
- pub(crate) fn decrypt_in_place_detached(
+ pub(crate) fn decrypt_inout_detached(
mut self,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
tag: &Tag,
) -> Result<(), Error> {
if buffer.len() / BLOCK_SIZE >= MAX_BLOCKS {
return Err(Error);
}
self.mac.update_padded(associated_data);
- self.mac.update_padded(buffer);
- self.authenticate_lengths(associated_data, buffer)?;
+ self.mac.update_padded(buffer.get_in());
+ self.authenticate_lengths(associated_data, buffer.get_in())?;
// This performs a constant-time comparison using the `subtle` crate
if self.mac.verify(tag).is_ok() {
// TODO(tarcieri): interleave decryption with Poly1305
// See: <https://github.com/RustCrypto/AEADs/issues/74>
- self.cipher.apply_keystream(buffer);
+ self.cipher.apply_keystream_inout(buffer);
Ok(())
} else {
Err(Error)
@@ -99,7 +102,7 @@ where
let associated_data_len: u64 = associated_data.len().try_into().map_err(|_| Error)?;
let buffer_len: u64 = buffer.len().try_into().map_err(|_| Error)?;
- let mut block = GenericArray::default();
+ let mut block = Array::default();
block[..8].copy_from_slice(&associated_data_len.to_le_bytes());
block[8..].copy_from_slice(&buffer_len.to_le_bytes());
self.mac.update(&[block]);
### external/vendor/chacha20poly1305/src/lib.rs
@@ -5,7 +5,6 @@
html_logo_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg",
html_favicon_url = "https://raw.githubusercontent.com/RustCrypto/meta/master/logo.svg"
)]
-#![warn(missing_docs, rust_2018_idioms)]
//! ## Supported Algorithms
//!
@@ -14,26 +13,31 @@
//!
//! - [`XChaCha20Poly1305`] - ChaCha20Poly1305 variant with an extended 192-bit (24-byte) nonce.
//! - [`ChaCha8Poly1305`] / [`ChaCha12Poly1305`] - non-standard, reduced-round variants
-//! (gated under the `reduced-round` Cargo feature). See the [Too Much Crypto][5]
+//! (gated under the `reduced-round` Cargo feature). See the
+//! [Too Much Crypto](https://eprint.iacr.org/2019/1492.pdf)
//! paper for background and rationale on when these constructions could be used.
//! When in doubt, prefer [`ChaCha20Poly1305`].
-//! - [`XChaCha8Poly1305`] / [`XChaCha12Poly1305`] - same as above,
-//! but with an extended 192-bit (24-byte) nonce.
+//! - [`XChaCha8Poly1305`] / [`XChaCha12Poly1305`] - same as above, but with an extended
+//! 192-bit (24-byte) nonce.
//!
//! # Usage
//!
-#![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")]
-#![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+#![cfg_attr(feature = "getrandom", doc = "```")]
+#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `getrandom` feature is enabled
+//!
//! use chacha20poly1305::{
-//! aead::{Aead, AeadCore, KeyInit, OsRng},
+//! aead::{Aead, AeadCore, Generate, Key, KeyInit},
//! ChaCha20Poly1305, Nonce
//! };
//!
-//! let key = ChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<ChaCha20Poly1305>::generate();
//! let cipher = ChaCha20Poly1305::new(&key);
-//! let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
+//!
+//! let nonce = Nonce::generate(); // MUST be unique per message
//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
+//!
//! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?;
//! assert_eq!(&plaintext, b"plaintext message");
//! # Ok(())
@@ -45,46 +49,48 @@
//! This crate has an optional `alloc` feature which can be disabled in e.g.
//! microcontroller environments that don't have a heap.
//!
-//! The [`AeadInPlace::encrypt_in_place`] and [`AeadInPlace::decrypt_in_place`]
+//! The [`AeadInOut::encrypt_in_place`] and [`AeadInOut::decrypt_in_place`]
//! methods accept any type that impls the [`aead::Buffer`] trait which
//! contains the plaintext for encryption or ciphertext for decryption.
//!
-//! Note that if you enable the `heapless` feature of this crate,
-//! you will receive an impl of [`aead::Buffer`] for `heapless::Vec`
-//! (re-exported from the [`aead`] crate as [`aead::heapless::Vec`]),
-//! which can then be passed as the `buffer` parameter to the in-place encrypt
+//! Enabling the `arrayvec` feature of this crate will provide an impl of
+//! [`aead::Buffer`] for `arrayvec::ArrayVec` (re-exported from the [`aead`] crate as
+//! [`aead::arrayvec::ArrayVec`]), and enabling the `bytes` feature of this crate will
+//! provide an impl of [`aead::Buffer`] for `bytes::BytesMut` (re-exported from the
+//! [`aead`] crate as [`aead::bytes::BytesMut`]).
+//!
+//! It can then be passed as the `buffer` parameter to the in-place encrypt
//! and decrypt methods:
//!
+#![cfg_attr(all(feature = "getrandom", feature = "arrayvec"), doc = "```")]
#![cfg_attr(
- all(feature = "getrandom", feature = "heapless", feature = "std"),
- doc = "```"
-)]
-#![cfg_attr(
- not(all(feature = "getrandom", feature = "heapless", feature = "std")),
+ not(all(feature = "getrandom", feature = "arrayvec")),
doc = "```ignore"
)]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `arrayvec` and `getrandom` features are enabled
+//!
//! use chacha20poly1305::{
-//! aead::{AeadCore, AeadInPlace, KeyInit, OsRng, heapless::Vec},
+//! aead::{AeadCore, AeadInOut, Generate, Key, KeyInit, arrayvec::ArrayVec},
//! ChaCha20Poly1305, Nonce,
//! };
//!
-//! let key = ChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<ChaCha20Poly1305>::generate();
//! let cipher = ChaCha20Poly1305::new(&key);
-//! let nonce = ChaCha20Poly1305::generate_nonce(&mut OsRng); // 96-bits; unique per message
//!
-//! let mut buffer: Vec<u8, 128> = Vec::new(); // Note: buffer needs 16-bytes overhead for auth tag
-//! buffer.extend_from_slice(b"plaintext message");
+//! let nonce = Nonce::generate(); // MUST be unique per message
+//! let mut buffer: ArrayVec<u8, 128> = ArrayVec::new(); // Note: buffer needs 16-bytes overhead for auth tag
+//! buffer.try_extend_from_slice(b"plaintext message").unwrap();
//!
//! // Encrypt `buffer` in-place, replacing the plaintext contents with ciphertext
//! cipher.encrypt_in_place(&nonce, b"", &mut buffer)?;
//!
//! // `buffer` now contains the message ciphertext
-//! assert_ne!(&buffer, b"plaintext message");
+//! assert_ne!(buffer.as_ref(), b"plaintext message");
//!
//! // Decrypt `buffer` in-place, replacing its ciphertext context with the original plaintext
//! cipher.decrypt_in_place(&nonce, b"", &mut buffer)?;
-//! assert_eq!(&buffer, b"plaintext message");
+//! assert_eq!(buffer.as_ref(), b"plaintext message");
//! # Ok(())
//! # }
//! ```
@@ -107,28 +113,30 @@
//! proof from the XSalsa20 paper to the construction in order to demonstrate
//! that XChaCha20 is secure if ChaCha20 is secure (see Section 3.1):
//!
-//! <https://tools.ietf.org/html/draft-arciszewski-xchacha-03>
+//! <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha>
//!
//! It is worth noting that NaCl/libsodium's default "secretbox" algorithm is
//! XSalsa20Poly1305, not XChaCha20Poly1305, and thus not compatible with
//! this library. If you are interested in that construction, please see the
-//! `xsalsa20poly1305` crate:
+//! `crypto_secretbox` crate:
//!
-//! <https://docs.rs/xsalsa20poly1305/>
+//! <https://docs.rs/crypto_secretbox/>
//!
//! # Usage
//!
-#![cfg_attr(all(feature = "getrandom", feature = "std"), doc = "```")]
-#![cfg_attr(not(all(feature = "getrandom", feature = "std")), doc = "```ignore")]
-//! # fn main() -> Result<(), Box<dyn std::error::Error>> {
+#![cfg_attr(feature = "getrandom", doc = "```")]
+#![cfg_attr(not(feature = "getrandom"), doc = "```ignore")]
+//! # fn main() -> Result<(), Box<dyn core::error::Error>> {
+//! // NOTE: requires the `getrandom` feature is enabled
+//!
//! use chacha20poly1305::{
-//! aead::{Aead, AeadCore, KeyInit, OsRng},
+//! aead::{Aead, AeadCore, Generate, Key, KeyInit},
//! XChaCha20Poly1305, XNonce
//! };
//!
-//! let key = XChaCha20Poly1305::generate_key(&mut OsRng);
+//! let key = Key::<XChaCha20Poly1305>::generate();
//! let cipher = XChaCha20Poly1305::new(&key);
-//! let nonce = XChaCha20Poly1305::generate_nonce(&mut OsRng); // 192-bits; unique per message
+//! let nonce = XNonce::generate(); // MUST be unique per message
//! let ciphertext = cipher.encrypt(&nonce, b"plaintext message".as_ref())?;
//! let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref())?;
//! assert_eq!(&plaintext, b"plaintext message");
@@ -138,44 +146,44 @@
mod cipher;
-pub use aead::{self, consts, AeadCore, AeadInPlace, Error, KeyInit, KeySizeUser};
+pub use aead::{self, AeadCore, AeadInOut, Error, KeyInit, KeySizeUser, consts};
-use self::cipher::Cipher;
+use crate::cipher::Cipher;
use ::cipher::{KeyIvInit, StreamCipher, StreamCipherSeek};
use aead::{
- consts::{U0, U12, U16, U24, U32},
- generic_array::{ArrayLength, GenericArray},
+ TagPosition,
+ array::{Array, ArraySize},
+ consts::{U12, U16, U24, U32},
+ inout::InOutBuf,
};
-use core::marker::PhantomData;
-use zeroize::{Zeroize, ZeroizeOnDrop};
-
use chacha20::{ChaCha20, XChaCha20};
+use core::{fmt, marker::PhantomData};
#[cfg(feature = "reduced-round")]
-use chacha20::{ChaCha12, ChaCha8, XChaCha12, XChaCha8};
+use chacha20::{ChaCha8, ChaCha12, XChaCha8, XChaCha12};
/// Key type (256-bits/32-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
+/// Implemented as an alias for [`Array`].
///
/// All [`ChaChaPoly1305`] variants (including `XChaCha20Poly1305`) use this
/// key type.
-pub type Key = GenericArray<u8, U32>;
+pub type Key = Array<u8, U32>;
/// Nonce type (96-bits/12-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
-pub type Nonce = GenericArray<u8, U12>;
+/// Implemented as an alias for [`Array`].
+pub type Nonce = Array<u8, U12>;
/// XNonce type (192-bits/24-bytes).
///
-/// Implemented as an alias for [`GenericArray`].
-pub type XNonce = GenericArray<u8, U24>;
+/// Implemented as an alias for [`Array`].
+pub type XNonce = Array<u8, U24>;
/// Poly1305 tag.
///
-/// Implemented as an alias for [`GenericArray`].
-pub type Tag = GenericArray<u8, U16>;
+/// Implemented as an alias for [`Array`].
+pub type Tag = Array<u8, U16>;
/// ChaCha20Poly1305 Authenticated Encryption with Additional Data (AEAD).
pub type ChaCha20Poly1305 = ChaChaPoly1305<ChaCha20, U12>;
@@ -206,7 +214,7 @@ pub type XChaCha12Poly1305 = ChaChaPoly1305<XChaCha12, U24>;
/// Generic ChaCha+Poly1305 Authenticated Encryption with Additional Data (AEAD) construction.
///
/// See the [toplevel documentation](index.html) for a usage example.
-pub struct ChaChaPoly1305<C, N: ArrayLength<u8> = U12> {
+pub struct ChaChaPoly1305<C, N: ArraySize = U12> {
/// Secret key.
key: Key,
@@ -219,14 +227,14 @@ pub struct ChaChaPoly1305<C, N: ArrayLength<u8> = U12> {
impl<C, N> KeySizeUser for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
type KeySize = U32;
}
impl<C, N> KeyInit for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
#[inline]
fn new(key: &Key) -> Self {
@@ -240,45 +248,41 @@ where
impl<C, N> AeadCore for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
type NonceSize = N;
type TagSize = U16;
- type CiphertextOverhead = U0;
+ const TAG_POSITION: TagPosition = TagPosition::Postfix;
}
-impl<C, N> AeadInPlace for ChaChaPoly1305<C, N>
+impl<C, N> AeadInOut for ChaChaPoly1305<C, N>
where
C: KeyIvInit<KeySize = U32, IvSize = N> + StreamCipher + StreamCipherSeek,
- N: ArrayLength<u8>,
+ N: ArraySize,
{
- fn encrypt_in_place_detached(
+ fn encrypt_inout_detached(
&self,
nonce: &aead::Nonce<Self>,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
) -> Result<Tag, Error> {
- Cipher::new(C::new(&self.key, nonce)).encrypt_in_place_detached(associated_data, buffer)
+ Cipher::new(C::new(&self.key, nonce)).encrypt_inout_detached(associated_data, buffer)
}
- fn decrypt_in_place_detached(
+ fn decrypt_inout_detached(
&self,
nonce: &aead::Nonce<Self>,
associated_data: &[u8],
- buffer: &mut [u8],
+ buffer: InOutBuf<'_, '_, u8>,
tag: &Tag,
) -> Result<(), Error> {
- Cipher::new(C::new(&self.key, nonce)).decrypt_in_place_detached(
- associated_data,
- buffer,
- tag,
- )
+ Cipher::new(C::new(&self.key, nonce)).decrypt_inout_detached(associated_data, buffer, tag)
}
}
impl<C, N> Clone for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
fn clone(&self) -> Self {
Self {
@@ -291,11 +295,25 @@ where
impl<C, N> Drop for ChaChaPoly1305<C, N>
where
- N: ArrayLength<u8>,
+ N: ArraySize,
{
fn drop(&mut self) {
- self.key.as_mut_slice().zeroize();
+ #[cfg(feature = "zeroize")]
+ {
+ use zeroize::Zeroize;
+ self.key.as_mut_slice().zeroize();
+ }
+ }
+}
+
+impl<C, N> fmt::Debug for ChaChaPoly1305<C, N>
+where
+ N: ArraySize,
+{
+ fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
+ f.debug_struct("ChaChaPoly1305").finish_non_exhaustive()
}
}
-impl<C, N: ArrayLength<u8>> ZeroizeOnDrop for ChaChaPoly1305<C, N> {}
+#[cfg(feature = "zeroize")]
+impl<C, N: ArraySize> zeroize::ZeroizeOnDrop for ChaChaPoly1305<C, N> {}
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305_fail.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_chacha20poly1305_pass.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305_fail.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/data/wycheproof_xchacha20poly1305_pass.blb
[binary or diff unavailable]
### external/vendor/chacha20poly1305/tests/lib.rs
@@ -6,29 +6,39 @@ use chacha20poly1305::ChaCha20Poly1305;
use chacha20poly1305::XChaCha20Poly1305;
// Test vectors from Wycheproof
-aead::new_test!(
- wycheproof_chacha20poly1305,
- "wycheproof_chacha20poly1305",
+aead::new_pass_test!(
+ wycheproof_chacha20poly1305_pass,
+ "wycheproof_chacha20poly1305_pass",
ChaCha20Poly1305
);
-aead::new_test!(
- wycheproof_xchacha20poly1305,
- "wycheproof_xchacha20poly1305",
+aead::new_fail_test!(
+ wycheproof_chacha20poly1305_fail,
+ "wycheproof_chacha20poly1305_fail",
+ ChaCha20Poly1305
+);
+aead::new_pass_test!(
+ wycheproof_xchacha20poly1305_pass,
+ "wycheproof_xchacha20poly1305_pass",
+ XChaCha20Poly1305
+);
+aead::new_fail_test!(
+ wycheproof_xchacha20poly1305_fail,
+ "wycheproof_xchacha20poly1305_fail",
XChaCha20Poly1305
);
macro_rules! impl_tests {
($cipher:ty, $key:expr, $nonce:expr, $aad:expr, $plaintext:expr, $ciphertext:expr, $tag:expr) => {
#[test]
fn encrypt() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let payload = Payload {
msg: $plaintext,
aad: $aad,
};
- let ciphertext = <$cipher>::new(key).encrypt(nonce, payload).unwrap();
+ let ciphertext = <$cipher>::new(&key).encrypt(&nonce, payload).unwrap();
let tag_begins = ciphertext.len() - 16;
assert_eq!($ciphertext, &ciphertext[..tag_begins]);
@@ -37,8 +47,8 @@ macro_rules! impl_tests {
#[test]
fn decrypt() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let mut ciphertext = Vec::from($ciphertext);
ciphertext.extend_from_slice($tag);
@@ -47,15 +57,15 @@ macro_rules! impl_tests {
aad: $aad,
};
- let plaintext = <$cipher>::new(key).decrypt(nonce, payload).unwrap();
+ let plaintext = <$cipher>::new(&key).decrypt(&nonce, payload).unwrap();
assert_eq!($plaintext, plaintext.as_slice());
}
#[test]
fn decrypt_modified() {
- let key = GenericArray::from_slice($key);
- let nonce = GenericArray::from_slice($nonce);
+ let key = Array(*$key);
+ let nonce = Array(*$nonce);
let mut ciphertext = Vec::from($ciphertext);
ciphertext.extend_from_slice($tag);
@@ -68,8 +78,8 @@ macro_rules! impl_tests {
aad: $aad,
};
- let cipher = <$cipher>::new(key);
- assert!(cipher.decrypt(nonce, payload).is_err());
+ let cipher = <$cipher>::new(&key);
+ assert!(cipher.decrypt(&nonce, payload).is_err());
}
};
}
@@ -96,9 +106,9 @@ const PLAINTEXT: &[u8] = b"Ladies and Gentlemen of the class of '99: \
/// <https://tools.ietf.org/html/rfc8439#section-2.8.2>
mod chacha20 {
use super::{AAD, KEY, PLAINTEXT};
- use chacha20poly1305::aead::generic_array::GenericArray;
- use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::ChaCha20Poly1305;
+ use chacha20poly1305::aead::array::Array;
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
const NONCE: &[u8; 12] = &[
0x07, 0x00, 0x00, 0x00, 0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47,
@@ -132,18 +142,18 @@ mod chacha20 {
#[test]
fn clone_impl() {
- let _ = ChaCha20Poly1305::new(GenericArray::from_slice(KEY)).clone();
+ let _ = ChaCha20Poly1305::new(KEY.into()).clone();
}
}
/// XChaCha20Poly1305 test vectors.
///
-/// From <https://tools.ietf.org/html/draft-arciszewski-xchacha-03#appendix-A.1>
+/// From <https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.1>
mod xchacha20 {
use super::{AAD, KEY, PLAINTEXT};
- use chacha20poly1305::aead::generic_array::GenericArray;
- use chacha20poly1305::aead::{Aead, KeyInit, Payload};
use chacha20poly1305::XChaCha20Poly1305;
+ use chacha20poly1305::aead::array::Array;
+ use chacha20poly1305::aead::{Aead, KeyInit, Payload};
const NONCE: &[u8; 24] = &[
0x40, 0x41, 0x42, 0x43, 0x44, 0x45, 0x46, 0x47, 0x48, 0x49, 0x4a, 0x4b, 0x4c, 0x4d, 0x4e,
### external/vendor/cipher/.cargo-checksum.json
@@ -1 +1 @@
-{"files":{".cargo_vcs_info.json":"cd35050864931045c5251108168d7a28930c9a54ec68a22999116f1ba034d139","CHANGELOG.md":"76b65408515ba9ab7b04742e8ac7269ea7ec18001c218ac7739a0513b6dc055f","Cargo.toml":"14da8d3fa5933ee2ccfe67432b260db0c50a732db4c1e13303abadd09af9e634","Cargo.toml.orig":"b319f1dd839f54a1761578fff6de9a58d0a71fb3cb31881b62ccd1571ff0c761","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"5c7bd92d1f096f12203dc1b601e3cb17484fa1b023e30b6b8edcc80e416237ec","README.md":"be7477bf37a82e5286846153ee87ac556550f0cea503ba42a4e8d9065f848e4d","src/block.rs":"d360a0dbedc71a1702d7ada005a4b1fc7da98aae24e099e7a41ffedcb2b6b5c0","src/dev.rs":"82e51f2d453c922ccd40f16e9e2353e7f0e4fe0db74b810a75410f375709f3d7","src/dev/block.rs":"f4a4e194907751768242e95ddb702827399d3b742848b381de62e5e859610129","src/dev/stream.rs":"8b0cfcaf037cf469ed4112e63afeb0782e3c6e09477e3065842aaec65d66041e","src/errors.rs":"d2c026ff03556c6d0a284cbd81d8ddadf5e2b6ca66d47c39ee9d4393fb96e089","src/lib.rs":"5582e304d673d1dd9ffc16e8fa3d240bb43538471341ca3c99d841ea1be0581e","src/stream.rs":"9ab2d14811de520578dc66af29db7200f3fd9b04fecfc916acf524b9da46c0a6","src/stream_core.rs":"0546f72cdf1a91e095235044047ca52eda73a7fd972a45bc287e17407094bb13","src/stream_wrapper.rs":"bcf4c76bacd006d7a0a65605f23fe43dc4d6c535a59a37103ee6e044e692f7d7"},"package":"773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad"}
\ No newline at end of file
+{"files":{".cargo_vcs_info.json":"a9861e72db50f80783a4e743a7129a5dd457d6fd1275ef28252f6c4af79554e6","CHANGELOG.md":"a8a99f9731115fa0eb271e2e687bfc580315648c5789b9559ad83e80e591db72","Cargo.lock":"08a46458af5efbcbb5a8e82b37a58d723a171b3847126275ed7bee1a330fb504","Cargo.toml":"8685a3b996d8d12e00d51d882425a409101d344f7efac1a48cf37a7509847c7f","Cargo.toml.orig":"75e90eee7bb7c8693451b1ce893104bcf616ed5cf8150e4574d39937768d3f79","LICENSE-APACHE":"a9040321c3712d8fd0b09cf52b17445de04a23a10165049ae187cd39e5c86be5","LICENSE-MIT":"950d712c518a02fcb7cff96950aee304a1cc5283361712c980ea21e8d6d669a5","README.md":"274b6472f637fdc8211b7396716016b9a91b5cbc59a7a3d59552355db785b11a","src/block.rs":"5aa181063d77cd7cb45b02fc400cf05aa8f29766c4b9f32226bd79e8386a12d8","src/block/backends.rs":"1647a4fde7e026e99205611fa179c88395fb67c312866c332c052184b914f943","src/block/ctx.rs":"c5e8e1599e0393b41ee601b9beedac2b1814d5d7800f046b991244c316ce7e93","src/dev.rs":"714bd891a70182125fbff1139c45d789d5943fcaae41604ad8ee41cf6b2139c6","src/dev/block_bench.rs":"d388849400aa1e0a65cbc528d2aac26d6f6dbe84b527609171989c2a9f30be6e","src/dev/block_cipher.rs":"ae78379371929a4dbaf14c25f362b9056bc22e81da47b065d558d1d2a4732d1a","src/dev/block_mode.rs":"de10a65369194d06de9b40e4541f69cad8cb59dc9ebfce1b440980b06abb83c7","src/dev/stream.rs":"2673eceb2d1aa44351eb39078b26e971d54a9754358a0d1cbc738c36900232f7","src/lib.rs":"2abd6484b6fbae1eb01f1f65ed26c2c20304fc91040d875d44b3f31bce555a57","src/stream.rs":"9558c02e4e05cc5f26a6d9e4ecae14e188432e0f4e0ef3dab909024a64ac7f09","src/stream/core_api.rs":"b79ca50449712d6aae8bc98447f80194217ff34572a225efd0d802cc475f4640","src/stream/errors.rs":"2e8ec1dc8d142daa70b61c849c80d0b3c61146bd0c511a03e0cc48d382a1bf6d","src/stream/wrapper.rs":"6fcf34c8511f80d46f0c48d5e52e3502641cd3ac8047fcb72336b0ac597e335b","src/tweak.rs":"d9e759821bcb790b4a4cc6f9a59dd809859915b8740a19eecce08027350ae1e3","src/tweak/ctx.rs":"34cd8d4118abd3cd57f56df74a9a6c1e9c0ebaf1926279acd7318c2c9b975ab9","src/tweak/zero.rs":"0162fdcaa6d4aefbe431f787f29155dbf10fe98549361a2348208800968d2ba2","tests/data/dummy_stream_cipher.blb":"b9573cccdb727cd7281940f69e934565c387e9074cbb4949358e20f0ea0e2c77","tests/stream.rs":"a98dabca3efc1cba888b2b0ed4a49b50286695b1dbbec69e4241053a263ab46e"},"package":"e8cf2a2c93cd704877c0858356ed03480ff301ee950b43f1cbe4573b088bfa6c"}
\ No newline at end of file
### external/vendor/cipher/.cargo_vcs_info.json
@@ -1,6 +1,6 @@
{
"git": {
- "sha1": "0af93f6076a76757c65cb2ef6f6abd9756440478"
+ "sha1": "f836f71fadb3b975b577a293d57851d044f0a44b"
},
"path_in_vcs": "cipher"
}
\ No newline at end of file
### external/vendor/cipher/CHANGELOG.md
@@ -5,6 +5,80 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+## 0.5.2 (2026-05-19)
+### Added
+- Re-export of `SetIvState` ([#2422])
+
+[#2422]: https://github.com/RustCrypto/traits/pull/2422
+
+## 0.5.1 (2026-02-25)
+### Changed
+- Block sizes no longer bounded by `crypto_common::BlockSizes` ([#2309])
+- `StreamCipherCoreWrapper` is now bounded by `block_buffer::BlockSizes`
+ instead of `crypto_common::BlockSizes` ([#2309])
+- Bump `block-buffer` dependency to v0.12 ([#2309])
+
+### Fixed
+- `Key:` option in the `stream_cipher_bench` macro ([#2290])
+
+[#2290]: https://github.com/RustCrypto/traits/pull/2290
+[#2309]: https://github.com/RustCrypto/traits/pull/2309
+
+## 0.5.0 (2026-02-04) [YANKED]
+Note: this version was yanked because v0.5.1 introduces breaking changes.
+Users should migrate to `cipher` v0.5.1 and `crypto-common` v0.2.1 using `cargo update`.
+
+### Added
+- Traits for tweakable block ciphers ([#1721])
+- Methods for writing keystream ([#1907])
+
+### Changed
+- Replaced `generic-array` with `hybrid-array` ([#1358])
+- Rename `BlockCipher*`/`BlockMode*` ([#1482])
+ - `BlockEncrypt` => `BlockCipherEncrypt`
+ - `BlockDecrypt` => `BlockCipherDecrypt`
+ - `BlockEncryptMut` => `BlockModeEncrypt`
+ - `BlockDecryptMut` => `BlockModeDecrypt`
+- Split `BlockBackend` traits into 4 specific traits: ([#1636])
+ - `BlockCipherEncBackend`
+ - `BlockCipherDecBackend`
+ - `BlockModeEncBackend`
+ - `BlockModeDecBackend`
+- Edition changed to 2024 and MSRV bumped to 1.85 ([#1759])
+- Use `block_buffer::ReadBuffer` in `StreamCipherCoreWrapper` ([#1959])
+- Re-export of `crypto-common` moved to `cipher::common` ([#2237], [#2260])
+- `crypto-common` dependency bumped to v0.2 ([#2276])
+- `blobby` requirement bumped to v0.4 ([#2147])
+- `inout` dependency bumped to v0.2.2 ([#2149])
+
+### Fixed
+- Bugs in `StreamCipherCoreWrapper` trait implementations ([#1421])
+- Seeking implementation in the stream cipher wrapper ([#2052])
+
+### Removed
+- `std` feature ([#1691])
+- `BlockCipherEncrypt::encrypt_padded*` and `BlockCipherDecrypt::decrypt_padded*` methods.
+ Users of the ECB mode should use the `ecb-mode` crate instead. ([#2245])
+- `AsyncStreamCipher` trait ([#2280])
+
+[#1358]: https://github.com/RustCrypto/traits/pull/1358
+[#1421]: https://github.com/RustCrypto/traits/pull/1421
+[#1482]: https://github.com/RustCrypto/traits/pull/1482
+[#1636]: https://github.com/RustCrypto/traits/pull/1636
+[#1691]: https://github.com/RustCrypto/traits/pull/1691
+[#1721]: https://github.com/RustCrypto/traits/pull/1721
+[#1759]: https://github.com/RustCrypto/traits/pull/1759
+[#1907]: https://github.com/RustCrypto/traits/pull/1907
+[#1959]: https://github.com/RustCrypto/traits/pull/1959
+[#2052]: https://github.com/RustCrypto/traits/pull/2052
+[#2147]: https://github.com/RustCrypto/traits/pull/2147
+[#2149]: https://github.com/RustCrypto/traits/pull/2149
+[#2237]: https://github.com/RustCrypto/traits/pull/2237
+[#2245]: https://github.com/RustCrypto/traits/pull/2245
+[#2260]: https://github.com/RustCrypto/traits/pull/2260
+[#2276]: https://github.com/RustCrypto/traits/pull/2276
+[#2280]: https://github.com/RustCrypto/traits/pull/2280
+
## 0.4.4 (2022-03-09)
### Changed
- Move `ParBlocks`/`ParBlocksSizeUser` to the `crypto-common` crate ([#1052])
### external/vendor/cipher/Cargo.lock
@@ -0,0 +1,465 @@
+# This file is automatically @generated by Cargo.
+# It is not intended for manual editing.
+version = 4
+
+[[package]]
+name = "anyhow"
+version = "1.0.102"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "7f202df86484c868dbad7eaa557ef785d5c66295e41b460ef922eca0723b842c"
+
+[[package]]
+name = "bitflags"
+version = "2.11.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "c4512299f36f043ab09a583e57bceb5a5aab7a73db1805848e8fef3c9e8c78b3"
+
+[[package]]
+name = "blobby"
+version = "0.4.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "89af0b093cc13baa4e51e64e65ec2422f7e73aea0e612e5ad3872986671622f1"
+
+[[package]]
+name = "block-buffer"
+version = "0.12.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "cdd35008169921d80bc60d3d0ab416eecb028c4cd653352907921d95084790be"
+dependencies = [
+ "hybrid-array",
+ "zeroize",
+]
+
+[[package]]
+name = "block-padding"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "710f1dd022ef4e93f8a438b4ba958de7f64308434fa6a87104481645cc30068b"
+dependencies = [
+ "hybrid-array",
+]
+
+[[package]]
+name = "cfg-if"
+version = "1.0.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
+
+[[package]]
+name = "cipher"
+version = "0.5.2"
+dependencies = [
+ "blobby",
+ "block-buffer",
+ "crypto-common",
+ "hex-literal",
+ "inout",
+ "zeroize",
+]
+
+[[package]]
+name = "crypto-common"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453"
+dependencies = [
+ "getrandom",
+ "hybrid-array",
+ "rand_core",
+]
+
+[[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 = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
+
+[[package]]
+name = "getrandom"
+version = "0.4.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0de51e6874e94e7bf76d726fc5d13ba782deca734ff60d5bb2fb2607c7406555"
+dependencies = [
+ "cfg-if",
+ "libc",
+ "r-efi",
+ "rand_core",
+ "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.17.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
+
+[[package]]
+name = "heck"
+version = "0.5.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
+
+[[package]]
+name = "hex-literal"
+version = "1.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e712f64ec3850b98572bffac52e2c6f282b29fe6c5fa6d42334b30be438d95c1"
+
+[[package]]
+name = "hybrid-array"
+version = "0.4.12"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "9155a582abd142abc056962c29e3ce5ff2ad5469f4246b537ed42c5deba857da"
+dependencies = [
+ "typenum",
+ "zeroize",
+]
+
+[[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.14.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
+dependencies = [
+ "equivalent",
+ "hashbrown 0.17.1",
+ "serde",
+ "serde_core",
+]
+
+[[package]]
+name = "inout"
+version = "0.2.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "4250ce6452e92010fdf7268ccc5d14faa80bb12fc741938534c58f16804e03c7"
+dependencies = [
+ "block-padding",
+ "hybrid-array",
+]
+
+[[package]]
+name = "itoa"
+version = "1.0.18"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
+
+[[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.186"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
+
+[[package]]
+name = "log"
+version = "0.4.29"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5e5032e24019045c762d3c0f28f5b6b8bbf38563a65908389bf7978758920897"
+
+[[package]]
+name = "memchr"
+version = "2.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8ca58f447f06ed17d5fc4043ce1b10dd205e060fb3ce5b979b8ed8e59ff3f79"
+
+[[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.106"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
+dependencies = [
+ "unicode-ident",
+]
+
+[[package]]
+name = "quote"
+version = "1.0.45"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "41f2619966050689382d2b44f664f4bc593e129785a36d6ee376ddf37259b924"
+dependencies = [
+ "proc-macro2",
+]
+
+[[package]]
+name = "r-efi"
+version = "6.0.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
+
+[[package]]
+name = "rand_core"
+version = "0.10.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69"
+
+[[package]]
+name = "semver"
+version = "1.0.28"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"
+
+[[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",
+]
+
+[[package]]
+name = "serde_json"
+version = "1.0.149"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "83fc039473c5595ace860d8c4fafa220ff474b3fc6bfdb4293327f1a37e94d86"
+dependencies = [
+ "itoa",
+ "memchr",
+ "serde",
+ "serde_core",
+ "zmij",
+]
+
+[[package]]
+name = "syn"
+version = "2.0.117"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e665b8803e7b1d2a727f4023456bbbbe74da67099c585258af0ad9c5013b9b99"
+dependencies = [
+ "proc-macro2",
+ "quote",
+ "unicode-ident",
+]
+
+[[package]]
+name = "typenum"
+version = "1.20.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "40ce102ab67701b8526c123c1bab5cbe42d7040ccfd0f64af1a385808d2f43de"
+
+[[package]]
+name = "unicode-ident"
+version = "1.0.24"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
+
+[[package]]
+name = "unicode-xid"
+version = "0.2.6"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853"
+
+[[package]]
+name = "wasip2"
+version = "1.0.1+wasi-0.2.4"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0562428422c63773dad2c345a1882263bbf4d65cf3f42e90921f787ef5ad58e7"
+dependencies = [
+ "wit-bindgen 0.46.0",
+]
+
+[[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 0.51.0",
+]
+
+[[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 = "wit-bindgen"
+version = "0.46.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "f17a85883d4e6d00e8a97c586de764dabcc06133f7f1d55dce5cdc070ad7fe59"
+
+[[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-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 = "zeroize"
+version = "1.8.2"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b97154e67e32c85465826e8bcc1c59429aaaf107c1e4a9e53c8d8ccd5eff88d0"
+
+[[package]]
+name = "zmij"
+version = "1.0.21"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
### external/vendor/cipher/Cargo.toml
@@ -10,11 +10,17 @@
# See Cargo.toml.orig for the original contents.
[package]
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
name = "cipher"
-version = "0.4.4"
+version = "0.5.2"
authors = ["RustCrypto Developers"]
+build = false
+autolib = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
description = "Traits for describing block ciphers and stream ciphers"
documentation = "https://docs.rs/cipher"
readme = "README.md"
@@ -33,33 +39,86 @@ repository = "https://github.com/RustCrypto/traits"
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = [
- "--cfg",
- "docsrs",
+
+[features]
+alloc = []
+block-padding = ["inout/block-padding"]
+dev = ["blobby"]
+getrandom = ["common/getrandom"]
+rand_core = ["common/rand_core"]
+stream-wrapper = ["block-buffer"]
+zeroize = [
+ "dep:zeroize",
+ "common/zeroize",
+ "block-buffer?/zeroize",
]
+[lib]
+name = "cipher"
+path = "src/lib.rs"
+
+[[test]]
+name = "stream"
+path = "tests/stream.rs"
+
[dependencies.blobby]
-version = "0.3"
+version = "0.4"
optional = true
-[dependencies.crypto-common]
-version = "0.1.6"
+[dependencies.block-buffer]
+version = "0.12"
+optional = true
+
+[dependencies.common]
+version = "0.2.2"
+package = "crypto-common"
[dependencies.inout]
-version = "0.1"
+version = "0.2.2"
[dependencies.zeroize]
-version = "1.5"
+version = "1.8"
optional = true
default-features = false
-[features]
-alloc = []
-block-padding = ["inout/block-padding"]
-dev = ["blobby"]
-rand_core = ["crypto-common/rand_core"]
-std = [
- "alloc",
- "crypto-common/std",
- "inout/std",
-]
+[dev-dependencies.hex-literal]
+version = "1"
+
+[lints.clippy]
+borrow_as_ptr = "warn"
+cast_lossless = "warn"
+cast_possible_truncation = "warn"
+cast_possible_wrap = "warn"
+cast_precision_loss = "warn"
+cast_sign_loss = "warn"
+checked_conversions = "warn"
+from_iter_instead_of_collect = "warn"
+implicit_saturating_sub = "warn"
+manual_assert = "warn"
+map_unwrap_or = "warn"
+missing_errors_doc = "warn"
+missing_panics_doc = "warn"
+mod_module_files = "warn"
+must_use_candidate = "warn"
+needless_range_loop = "allow"
+ptr_as_ptr = "warn"
+redundant_closure_for_method_calls = "warn"
+ref_as_ptr = "warn"
+return_self_not_must_use = "warn"
+semicolon_if_nothing_returned = "warn"
+std_instead_of_alloc = "warn"
+std_instead_of_core = "warn"
+trivially_copy_pass_by_ref = "warn"
+undocumented_unsafe_blocks = "warn"
+unnecessary_safety_comment = "warn"
+unwrap_in_result = "warn"
+unwrap_used = "warn"
+
+[lints.rust]
+missing_copy_implementations = "warn"
+missing_debug_implementations = "warn"
+missing_docs = "warn"
+trivial_casts = "warn"
+trivial_numeric_casts = "warn"
+unused_lifetimes = "warn"
+unused_qualifications = "warn"
### external/vendor/cipher/Cargo.toml.orig
@@ -1,32 +1,40 @@
[package]
name = "cipher"
-description = "Traits for describing block ciphers and stream ciphers"
-version = "0.4.4"
+version = "0.5.2"
authors = ["RustCrypto Developers"]
-license = "MIT OR Apache-2.0"
-readme = "README.md"
-edition = "2021"
-rust-version = "1.56"
+edition = "2024"
+rust-version = "1.85"
documentation = "https://docs.rs/cipher"
+readme = "README.md"
repository = "https://github.com/RustCrypto/traits"
+license = "MIT OR Apache-2.0"
keywords = ["crypto", "block-cipher", "stream-cipher", "trait"]
categories = ["cryptography", "no-std"]
+description = "Traits for describing block ciphers and stream ciphers"
[dependencies]
-crypto-common = "0.1.6"
-inout = "0.1"
+common = { version = "0.2.2", package = "crypto-common" }
+inout = "0.2.2"
# optional dependencies
-blobby = { version = "0.3", optional = true }
-zeroize = { version = "1.5", optional = true, default-features = false }
+blobby = { version = "0.4", optional = true }
+block-buffer = { version = "0.12", optional = true }
+zeroize = { version = "1.8", optional = true, default-features = false }
+
+[dev-dependencies]
+hex-literal = "1"
[features]
alloc = []
-std = ["alloc", "crypto-common/std", "inout/std"]
block-padding = ["inout/block-padding"]
-rand_core = ["crypto-common/rand_core"] # Enable random key and IV generation methods
+stream-wrapper = ["block-buffer"]
+getrandom = ["common/getrandom"]
+rand_core = ["common/rand_core"]
dev = ["blobby"]
+zeroize = ["dep:zeroize", "common/zeroize", "block-buffer?/zeroize"]
+
+[lints]
+workspace = true
[package.metadata.docs.rs]
all-features = true
-rustdoc-args = ["--cfg", "docsrs"]
### external/vendor/cipher/LICENSE-MIT
@@ -1,4 +1,4 @@
-Copyright (c) 2016-2020 RustCrypto Developers
+Copyright (c) 2016-2025 RustCrypto Developers
Permission is hereby granted, free of charge, to any
person obtaining a copy of this software and associated
### external/vendor/cipher/README.md
@@ -7,19 +7,10 @@
[![Project Chat][chat-image]][chat-link]
[![Build Status][build-image]][build-link]
-Traits which define the functionality of [block ciphers] and [stream ciphers].
+Traits which define the functionality of [block ciphers], [block modes] and [stream ciphers].
-See [RustCrypto/block-ciphers] and [RustCrypto/stream-ciphers] for algorithm
-implementations which use these traits.
-
-[Documentation][docs-link]
-
-## Minimum Supported Rust Version
-
-Rust **1.56** or higher.
-
-Minimum supported Rust version can be changed in the future, but it will be
-done with a minor version bump.
+See [RustCrypto/block-ciphers] and [RustCrypto/stream-ciphers] for algorithm implementations which
+use these traits.
## SemVer Policy
@@ -48,15 +39,16 @@ dual licensed as above, without any additional terms or conditions.
[docs-image]: https://docs.rs/cipher/badge.svg
[docs-link]: https://docs.rs/cipher/
[license-image]: https://img.shields.io/badge/license-Apache2.0/MIT-blue.svg
-[rustc-image]: https://img.shields.io/badge/rustc-1.41+-blue.svg
+[rustc-image]: https://img.shields.io/badge/rustc-1.85+-blue.svg
[chat-image]: https://img.shields.io/badge/zulip-join_chat-blue.svg
[chat-link]: https://rustcrypto.zulipchat.com/#narrow/stream/260050-traits
-[build-image]: https://github.com/RustCrypto/traits/workflows/cipher/badge.svg?branch=master&event=push
-[build-link]: https://github.com/RustCrypto/traits/actions?query=workflow:cipher
+[build-image]: https://github.com/RustCrypto/traits/actions/workflows/cipher.yml/badge.svg?branch=master
+[build-link]: https://github.com/RustCrypto/traits/actions/workflows/cipher.yml?query=branch:master
[//]: # (general links)
[block ciphers]: https://en.wikipedia.org/wiki/Block_cipher
+[block modes]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
[stream ciphers]: https://en.wikipedia.org/wiki/Stream_cipher
[RustCrypto/block-ciphers]: https://github.com/RustCrypto/block-ciphers
[RustCrypto/stream-ciphers]: https://github.com/RustCrypto/stream-ciphers
### external/vendor/cipher/src/block.rs
@@ -10,76 +10,30 @@
//! [2]: https://en.wikipedia.org/wiki/Block_cipher_mode_of_operation
//! [3]: https://en.wikipedia.org/wiki/Symmetric-key_algorithm
-use crate::{ParBlocks, ParBlocksSizeUser};
#[cfg(all(feature = "block-padding", feature = "alloc"))]
use alloc::{vec, vec::Vec};
+use common::{Block, BlockSizeUser};
+use inout::{InOut, InOutBuf, NotEqualError};
#[cfg(feature = "block-padding")]
use inout::{
- block_padding::{Padding, UnpadError},
InOutBufReserved, PadError,
+ block_padding::{self, Padding},
};
-use inout::{InOut, InOutBuf, NotEqualError};
-
-pub use crypto_common::{generic_array::ArrayLength, typenum::Unsigned, Block, BlockSizeUser};
-
-/// Marker trait for block ciphers.
-pub trait BlockCipher: BlockSizeUser {}
-
-/// Trait implemented by block cipher encryption and decryption backends.
-pub trait BlockBackend: ParBlocksSizeUser {
- /// Process single inout block.
- fn proc_block(&mut self, block: InOut<'_, '_, Block<Self>>);
-
- /// Process inout blocks in parallel.
- #[inline(always)]
- fn proc_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
- for i in 0..Self::ParBlocksSize::USIZE {
- self.proc_block(blocks.get(i));
- }
- }
- /// Process buffer of inout blocks. Length of the buffer MUST be smaller
- /// than `Self::ParBlocksSize`.
- #[inline(always)]
- fn proc_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- assert!(blocks.len() < Self::ParBlocksSize::USIZE);
- for block in blocks {
- self.proc_block(block);
- }
- }
+mod backends;
+mod ctx;
- /// Process single block in-place.
- #[inline(always)]
- fn proc_block_inplace(&mut self, block: &mut Block<Self>) {
- self.proc_block(block.into());
- }
+use ctx::{BlockCtx, BlocksCtx};
- /// Process blocks in parallel in-place.
- #[inline(always)]
- fn proc_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
- self.proc_par_blocks(blocks.into());
- }
-
- /// Process buffer of blocks in-place. Length of the buffer MUST be smaller
- /// than `Self::ParBlocksSize`.
- #[inline(always)]
- fn proc_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
- self.proc_tail_blocks(blocks.into());
- }
-}
-
-/// Trait for [`BlockBackend`] users.
-///
-/// This trait is used to define rank-2 closures.
-pub trait BlockClosure: BlockSizeUser {
- /// Execute closure with the provided block cipher backend.
- fn call<B: BlockBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
-}
+pub use backends::{
+ BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherEncBackend, BlockCipherEncClosure,
+ BlockModeDecBackend, BlockModeDecClosure, BlockModeEncBackend, BlockModeEncClosure,
+};
/// Encrypt-only functionality for block ciphers.
-pub trait BlockEncrypt: BlockSizeUser + Sized {
+pub trait BlockCipherEncrypt: BlockSizeUser + Sized {
/// Encrypt data using backend provided to the rank-2 closure.
- fn encrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>);
/// Encrypt single `inout` block.
#[inline]
@@ -116,6 +70,7 @@ pub trait BlockEncrypt: BlockSizeUser + Sized {
/// Encrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
@@ -127,74 +82,12 @@ pub trait BlockEncrypt: BlockSizeUser + Sized {
InOutBuf::new(in_blocks, out_blocks)
.map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
}
-
- /// Pad input and encrypt. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded_inout<'inp, 'out, P: Padding<Self::BlockSize>>(
- &self,
- data: InOutBufReserved<'inp, 'out, u8>,
- ) -> Result<&'out [u8], PadError> {
- let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
- self.encrypt_blocks_inout(buf.get_blocks());
- if let Some(block) = buf.get_tail_block() {
- self.encrypt_block_inout(block);
- }
- Ok(buf.into_out())
- }
-
- /// Pad input and encrypt in-place. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded<'a, P: Padding<Self::BlockSize>>(
- &self,
- buf: &'a mut [u8],
- msg_len: usize,
- ) -> Result<&'a [u8], PadError> {
- let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
- self.encrypt_padded_inout::<P>(buf)
- }
-
- /// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
- ///
- /// Returns [`PadError`] if length of output buffer is not sufficient.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn encrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
- &self,
- msg: &[u8],
- out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], PadError> {
- let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
- self.encrypt_padded_inout::<P>(buf)
- }
-
- /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
- #[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
- #[inline]
- fn encrypt_padded_vec<P: Padding<Self::BlockSize>>(&self, msg: &[u8]) -> Vec<u8> {
- let mut out = allocate_out_vec::<Self>(msg.len());
- let len = self
- .encrypt_padded_b2b::<P>(msg, &mut out)
- .expect("enough space for encrypting is allocated")
- .len();
- out.truncate(len);
- out
- }
}
/// Decrypt-only functionality for block ciphers.
-pub trait BlockDecrypt: BlockSizeUser {
+pub trait BlockCipherDecrypt: BlockSizeUser {
/// Decrypt data using backend provided to the rank-2 closure.
- fn decrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>);
/// Decrypt single `inout` block.
#[inline]
@@ -231,6 +124,7 @@ pub trait BlockDecrypt: BlockSizeUser {
/// Decrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
@@ -242,78 +136,17 @@ pub trait BlockDecrypt: BlockSizeUser {
InOutBuf::new(in_blocks, out_blocks)
.map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
}
+}
- /// Decrypt input and unpad it. Returns resulting ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded_inout<'inp, 'out, P: Padding<Self::BlockSize>>(
- &self,
- data: InOutBuf<'inp, 'out, u8>,
- ) -> Result<&'out [u8], UnpadError> {
- let (mut blocks, tail) = data.into_chunks();
- if !tail.is_empty() {
- return Err(UnpadError);
- }
- self.decrypt_blocks_inout(blocks.reborrow());
- P::unpad_blocks(blocks.into_out())
- }
-
- /// Decrypt input and unpad it in-place. Returns resulting ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded<'a, P: Padding<Self::BlockSize>>(
- &self,
- buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
- self.decrypt_padded_inout::<P>(buf.into())
- }
-
- /// Decrypt input and unpad it buffer-to-buffer. Returns resulting
- /// ciphertext slice.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
- #[inline]
- fn decrypt_padded_b2b<'a, P: Padding<Self::BlockSize>>(
- &self,
- in_buf: &[u8],
- out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
- if out_buf.len() < in_buf.len() {
- return Err(UnpadError);
- }
- let n = in_buf.len();
- // note: `new` always returns `Ok` here
- let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
- self.decrypt_padded_inout::<P>(buf)
+impl<Alg: BlockCipherEncrypt> BlockCipherEncrypt for &Alg {
+ fn encrypt_with_backend(&self, f: impl BlockCipherEncClosure<BlockSize = Self::BlockSize>) {
+ Alg::encrypt_with_backend(self, f);
}
+}
- /// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
- /// ciphertext Vec.
- ///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
- /// not multiple of `Self::BlockSize`.
- #[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
- #[inline]
- fn decrypt_padded_vec<P: Padding<Self::BlockSize>>(
- &self,
- buf: &[u8],
- ) -> Result<Vec<u8>, UnpadError> {
- let mut out = vec![0; buf.len()];
- let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
- out.truncate(len);
- Ok(out)
+impl<Alg: BlockCipherDecrypt> BlockCipherDecrypt for &Alg {
+ fn decrypt_with_backend(&self, f: impl BlockCipherDecClosure<BlockSize = Self::BlockSize>) {
+ Alg::decrypt_with_backend(self, f);
}
}
@@ -322,117 +155,138 @@ pub trait BlockDecrypt: BlockSizeUser {
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
-pub trait BlockEncryptMut: BlockSizeUser + Sized {
+pub trait BlockModeEncrypt: BlockSizeUser + Sized {
/// Encrypt data using backend provided to the rank-2 closure.
- fn encrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn encrypt_with_backend(&mut self, f: impl BlockModeEncClosure<BlockSize = Self::BlockSize>);
/// Encrypt single `inout` block.
#[inline]
- fn encrypt_block_inout_mut(&mut self, block: InOut<'_, '_, Block<Self>>) {
- self.encrypt_with_backend_mut(BlockCtx { block });
+ fn encrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt `inout` blocks.
#[inline]
- fn encrypt_blocks_inout_mut(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- self.encrypt_with_backend_mut(BlocksCtx { blocks });
+ fn encrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ self.encrypt_with_backend(BlocksCtx { blocks });
}
/// Encrypt single block in-place.
#[inline]
- fn encrypt_block_mut(&mut self, block: &mut Block<Self>) {
+ fn encrypt_block(&mut self, block: &mut Block<Self>) {
let block = block.into();
- self.encrypt_with_backend_mut(BlockCtx { block });
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt `in_block` and write result to `out_block`.
#[inline]
- fn encrypt_block_b2b_mut(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
+ fn encrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
let block = (in_block, out_block).into();
- self.encrypt_with_backend_mut(BlockCtx { block });
+ self.encrypt_with_backend(BlockCtx { block });
}
/// Encrypt blocks in-place.
#[inline]
- fn encrypt_blocks_mut(&mut self, blocks: &mut [Block<Self>]) {
+ fn encrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
let blocks = blocks.into();
- self.encrypt_with_backend_mut(BlocksCtx { blocks });
+ self.encrypt_with_backend(BlocksCtx { blocks });
}
/// Encrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
- fn encrypt_blocks_b2b_mut(
+ fn encrypt_blocks_b2b(
&mut self,
in_blocks: &[Block<Self>],
out_blocks: &mut [Block<Self>],
) -> Result<(), NotEqualError> {
InOutBuf::new(in_blocks, out_blocks)
- .map(|blocks| self.encrypt_with_backend_mut(BlocksCtx { blocks }))
+ .map(|blocks| self.encrypt_with_backend(BlocksCtx { blocks }))
}
/// Pad input and encrypt. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_inout_mut<'inp, 'out, P: Padding<Self::BlockSize>>(
+ fn encrypt_padded_inout<'out, P: Padding>(
mut self,
- data: InOutBufReserved<'inp, 'out, u8>,
+ data: InOutBufReserved<'_, 'out, u8>,
) -> Result<&'out [u8], PadError> {
let mut buf = data.into_padded_blocks::<P, Self::BlockSize>()?;
- self.encrypt_blocks_inout_mut(buf.get_blocks());
+ self.encrypt_blocks_inout(buf.get_blocks());
if let Some(block) = buf.get_tail_block() {
- self.encrypt_block_inout_mut(block);
+ self.encrypt_block_inout(block);
}
Ok(buf.into_out())
}
/// Pad input and encrypt in-place. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &mut [u8],
- msg_len: usize,
- ) -> Result<&[u8], PadError> {
+ fn encrypt_padded<P: Padding>(self, buf: &mut [u8], msg_len: usize) -> Result<&[u8], PadError> {
let buf = InOutBufReserved::from_mut_slice(buf, msg_len).map_err(|_| PadError)?;
- self.encrypt_padded_inout_mut::<P>(buf)
+ self.encrypt_padded_inout::<P>(buf)
}
/// Pad input and encrypt buffer-to-buffer. Returns resulting ciphertext slice.
///
+ /// # Errors
/// Returns [`PadError`] if length of output buffer is not sufficient.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn encrypt_padded_b2b_mut<'a, P: Padding<Self::BlockSize>>(
+ fn encrypt_padded_b2b<'a, P: Padding>(
self,
msg: &[u8],
out_buf: &'a mut [u8],
) -> Result<&'a [u8], PadError> {
let buf = InOutBufReserved::from_slices(msg, out_buf).map_err(|_| PadError)?;
- self.encrypt_padded_inout_mut::<P>(buf)
+ self.encrypt_padded_inout::<P>(buf)
}
- /// Pad input and encrypt into a newly allocated Vec. Returns resulting ciphertext Vec.
+ /// Pad `msg` with padding algorithm `P`, encrypt it into a newly allocated `Vec`,
+ /// and return the resulting ciphertext vector.
+ ///
+ /// # Panics
+ /// If `NoPadding` is used with a message size that is not a multiple of the cipher block size.
#[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
#[inline]
- fn encrypt_padded_vec_mut<P: Padding<Self::BlockSize>>(self, msg: &[u8]) -> Vec<u8> {
- let mut out = allocate_out_vec::<Self>(msg.len());
- let len = self
- .encrypt_padded_b2b_mut::<P>(msg, &mut out)
- .expect("enough space for encrypting is allocated")
+ fn encrypt_padded_vec<P: Padding>(self, msg: &[u8]) -> Vec<u8> {
+ use block_padding::{NoPadding, ZeroPadding};
+ use common::typenum::Unsigned;
+ use core::any::TypeId;
+
+ let bs = Self::BlockSize::USIZE;
+ let msg_len = msg.len();
+
+ let pad_type_id = TypeId::of::<P>();
+ let buf_blocks_len = if pad_type_id == TypeId::of::<NoPadding>() {
+ assert!(
+ msg_len % bs == 0,
+ "NoPadding is used with a {msg_len}‑byte message,
+ which is not a multiple of the {bs}‑byte cipher block size"
+ );
+ msg_len / bs
+ } else if pad_type_id == TypeId::of::<ZeroPadding>() {
+ msg_len.div_ceil(bs)
+ } else {
+ 1 + msg_len / bs
+ };
+
+ let mut buf = vec![0; bs * buf_blocks_len];
+ let res_len = self
+ .encrypt_padded_b2b::<P>(msg, &mut buf)
+ .expect("`buf` has enough space for encryption")
.len();
- out.truncate(len);
- out
+ buf.truncate(res_len);
+ buf
}
}
@@ -441,281 +295,122 @@ pub trait BlockEncryptMut: BlockSizeUser + Sized {
/// The main use case for this trait is blocks modes, but it also can be used
/// for hardware cryptographic engines which require `&mut self` access to an
/// underlying hardware peripheral.
-pub trait BlockDecryptMut: BlockSizeUser + Sized {
+pub trait BlockModeDecrypt: BlockSizeUser + Sized {
/// Decrypt data using backend provided to the rank-2 closure.
- fn decrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>);
+ fn decrypt_with_backend(&mut self, f: impl BlockModeDecClosure<BlockSize = Self::BlockSize>);
/// Decrypt single `inout` block.
#[inline]
- fn decrypt_block_inout_mut(&mut self, block: InOut<'_, '_, Block<Self>>) {
- self.decrypt_with_backend_mut(BlockCtx { block });
+ fn decrypt_block_inout(&mut self, block: InOut<'_, '_, Block<Self>>) {
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt `inout` blocks.
#[inline]
- fn decrypt_blocks_inout_mut(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
- self.decrypt_with_backend_mut(BlocksCtx { blocks });
+ fn decrypt_blocks_inout(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ self.decrypt_with_backend(BlocksCtx { blocks });
}
/// Decrypt single block in-place.
#[inline]
- fn decrypt_block_mut(&mut self, block: &mut Block<Self>) {
+ fn decrypt_block(&mut self, block: &mut Block<Self>) {
let block = block.into();
- self.decrypt_with_backend_mut(BlockCtx { block });
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt `in_block` and write result to `out_block`.
#[inline]
- fn decrypt_block_b2b_mut(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
+ fn decrypt_block_b2b(&mut self, in_block: &Block<Self>, out_block: &mut Block<Self>) {
let block = (in_block, out_block).into();
- self.decrypt_with_backend_mut(BlockCtx { block });
+ self.decrypt_with_backend(BlockCtx { block });
}
/// Decrypt blocks in-place.
#[inline]
- fn decrypt_blocks_mut(&mut self, blocks: &mut [Block<Self>]) {
+ fn decrypt_blocks(&mut self, blocks: &mut [Block<Self>]) {
let blocks = blocks.into();
- self.decrypt_with_backend_mut(BlocksCtx { blocks });
+ self.decrypt_with_backend(BlocksCtx { blocks });
}
/// Decrypt blocks buffer-to-buffer.
///
+ /// # Errors
/// Returns [`NotEqualError`] if provided `in_blocks` and `out_blocks`
/// have different lengths.
#[inline]
- fn decrypt_blocks_b2b_mut(
+ fn decrypt_blocks_b2b(
&mut self,
in_blocks: &[Block<Self>],
out_blocks: &mut [Block<Self>],
) -> Result<(), NotEqualError> {
InOutBuf::new(in_blocks, out_blocks)
- .map(|blocks| self.decrypt_with_backend_mut(BlocksCtx { blocks }))
+ .map(|blocks| self.decrypt_with_backend(BlocksCtx { blocks }))
}
- /// Decrypt input and unpad it. Returns resulting ciphertext slice.
+ /// Decrypt input and unpad it. Returns resulting plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_inout_mut<'inp, 'out, P: Padding<Self::BlockSize>>(
+ fn decrypt_padded_inout<'out, P: Padding>(
mut self,
- data: InOutBuf<'inp, 'out, u8>,
- ) -> Result<&'out [u8], UnpadError> {
+ data: InOutBuf<'_, 'out, u8>,
+ ) -> Result<&'out [u8], block_padding::Error> {
let (mut blocks, tail) = data.into_chunks();
if !tail.is_empty() {
- return Err(UnpadError);
+ return Err(block_padding::Error);
}
- self.decrypt_blocks_inout_mut(blocks.reborrow());
- P::unpad_blocks(blocks.into_out())
+ self.decrypt_blocks_inout(blocks.reborrow());
+ P::unpad_blocks::<Self::BlockSize>(blocks.into_out())
}
- /// Decrypt input and unpad it in-place. Returns resulting ciphertext slice.
+ /// Decrypt input and unpad it in-place. Returns resulting plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &mut [u8],
- ) -> Result<&[u8], UnpadError> {
- self.decrypt_padded_inout_mut::<P>(buf.into())
+ fn decrypt_padded<P: Padding>(self, buf: &mut [u8]) -> Result<&[u8], block_padding::Error> {
+ self.decrypt_padded_inout::<P>(buf.into())
}
/// Decrypt input and unpad it buffer-to-buffer. Returns resulting
- /// ciphertext slice.
+ /// plaintext slice.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(feature = "block-padding")]
- #[cfg_attr(docsrs, doc(cfg(feature = "block-padding")))]
#[inline]
- fn decrypt_padded_b2b_mut<'a, P: Padding<Self::BlockSize>>(
+ fn decrypt_padded_b2b<'a, P: Padding>(
self,
in_buf: &[u8],
out_buf: &'a mut [u8],
- ) -> Result<&'a [u8], UnpadError> {
+ ) -> Result<&'a [u8], block_padding::Error> {
if out_buf.len() < in_buf.len() {
- return Err(UnpadError);
+ return Err(block_padding::Error);
}
let n = in_buf.len();
// note: `new` always returns `Ok` here
- let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| UnpadError)?;
- self.decrypt_padded_inout_mut::<P>(buf)
+ let buf = InOutBuf::new(in_buf, &mut out_buf[..n]).map_err(|_| block_padding::Error)?;
+ self.decrypt_padded_inout::<P>(buf)
}
/// Decrypt input and unpad it in a newly allocated Vec. Returns resulting
- /// ciphertext Vec.
+ /// plaintext `Vec`.
///
- /// Returns [`UnpadError`] if padding is malformed or if input length is
+ /// # Errors
+ /// Returns [`block_padding::Error`] if padding is malformed or if input length is
/// not multiple of `Self::BlockSize`.
#[cfg(all(feature = "block-padding", feature = "alloc"))]
- #[cfg_attr(docsrs, doc(cfg(all(feature = "block-padding", feature = "alloc"))))]
#[inline]
- fn decrypt_padded_vec_mut<P: Padding<Self::BlockSize>>(
- self,
- buf: &[u8],
- ) -> Result<Vec<u8>, UnpadError> {
+ fn decrypt_padded_vec<P: Padding>(self, buf: &[u8]) -> Result<Vec<u8>, block_padding::Error> {
let mut out = vec![0; buf.len()];
- let len = self.decrypt_padded_b2b_mut::<P>(buf, &mut out)?.len();
+ let len = self.decrypt_padded_b2b::<P>(buf, &mut out)?.len();
out.truncate(len);
Ok(out)
}
}
-
-impl<Alg: BlockEncrypt> BlockEncryptMut for Alg {
- fn encrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- self.encrypt_with_backend(f);
- }
-}
-
-impl<Alg: BlockDecrypt> BlockDecryptMut for Alg {
- fn decrypt_with_backend_mut(&mut self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- self.decrypt_with_backend(f);
- }
-}
-
-impl<Alg: BlockCipher> BlockCipher for &Alg {}
-
-impl<Alg: BlockEncrypt> BlockEncrypt for &Alg {
- fn encrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- Alg::encrypt_with_backend(self, f);
- }
-}
-
-impl<Alg: BlockDecrypt> BlockDecrypt for &Alg {
- fn decrypt_with_backend(&self, f: impl BlockClosure<BlockSize = Self::BlockSize>) {
- Alg::decrypt_with_backend(self, f);
- }
-}
-
-/// Closure used in methods which operate over separate blocks.
-struct BlockCtx<'inp, 'out, BS: ArrayLength<u8>> {
- block: InOut<'inp, 'out, Block<Self>>,
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for BlockCtx<'inp, 'out, BS> {
- type BlockSize = BS;
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockClosure for BlockCtx<'inp, 'out, BS> {
- #[inline(always)]
- fn call<B: BlockBackend<BlockSize = BS>>(self, backend: &mut B) {
- backend.proc_block(self.block);
- }
-}
-
-/// Closure used in methods which operate over slice of blocks.
-struct BlocksCtx<'inp, 'out, BS: ArrayLength<u8>> {
- blocks: InOutBuf<'inp, 'out, Block<Self>>,
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockSizeUser for BlocksCtx<'inp, 'out, BS> {
- type BlockSize = BS;
-}
-
-impl<'inp, 'out, BS: ArrayLength<u8>> BlockClosure for BlocksCtx<'inp, 'out, BS> {
- #[inline(always)]
- fn call<B: BlockBackend<BlockSize = BS>>(self, backend: &mut B) {
- if B::ParBlocksSize::USIZE > 1 {
- let (chunks, tail) = self.blocks.into_chunks();
- for chunk in chunks {
- backend.proc_par_blocks(chunk);
- }
- backend.proc_tail_blocks(tail);
- } else {
- for block in self.blocks {
- backend.proc_block(block);
- }
- }
- }
-}
-
-#[cfg(all(feature = "block-padding", feature = "alloc"))]
-fn allocate_out_vec<BS: BlockSizeUser>(len: usize) -> Vec<u8> {
- let bs = BS::BlockSize::USIZE;
- vec![0; bs * (len / bs + 1)]
-}
-
-/// Implement simple block backend
-#[macro_export]
-macro_rules! impl_simple_block_encdec {
- (
- <$($N:ident$(:$b0:ident$(+$b:ident)*)?),*>
- $cipher:ident, $block_size:ty, $state:ident, $block:ident,
- encrypt: $enc_block:block
- decrypt: $dec_block:block
- ) => {
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockSizeUser for $cipher<$($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockEncrypt for $cipher<$($N),*> {
- fn encrypt_with_backend(&self, f: impl $crate::BlockClosure<BlockSize = $block_size>) {
- struct EncBack<'a, $($N$(:$b0$(+$b)*)?),* >(&'a $cipher<$($N),*>);
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockSizeUser for EncBack<'a, $($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::ParBlocksSizeUser for EncBack<'a, $($N),*> {
- type ParBlocksSize = $crate::consts::U1;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockBackend for EncBack<'a, $($N),*> {
- #[inline(always)]
- fn proc_block(
- &mut self,
- mut $block: $crate::inout::InOut<'_, '_, $crate::Block<Self>>
- ) {
- let $state: &$cipher<$($N),*> = self.0;
- $enc_block
- }
- }
-
- f.call(&mut EncBack(self))
- }
- }
-
- impl<$($N$(:$b0$(+$b)*)?),*> $crate::BlockDecrypt for $cipher<$($N),*> {
- fn decrypt_with_backend(&self, f: impl $crate::BlockClosure<BlockSize = $block_size>) {
- struct DecBack<'a, $($N$(:$b0$(+$b)*)?),* >(&'a $cipher<$($N),*>);
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockSizeUser for DecBack<'a, $($N),*> {
- type BlockSize = $block_size;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::ParBlocksSizeUser for DecBack<'a, $($N),*> {
- type ParBlocksSize = $crate::consts::U1;
- }
-
- impl<'a, $($N$(:$b0$(+$b)*)?),* > $crate::BlockBackend for DecBack<'a, $($N),*> {
- #[inline(always)]
- fn proc_block(
- &mut self,
- mut $block: $crate::inout::InOut<'_, '_, $crate::Block<Self>>
- ) {
- let $state: &$cipher<$($N),*> = self.0;
- $dec_block
- }
- }
-
- f.call(&mut DecBack(self))
- }
- }
- };
- (
- $cipher:ident, $block_size:ty, $state:ident, $block:ident,
- encrypt: $enc_block:block
- decrypt: $dec_block:block
- ) => {
- $crate::impl_simple_block_encdec!(
- <> $cipher, $block_size, $state, $block,
- encrypt: $enc_block
- decrypt: $dec_block
- );
- };
-}
### external/vendor/cipher/src/block/backends.rs
@@ -0,0 +1,206 @@
+use common::{Block, BlockSizeUser, ParBlocks, ParBlocksSizeUser, typenum::Unsigned};
+use inout::{InOut, InOutBuf};
+
+/// Trait implemented by block cipher mode encryption backends.
+pub trait BlockCipherEncBackend: ParBlocksSizeUser {
+ /// Encrypt single inout block.
+ fn encrypt_block(&self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Encrypt inout blocks in parallel.
+ #[inline(always)]
+ fn encrypt_par_blocks(&self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.encrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Encrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.encrypt_block(block);
+ }
+ }
+
+ /// Encrypt single block in-place.
+ #[inline(always)]
+ fn encrypt_block_inplace(&self, block: &mut Block<Self>) {
+ self.encrypt_block(block.into());
+ }
+
+ /// Encrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn encrypt_par_blocks_inplace(&self, blocks: &mut ParBlocks<Self>) {
+ self.encrypt_par_blocks(blocks.into());
+ }
+
+ /// Encrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks_inplace(&self, blocks: &mut [Block<Self>]) {
+ self.encrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockCipherEncBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockCipherEncClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockCipherEncBackend<BlockSize = Self::BlockSize>>(self, backend: &B);
+}
+
+/// Trait implemented by block cipher decryption backends.
+pub trait BlockCipherDecBackend: ParBlocksSizeUser {
+ /// Decrypt single inout block.
+ fn decrypt_block(&self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Decrypt inout blocks in parallel.
+ #[inline(always)]
+ fn decrypt_par_blocks(&self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.decrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Decrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks(&self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.decrypt_block(block);
+ }
+ }
+
+ /// Decrypt single block in-place.
+ #[inline(always)]
+ fn decrypt_block_inplace(&self, block: &mut Block<Self>) {
+ self.decrypt_block(block.into());
+ }
+
+ /// Decrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn decrypt_par_blocks_inplace(&self, blocks: &mut ParBlocks<Self>) {
+ self.decrypt_par_blocks(blocks.into());
+ }
+
+ /// Decrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks_inplace(&self, blocks: &mut [Block<Self>]) {
+ self.decrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockCipherDecBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockCipherDecClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockCipherDecBackend<BlockSize = Self::BlockSize>>(self, backend: &B);
+}
+
+/// Trait implemented by block cipher mode encryption backends.
+pub trait BlockModeEncBackend: ParBlocksSizeUser {
+ /// Encrypt single inout block.
+ fn encrypt_block(&mut self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Encrypt inout blocks in parallel.
+ #[inline(always)]
+ fn encrypt_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.encrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Encrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.encrypt_block(block);
+ }
+ }
+
+ /// Encrypt single block in-place.
+ #[inline(always)]
+ fn encrypt_block_inplace(&mut self, block: &mut Block<Self>) {
+ self.encrypt_block(block.into());
+ }
+
+ /// Encrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn encrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
+ self.encrypt_par_blocks(blocks.into());
+ }
+
+ /// Encrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn encrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
+ self.encrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockModeEncBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockModeEncClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockModeEncBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
+}
+
+/// Trait implemented by block cipher mode decryption backends.
+pub trait BlockModeDecBackend: ParBlocksSizeUser {
+ /// Decrypt single inout block.
+ fn decrypt_block(&mut self, block: InOut<'_, '_, Block<Self>>);
+
+ /// Decrypt inout blocks in parallel.
+ #[inline(always)]
+ fn decrypt_par_blocks(&mut self, mut blocks: InOut<'_, '_, ParBlocks<Self>>) {
+ for i in 0..Self::ParBlocksSize::USIZE {
+ self.decrypt_block(blocks.get(i));
+ }
+ }
+
+ /// Decrypt buffer of inout blocks. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks(&mut self, blocks: InOutBuf<'_, '_, Block<Self>>) {
+ assert!(blocks.len() < Self::ParBlocksSize::USIZE);
+ for block in blocks {
+ self.decrypt_block(block);
+ }
+ }
+
+ /// Decrypt single block in-place.
+ #[inline(always)]
+ fn decrypt_block_inplace(&mut self, block: &mut Block<Self>) {
+ self.decrypt_block(block.into());
+ }
+
+ /// Decrypt blocks in parallel in-place.
+ #[inline(always)]
+ fn decrypt_par_blocks_inplace(&mut self, blocks: &mut ParBlocks<Self>) {
+ self.decrypt_par_blocks(blocks.into());
+ }
+
+ /// Decrypt buffer of blocks in-place. Length of the buffer MUST be smaller
+ /// than `Self::ParBlocksSize`.
+ #[inline(always)]
+ fn decrypt_tail_blocks_inplace(&mut self, blocks: &mut [Block<Self>]) {
+ self.decrypt_tail_blocks(blocks.into());
+ }
+}
+
+/// Trait for [`BlockModeDecBackend`] users.
+///
+/// This trait is used to define rank-2 closures.
+pub trait BlockModeDecClosure: BlockSizeUser {
+ /// Execute closure with the provided block cipher backend.
+ fn call<B: BlockModeDecBackend<BlockSize = Self::BlockSize>>(self, backend: &mut B);
+}
### external/vendor/cipher/src/block/ctx.rs
@@ -0,0 +1,120 @@
+use common::{Block, BlockSizeUser, array::ArraySize, typenum::Unsigned};
+use inout::{InOut, InOutBuf};
+
+use super::{
+ BlockCipherDecBackend, BlockCipherDecClosure, BlockCipherEncBackend, BlockCipherEncClosure,
+ BlockModeDecBackend, BlockModeDecClosure, BlockModeEncBackend, BlockModeEncClosure,
+};
+
+/// Closure used in methods which operate over separate blocks.
+pub(super) struct BlockCtx<'inp, 'out, BS: ArraySize> {
+ pub block: InOut<'inp, 'out, Block<Self>>,
+}
+
+impl<BS: ArraySize> BlockSizeUser for BlockCtx<'_, '_, BS> {
+ type BlockSize = BS;
+}
+
+impl<BS: ArraySize> BlockCipherEncClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherEncBackend<BlockSize = BS>>(self, backend: &B) {
+ backend.encrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockCipherDecClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherDecBackend<BlockSize = BS>>(self, backend: &B) {
+ backend.decrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockModeEncClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeEncBackend<BlockSize = BS>>(self, backend: &mut B) {
+ backend.encrypt_block(self.block);
+ }
+}
+
+impl<BS: ArraySize> BlockModeDecClosure for BlockCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeDecBackend<BlockSize = BS>>(self, backend: &mut B) {
+ backend.decrypt_block(self.block);
+ }
+}
+/// Closure used in methods which operate over slice of blocks.
+pub(super) struct BlocksCtx<'inp, 'out, BS: ArraySize> {
+ pub blocks: InOutBuf<'inp, 'out, Block<Self>>,
+}
+
+impl<BS: ArraySize> BlockSizeUser for BlocksCtx<'_, '_, BS> {
+ type BlockSize = BS;
+}
+
+impl<BS: ArraySize> BlockCipherEncClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherEncBackend<BlockSize = BS>>(self, backend: &B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.encrypt_par_blocks(chunk);
+ }
+ backend.encrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.encrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockCipherDecClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockCipherDecBackend<BlockSize = BS>>(self, backend: &B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.decrypt_par_blocks(chunk);
+ }
+ backend.decrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.decrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockModeEncClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeEncBackend<BlockSize = BS>>(self, backend: &mut B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.encrypt_par_blocks(chunk);
+ }
+ backend.encrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.encrypt_block(block);
+ }
+ }
+ }
+}
+
+impl<BS: ArraySize> BlockModeDecClosure for BlocksCtx<'_, '_, BS> {
+ #[inline(always)]
+ fn call<B: BlockModeDecBackend<BlockSize = BS>>(self, backend: &mut B) {
+ if B::ParBlocksSize::USIZE > 1 {
+ let (chunks, tail) = self.blocks.into_chunks();
+ for chunk in chunks {
+ backend.decrypt_par_blocks(chunk);
+ }
+ backend.decrypt_tail_blocks(tail);
+ } else {
+ for block in self.blocks {
+ backend.decrypt_block(block);
+ }
+ }
+ }
+}
### external/vendor/cipher/src/dev.rs
@@ -1,2 +1,7 @@
-mod block;
-mod stream;
+//! Development-related functionality
+mod block_bench;
+pub mod block_cipher;
+pub mod block_mode;
+pub mod stream;
+
+pub use blobby;
### external/vendor/cipher/src/dev/block.rs
@@ -1,389 +0,0 @@
-//! Development-related functionality
-
-pub use blobby;
-
-/// Define block cipher test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_cipher_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob3Iterator, generic_array::GenericArray, typenum::Unsigned,
- BlockDecryptMut, BlockEncryptMut, BlockSizeUser, KeyInit,
- };
-
- fn run_test(key: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- let mut state = <$cipher as KeyInit>::new_from_slice(key).unwrap();
-
- let mut block = GenericArray::clone_from_slice(pt);
- state.encrypt_block_mut(&mut block);
- if ct != block.as_slice() {
- return false;
- }
-
- state.decrypt_block_mut(&mut block);
- if pt != block.as_slice() {
- return false;
- }
-
- true
- }
-
- fn run_par_test(key: &[u8], pt: &[u8]) -> bool {
- type Block = cipher::Block<$cipher>;
-
- let mut state = <$cipher as KeyInit>::new_from_slice(key).unwrap();
-
- let block = Block::clone_from_slice(pt);
- let mut blocks1 = vec![block; 101];
- for (i, b) in blocks1.iter_mut().enumerate() {
- *b = block;
- b[0] = b[0].wrapping_add(i as u8);
- }
- let mut blocks2 = blocks1.clone();
-
- // check that `encrypt_blocks` and `encrypt_block`
- // result in the same ciphertext
- state.encrypt_blocks_mut(&mut blocks1);
- for b in blocks2.iter_mut() {
- state.encrypt_block_mut(b);
- }
- if blocks1 != blocks2 {
- return false;
- }
-
- // check that `encrypt_blocks` and `encrypt_block`
- // result in the same plaintext
- state.decrypt_blocks_mut(&mut blocks1);
- for b in blocks2.iter_mut() {
- state.decrypt_block_mut(b);
- }
- if blocks1 != blocks2 {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob3Iterator::new(data).unwrap().enumerate() {
- let [key, pt, ct] = row.unwrap();
- if !run_test(key, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, pt, ct,
- );
- }
-
- // test parallel blocks encryption/decryption
- if !run_par_test(key, pt) {
- panic!(
- "\n\
- Failed parallel test №{}\n\
- key:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define block mode encryption test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_mode_enc_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob4Iterator, generic_array::GenericArray, inout::InOutBuf,
- typenum::Unsigned, BlockEncryptMut, BlockSizeUser, KeyIvInit,
- };
-
- fn run_test(key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- assert_eq!(pt.len(), ct.len());
- // test block-by-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
-
- let mut out = vec![0u8; ct.len()];
- let mut buf = InOutBuf::new(pt, &mut out).unwrap();
- let (blocks, tail) = buf.reborrow().into_chunks();
- assert_eq!(tail.len(), 0);
- for block in blocks {
- state.encrypt_block_inout_mut(block);
- }
- if buf.get_out() != ct {
- return false;
- }
-
- // test multi-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
- buf.get_out().iter_mut().for_each(|b| *b = 0);
- let (blocks, _) = buf.reborrow().into_chunks();
- state.encrypt_blocks_inout_mut(blocks);
- if buf.get_out() != ct {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() {
- let [key, iv, pt, ct] = row.unwrap();
- if !run_test(key, iv, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- iv:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, iv, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define block mode decryption test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_mode_dec_test {
- ($name:ident, $test_name:expr, $cipher:ty $(,)?) => {
- #[test]
- fn $name() {
- use cipher::{
- blobby::Blob4Iterator, generic_array::GenericArray, inout::InOutBuf,
- typenum::Unsigned, BlockDecryptMut, BlockSizeUser, KeyIvInit,
- };
-
- fn run_test(key: &[u8], iv: &[u8], pt: &[u8], ct: &[u8]) -> bool {
- assert_eq!(pt.len(), ct.len());
- // test block-by-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
-
- let mut out = vec![0u8; pt.len()];
- let mut buf = InOutBuf::new(ct, &mut out).unwrap();
- let (blocks, tail) = buf.reborrow().into_chunks();
- assert_eq!(tail.len(), 0);
- for block in blocks {
- state.decrypt_block_inout_mut(block);
- }
- if buf.get_out() != pt {
- return false;
- }
-
- // test multi-block processing
- let mut state = <$cipher as KeyIvInit>::new_from_slices(key, iv).unwrap();
- buf.get_out().iter_mut().for_each(|b| *b = 0);
- let (blocks, _) = buf.reborrow().into_chunks();
- state.decrypt_blocks_inout_mut(blocks);
- if buf.get_out() != pt {
- return false;
- }
-
- true
- }
-
- let data = include_bytes!(concat!("data/", $test_name, ".blb"));
- for (i, row) in Blob4Iterator::new(data).unwrap().enumerate() {
- let [key, iv, pt, ct] = row.unwrap();
- if !run_test(key, iv, pt, ct) {
- panic!(
- "\n\
- Failed test №{}\n\
- key:\t{:?}\n\
- iv:\t{:?}\n\
- plaintext:\t{:?}\n\
- ciphertext:\t{:?}\n",
- i, key, iv, pt, ct,
- );
- }
- }
- }
- };
-}
-
-/// Define `IvState` test
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! iv_state_test {
- ($name:ident, $cipher:ty, encrypt $(,)?) => {
- $crate::iv_state_test!($name, $cipher, encrypt_blocks_mut);
- };
- ($name:ident, $cipher:ty, decrypt $(,)?) => {
- $crate::iv_state_test!($name, $cipher, decrypt_blocks_mut);
- };
- ($name:ident, $cipher:ty, apply_ks $(,)?) => {
- $crate::iv_state_test!($name, $cipher, apply_keystream_blocks);
- };
- ($name:ident, $cipher:ty, $method:ident $(,)?) => {
- #[test]
- fn $name() {
- use cipher::*;
-
- let mut blocks = [Block::<$cipher>::default(); 32];
-
- for (i, block) in blocks.iter_mut().enumerate() {
- for (j, b) in block.iter_mut().enumerate() {
- *b = (i + j) as u8;
- }
- }
-
- let mut key = Key::<$cipher>::default();
- let mut iv = Iv::<$cipher>::default();
- key.iter_mut().for_each(|b| *b = 0x42);
- iv.iter_mut().for_each(|b| *b = 0x24);
-
- let mut cipher = <$cipher>::new(&key, &iv);
- let mut target = blocks.clone();
- cipher.$method(&mut target);
-
- for i in 0..32 {
- let mut blocks = blocks.clone();
- let (b1, b2) = blocks.split_at_mut(i);
- let mut cipher1 = <$cipher>::new(&key, &iv);
- cipher1.$method(b1);
- let temp_iv = cipher1.iv_state();
- let mut cipher2 = <$cipher>::new(&key, &temp_iv);
- cipher2.$method(b2);
- assert_eq!(blocks, target);
- }
- }
- };
-}
-
-/// Define block encryptor benchmark
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_encryptor_bench {
- (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_encryptor_bench!(
- {
- use $crate::KeyInit;
- let key = test::black_box(Default::default());
- <$cipher>::new(&key)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_encryptor_bench!(
- {
- use $crate::KeyIvInit;
- let key = test::black_box(Default::default());
- let iv = test::black_box(Default::default());
- <$cipher>::new(&key, &iv)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- #[bench]
- pub fn $block_name(bh: &mut test::Bencher) {
- use cipher::BlockEncryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- for block in blocks.iter_mut() {
- cipher.encrypt_block_mut(block);
- }
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
-
- #[bench]
- pub fn $blocks_name(bh: &mut test::Bencher) {
- use cipher::BlockEncryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- cipher.encrypt_blocks_mut(&mut blocks);
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
- };
-}
-
-/// Define block decryptor benchmark
-#[macro_export]
-#[cfg_attr(docsrs, doc(cfg(feature = "dev")))]
-macro_rules! block_decryptor_bench {
- (Key: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_decryptor_bench!(
- {
- use $crate::KeyInit;
- let key = test::black_box(Default::default());
- <$cipher>::new(&key)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- (KeyIv: $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- $crate::block_decryptor_bench!(
- {
- use $crate::KeyIvInit;
- let key = test::black_box(Default::default());
- let iv = test::black_box(Default::default());
- <$cipher>::new(&key, &iv)
- },
- $cipher,
- $block_name,
- $blocks_name,
- );
- };
- ($init:block, $cipher:ty, $block_name:ident, $blocks_name:ident $(,)? ) => {
- #[bench]
- pub fn $block_name(bh: &mut test::Bencher) {
- use cipher::BlockDecryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- for block in blocks.iter_mut() {
- cipher.decrypt_block_mut(block);
- }
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
-
- #[bench]
- pub fn $blocks_name(bh: &mut test::Bencher) {
- use cipher::BlockDecryptMut;
-
- let mut cipher = $init;
- let mut blocks = vec![Default::default(); 1024];
-
- bh.iter(|| {
- cipher.decrypt_blocks_mut(&mut blocks);
- test::black_box(&blocks);
- });
- bh.bytes = (blocks.len() * blocks[0].len()) as u64;
- }
- };
-}
### external/vendor/cipher/src/dev/block_bench.rs
[binary or diff unavailable]
### external/vendor/cipher/src/dev/block_cipher.rs
[binary or diff unavailable]
### external/vendor/cipher/src/dev/block_mode.rs
[binary or diff unavailable]
### external/vendor/cipher/src/dev/stream.rs
[binary or diff unavailable]
### external/vendor/cipher/src/lib.rs
[binary or diff unavailable]
### external/vendor/cipher/src/stream.rs
[binary or diff unavailable]
### external/vendor/cipher/src/stream/core_api.rs
[binary or diff unavailable]
### external/vendor/cipher/src/stream/errors.rs
[binary or diff unavailable]
### external/vendor/cipher/src/stream/wrapper.rs
[binary or diff unavailable]
### external/vendor/cipher/src/stream_wrapper.rs
[binary or diff unavailable]
### external/vendor/cipher/src/tweak.rs
[binary or diff unavailable]
### external/vendor/cipher/src/tweak/ctx.rs
[binary or diff unavailable]
### external/vendor/cipher/src/tweak/zero.rs
[binary or diff unavailable]
### external/vendor/cipher/tests/data/dummy_stream_cipher.blb
[binary or diff unavailable]
### external/vendor/cipher/tests/stream.rs
[binary or diff unavailable]
### external/vendor/cmov/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/cmov/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/cmov/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/cmov/Cargo.lock
[binary or diff unavailable]
### external/vendor/cmov/Cargo.toml
[binary or diff unavailable]
### external/vendor/cmov/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/cmov/LICENSE-APACHE
[binary or diff unavailable]
### external/vendor/cmov/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/cmov/README.md
[binary or diff unavailable]
### external/vendor/cmov/src/array.rs
[binary or diff unavailable]
### external/vendor/cmov/src/backends.rs
[binary or diff unavailable]
### external/vendor/cmov/src/backends/aarch64.rs
[binary or diff unavailable]
### external/vendor/cmov/src/backends/soft.rs
[binary or diff unavailable]
### external/vendor/cmov/src/backends/x86.rs
[binary or diff unavailable]
### external/vendor/cmov/src/lib.rs
[binary or diff unavailable]
### external/vendor/cmov/src/macros.rs
[binary or diff unavailable]
### external/vendor/cmov/src/slice.rs
[binary or diff unavailable]
### external/vendor/cmov/tests/core_impls.rs
[binary or diff unavailable]
### external/vendor/cmov/tests/proptests.rs
[binary or diff unavailable]
### external/vendor/cmov/tests/regression.rs
[binary or diff unavailable]
### external/vendor/const-oid/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/const-oid/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/const-oid/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.lock
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.toml
[binary or diff unavailable]
### external/vendor/const-oid/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/const-oid/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/const-oid/README.md
[binary or diff unavailable]
### external/vendor/const-oid/src/arcs.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/buffer.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/checked.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/db.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/db/generated.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/encoder.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/error.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/lib.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/parser.rs
[binary or diff unavailable]
### external/vendor/const-oid/src/traits.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/lib.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/oid.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/oid_ref.rs
[binary or diff unavailable]
### external/vendor/const-oid/tests/proptests.proptest-regressions
[binary or diff unavailable]
### external/vendor/const-oid/tests/proptests.rs
[binary or diff unavailable]
### external/vendor/cpubits/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/cpubits/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/cpubits/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.lock
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.toml
[binary or diff unavailable]
### external/vendor/cpubits/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/cpubits/LICENSE-APACHE
[binary or diff unavailable]
### external/vendor/cpubits/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/cpubits/README.md
[binary or diff unavailable]
### external/vendor/cpubits/src/lib.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/cpufeatures/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/cpufeatures/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.lock
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.toml
[binary or diff unavailable]
### external/vendor/cpufeatures/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/cpufeatures/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/cpufeatures/README.md
[binary or diff unavailable]
### external/vendor/cpufeatures/src/aarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/lib.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/loongarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/miri.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/src/x86.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/aarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/loongarch64.rs
[binary or diff unavailable]
### external/vendor/cpufeatures/tests/x86.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/.cargo-checksum.json
[binary or diff unavailable]
### external/vendor/crypto-bigint/.cargo_vcs_info.json
[binary or diff unavailable]
### external/vendor/crypto-bigint/.github/workflows/crypto-bigint.yml
[binary or diff unavailable]
### external/vendor/crypto-bigint/.github/workflows/security-audit.yml
[binary or diff unavailable]
### external/vendor/crypto-bigint/CHANGELOG.md
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.lock
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.toml
[binary or diff unavailable]
### external/vendor/crypto-bigint/Cargo.toml.orig
[binary or diff unavailable]
### external/vendor/crypto-bigint/LICENSE-MIT
[binary or diff unavailable]
### external/vendor/crypto-bigint/README.md
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/bench.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/boxed_monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/boxed_uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/const_monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/int.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/limb.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/monty.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/benches/uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/array.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/bitlen.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/boxed/uint/cmp.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/checked.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/ct_choice.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/encoding.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/add.rs
[binary or diff unavailable]
### external/vendor/crypto-bigint/src/int/bit_and.rs
[binary or diff unavailable]Why this scored 25/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.