diff --git a/.containerversion b/.containerversion index 95f9650f01..e373ee695f 100644 --- a/.containerversion +++ b/.containerversion @@ -1 +1 @@ -49 +50 diff --git a/.github/workflows/ci-common.yml b/.github/workflows/ci-common.yml index 61f200423b..e9140034e3 100644 --- a/.github/workflows/ci-common.yml +++ b/.github/workflows/ci-common.yml @@ -126,6 +126,23 @@ jobs: - name: Build simulator run: make -j$(($(nproc) + 1)) simulator + simulator-ng: + runs-on: ubuntu-22.04 + container: ${{ inputs.container-repo }}:${{ inputs.container-version }} + steps: + - name: Clone the repo + uses: actions/checkout@v4 + with: + fetch-depth: 0 + fetch-tags: true + submodules: recursive + + - name: Mark directory as safe + run: git config --global --add safe.directory $GITHUB_WORKSPACE + + - name: Build simulator + run: make -j$(($(nproc) + 1)) simulator-ng + leakcheck: runs-on: ubuntu-22.04 container: ${{ inputs.container-repo }}:${{ inputs.container-version }} diff --git a/.gitmodules b/.gitmodules index 1f05a5cdef..9d021175ca 100644 --- a/.gitmodules +++ b/.gitmodules @@ -13,3 +13,6 @@ [submodule "external/secp256k1-zkp"] path = external/secp256k1-zkp url = https://github.com/BitBoxSwiss/secp256k1-zkp.git +[submodule "external/rust-sdl2"] + path = external/rust-sdl2 + url = https://github.com/BitBoxSwiss/rust-sdl2 diff --git a/CHANGELOG.md b/CHANGELOG.md index 31954aa0e9..accaa092e5 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ customers cannot upgrade their bootloader, its changes are recorded separately. - simulator: enable Test Merchant for payment requests - simulator: simulate a Nova device - Add API call to fetch multiple xpubs at once +- simulator-ng: a new simulator with a graphical user interface ### 9.23.1 - EVM: add HyperEVM (HYPE) and SONIC (S) to known networks diff --git a/CMakeLists.txt b/CMakeLists.txt index 2fe13fb661..e203b5dd68 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -398,6 +398,7 @@ else() include(CTest) add_subdirectory(test/unit-test) add_subdirectory(test/simulator) + add_subdirectory(test/simulator-ng) if(COVERAGE) find_program(GCOVR gcovr) if(NOT GCOVR STREQUAL "GCOVR-NOTFOUND") diff --git a/Dockerfile b/Dockerfile index d7e8ffe90b..1b88e9bec2 100644 --- a/Dockerfile +++ b/Dockerfile @@ -64,6 +64,12 @@ RUN apt-get update && apt-get install -y \ libudev-dev \ libhidapi-dev +# Deps for graphical simulator +RUN apt-get update && apt-get install -y \ + libsdl2-dev \ + libsdl2-image-dev \ + libsdl2-ttf-dev + RUN apt-get update && apt-get install -y \ doxygen \ graphviz diff --git a/Makefile b/Makefile index 4e5dad74c9..0f94d3ad8e 100644 --- a/Makefile +++ b/Makefile @@ -108,6 +108,8 @@ rust-docs: | build $(MAKE) -C build rust-docs simulator: | build-build-noasan $(MAKE) -C build-build-noasan simulator +simulator-ng: | build-build-noasan + $(MAKE) -C build-build-noasan simulator-ng run-simulator: | simulator ./build-build-noasan/bin/simulator unit-test: | build-build @@ -189,3 +191,7 @@ prepare-tidy: | build build-build $(MAKE) -C build-build rust-cbindgen clean: rm -rf build build-build build-debug build-build-noasan + +# When you vendor rust libs avoid duplicates +vendor-rust-deps: + (cd external; ./vendor-rust.sh) diff --git a/external/rust-sdl2 b/external/rust-sdl2 new file mode 160000 index 0000000000..cd5e61133b --- /dev/null +++ b/external/rust-sdl2 @@ -0,0 +1 @@ +Subproject commit cd5e61133b8e9939a4d6278ce39254b5abafc222 diff --git a/external/vendor-rust.sh b/external/vendor-rust.sh index 69756e5377..5bca0a8566 100755 --- a/external/vendor-rust.sh +++ b/external/vendor-rust.sh @@ -21,3 +21,9 @@ RUSTC_BOOTSTRAP=1 cargo vendor \ --manifest-path ../src/rust/Cargo.toml \ --sync "$RUST_SYSROOT/lib/rustlib/src/rust/library/test/Cargo.toml" \ vendor + +RUSTC_BOOTSTRAP=1 cargo vendor \ + --manifest-path ../test/simulator-ng/Cargo.toml \ + --no-delete \ + --sync "$RUST_SYSROOT/lib/rustlib/src/rust/library/test/Cargo.toml" \ + vendor diff --git a/external/vendor/bitflags/.cargo-checksum.json b/external/vendor/bitflags/.cargo-checksum.json new file mode 100644 index 0000000000..7e8d470b53 --- /dev/null +++ b/external/vendor/bitflags/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"d362fc1fccaaf4d421bcf0fe8b80ddb4f625dade0c1ee52d08bd0b95509a49d1","CODE_OF_CONDUCT.md":"42634d0f6d922f49857175af991802822f7f920487aefa2ee250a50d12251a66","Cargo.toml":"87aced7532a7974eb37ab5fe6037f0abafc36d6b2d74891ecd2bf2f14f50d11e","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"6485b8ed310d3f0340bf1ad1f47645069ce4069dcc6bb46c7d5c6faf41de1fdb","README.md":"baa8604f8afb34fd93b9c79729daafb884dedcaf34023e4af8ad037d916061fd","src/example_generated.rs":"e43eb59e90f317f38d436670a6067d2fd9eb35fb319fe716184e4a04e24ed1b2","src/lib.rs":"e6477688535ee326d27238aeedc9cb4320ac35b9d17a4deda09e0587b0ccdbd4","tests/basic.rs":"146f1cbf6279bc609242cd3349f29cb21b41294f5e4921875f5ec95bd83529a2","tests/compile-fail/impls/copy.rs":"b791371237ddc75a7c04d2130e03b462c9c00a80dca08bd45aa97433d9c0d13a","tests/compile-fail/impls/copy.stderr.beta":"77d83484ce221d4b6ff2f7de843929a452d779fcfff428122710dd8218c298e3","tests/compile-fail/impls/eq.rs":"0cee8b9e07d537890e0189710293b53972d0fab63c09366f33c391065afafa99","tests/compile-fail/impls/eq.stderr.beta":"381fc6143d45ce76d7cecc47aa59cb69fe5e79c0b60a4a85d5c6163b400b3cc7","tests/compile-fail/non_integer_base/all_defined.rs":"95e14cad9e94560262f2862c3c01865ac30369b69da1001b0e7285cb55e6cb75","tests/compile-fail/non_integer_base/all_defined.stderr.beta":"1760739a276690903bb03844025587d37939f5dfcbfab309db3c86f32bdbf748","tests/compile-fail/non_integer_base/all_missing.rs":"b3d9da619d23213731ba2581aa7999c796c3c79aaf4f0ee6b11ceec08a11537f","tests/compile-fail/non_integer_base/all_missing.stderr.beta":"37e102290d3867e175b21976be798939f294efb17580d5b51e7b17b590d55132","tests/compile-fail/visibility/private_field.rs":"38e4d3fe6471829360d12c8d09b097f6a21aa93fb51eac3b215d96bdae23316b","tests/compile-fail/visibility/private_field.stderr.beta":"5aa24a3ebb39326f31927721c5017b8beb66c3e501fb865a3fa814c9763bfa0f","tests/compile-fail/visibility/private_flags.rs":"2ce4235802aa4e9c96c4e77d9e31d8401ef58dcda4741325184f0764ab1fe393","tests/compile-fail/visibility/private_flags.stderr.beta":"f3eb9f7baf2689258f3519ff7ee5c6ec3c237264ebcfe63f40c40f2023e5022f","tests/compile-fail/visibility/pub_const.rs":"8f813a97ac518c5ea8ac65b184101912452384afaf7b8d6c5e62f8370eca3c0a","tests/compile-fail/visibility/pub_const.stderr.beta":"823976ae1794d7f5372e2ec9aabba497e7bb88004722904c38da342ed98e8962","tests/compile-pass/impls/convert.rs":"88fe80bfb9cd5779f0e1d92c9ec02a8b6bb67e334c07f2309e9c0ba5ef776eb0","tests/compile-pass/impls/default.rs":"c508f9a461691f44b45142fa5ad599f02326e1de4c0cbca6c0593f4652eba109","tests/compile-pass/impls/inherent_methods.rs":"ecc26388e9a394bfa7a5bb69a5d621ab3d4d1e53f28f657bb8e78fe79f437913","tests/compile-pass/redefinition/core.rs":"ff5b6e72f87acc6ebb12405d3c0f6e3fa62e669933656a454bb63b30ea44179c","tests/compile-pass/redefinition/stringify.rs":"1edbce42b900c14425d7ffa14e83e165ebe452d7dccd8c0a8a821bdec64f5c93","tests/compile-pass/repr/c.rs":"6fda17f7c2edfcd155314579e83d0fc8a16209e400f1f9a5ca77bd9a799041f2","tests/compile-pass/repr/transparent.rs":"6cdc87a2137d8a4e0c8ce9b6cba83c82255f8ea125951bf614418685600489ce","tests/compile-pass/visibility/bits_field.rs":"1f3e5ba5a047440066a9f6bf7b7af33f5b06f6b1da3dd9af6886168199a7ea0a","tests/compile-pass/visibility/pub_in.rs":"e95312ff60966d42ec4bc00225507895a9b8ec24056ce6a9edd9145be35d730f","tests/compile.rs":"f27c67a7dd183ca30efea1b6e0880e3469a6dd63b92b1fd711c082df182c9eec"},"package":"bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"} \ No newline at end of file diff --git a/external/vendor/bitflags/CHANGELOG.md b/external/vendor/bitflags/CHANGELOG.md new file mode 100644 index 0000000000..12fea1673a --- /dev/null +++ b/external/vendor/bitflags/CHANGELOG.md @@ -0,0 +1,206 @@ +# 1.3.2 + +- Allow `non_snake_case` in generated flags types ([#256]) + +[#252]: https://github.com/bitflags/bitflags/pull/256 + +# 1.3.1 + +- Revert unconditional `#[repr(transparent)]` ([#252]) + +[#252]: https://github.com/bitflags/bitflags/pull/252 + +# 1.3.0 (yanked) + +- Add `#[repr(transparent)]` ([#187]) + +- End `empty` doc comment with full stop ([#202]) + +- Fix typo in crate root docs ([#206]) + +- Document from_bits_unchecked unsafety ([#207]) + +- Let `is_all` ignore extra bits ([#211]) + +- Allows empty flag definition ([#225]) + +- Making crate accessible from std ([#227]) + +- Make `from_bits` a const fn ([#229]) + +- Allow multiple bitflags structs in one macro invocation ([#235]) + +- Add named functions to perform set operations ([#244]) + +- Fix typos in method docs ([#245]) + +- Modernization of the `bitflags` macro to take advantage of newer features and 2018 idioms ([#246]) + +- Fix regression (in an unreleased feature) and simplify tests ([#247]) + +- Use `Self` and fix bug when overriding `stringify!` ([#249]) + +[#187]: https://github.com/bitflags/bitflags/pull/187 +[#202]: https://github.com/bitflags/bitflags/pull/202 +[#206]: https://github.com/bitflags/bitflags/pull/206 +[#207]: https://github.com/bitflags/bitflags/pull/207 +[#211]: https://github.com/bitflags/bitflags/pull/211 +[#225]: https://github.com/bitflags/bitflags/pull/225 +[#227]: https://github.com/bitflags/bitflags/pull/227 +[#229]: https://github.com/bitflags/bitflags/pull/229 +[#235]: https://github.com/bitflags/bitflags/pull/235 +[#244]: https://github.com/bitflags/bitflags/pull/244 +[#245]: https://github.com/bitflags/bitflags/pull/245 +[#246]: https://github.com/bitflags/bitflags/pull/246 +[#247]: https://github.com/bitflags/bitflags/pull/247 +[#249]: https://github.com/bitflags/bitflags/pull/249 + +# 1.2.1 + +- Remove extraneous `#[inline]` attributes ([#194]) + +[#194]: https://github.com/bitflags/bitflags/pull/194 + +# 1.2.0 + +- Fix typo: {Lower, Upper}Exp - {Lower, Upper}Hex ([#183]) + +- Add support for "unknown" bits ([#188]) + +[#183]: https://github.com/rust-lang-nursery/bitflags/pull/183 +[#188]: https://github.com/rust-lang-nursery/bitflags/pull/188 + +# 1.1.0 + +This is a re-release of `1.0.5`, which was yanked due to a bug in the RLS. + +# 1.0.5 + +- Use compiletest_rs flags supported by stable toolchain ([#171]) + +- Put the user provided attributes first ([#173]) + +- Make bitflags methods `const` on newer compilers ([#175]) + +[#171]: https://github.com/rust-lang-nursery/bitflags/pull/171 +[#173]: https://github.com/rust-lang-nursery/bitflags/pull/173 +[#175]: https://github.com/rust-lang-nursery/bitflags/pull/175 + +# 1.0.4 + +- Support Rust 2018 style macro imports ([#165]) + + ```rust + use bitflags::bitflags; + ``` + +[#165]: https://github.com/rust-lang-nursery/bitflags/pull/165 + +# 1.0.3 + +- Improve zero value flag handling and documentation ([#157]) + +[#157]: https://github.com/rust-lang-nursery/bitflags/pull/157 + +# 1.0.2 + +- 30% improvement in compile time of bitflags crate ([#156]) + +- Documentation improvements ([#153]) + +- Implementation cleanup ([#149]) + +[#156]: https://github.com/rust-lang-nursery/bitflags/pull/156 +[#153]: https://github.com/rust-lang-nursery/bitflags/pull/153 +[#149]: https://github.com/rust-lang-nursery/bitflags/pull/149 + +# 1.0.1 +- Add support for `pub(restricted)` specifier on the bitflags struct ([#135]) +- Optimize performance of `all()` when called from a separate crate ([#136]) + +[#135]: https://github.com/rust-lang-nursery/bitflags/pull/135 +[#136]: https://github.com/rust-lang-nursery/bitflags/pull/136 + +# 1.0.0 +- **[breaking change]** Macro now generates [associated constants](https://doc.rust-lang.org/reference/items.html#associated-constants) ([#24]) + +- **[breaking change]** Minimum supported version is Rust **1.20**, due to usage of associated constants + +- After being broken in 0.9, the `#[deprecated]` attribute is now supported again ([#112]) + +- Other improvements to unit tests and documentation ([#106] and [#115]) + +[#24]: https://github.com/rust-lang-nursery/bitflags/pull/24 +[#106]: https://github.com/rust-lang-nursery/bitflags/pull/106 +[#112]: https://github.com/rust-lang-nursery/bitflags/pull/112 +[#115]: https://github.com/rust-lang-nursery/bitflags/pull/115 + +## How to update your code to use associated constants +Assuming the following structure definition: +```rust +bitflags! { + struct Something: u8 { + const FOO = 0b01, + const BAR = 0b10 + } +} +``` +In 0.9 and older you could do: +```rust +let x = FOO.bits | BAR.bits; +``` +Now you must use: +```rust +let x = Something::FOO.bits | Something::BAR.bits; +``` + +# 0.9.1 +- Fix the implementation of `Formatting` traits when other formatting traits were present in scope ([#105]) + +[#105]: https://github.com/rust-lang-nursery/bitflags/pull/105 + +# 0.9.0 +- **[breaking change]** Use struct keyword instead of flags to define bitflag types ([#84]) + +- **[breaking change]** Terminate const items with semicolons instead of commas ([#87]) + +- Implement the `Hex`, `Octal`, and `Binary` formatting traits ([#86]) + +- Printing an empty flag value with the `Debug` trait now prints "(empty)" instead of nothing ([#85]) + +- The `bitflags!` macro can now be used inside of a fn body, to define a type local to that function ([#74]) + +[#74]: https://github.com/rust-lang-nursery/bitflags/pull/74 +[#84]: https://github.com/rust-lang-nursery/bitflags/pull/84 +[#85]: https://github.com/rust-lang-nursery/bitflags/pull/85 +[#86]: https://github.com/rust-lang-nursery/bitflags/pull/86 +[#87]: https://github.com/rust-lang-nursery/bitflags/pull/87 + +# 0.8.2 +- Update feature flag used when building bitflags as a dependency of the Rust toolchain + +# 0.8.1 +- Allow bitflags to be used as a dependency of the Rust toolchain + +# 0.8.0 +- Add support for the experimental `i128` and `u128` integer types ([#57]) +- Add set method: `flags.set(SOME_FLAG, true)` or `flags.set(SOME_FLAG, false)` ([#55]) + This may break code that defines its own set method + +[#55]: https://github.com/rust-lang-nursery/bitflags/pull/55 +[#57]: https://github.com/rust-lang-nursery/bitflags/pull/57 + +# 0.7.1 +*(yanked)* + +# 0.7.0 +- Implement the Extend trait ([#49]) +- Allow definitions inside the `bitflags!` macro to refer to items imported from other modules ([#51]) + +[#49]: https://github.com/rust-lang-nursery/bitflags/pull/49 +[#51]: https://github.com/rust-lang-nursery/bitflags/pull/51 + +# 0.6.0 +- The `no_std` feature was removed as it is now the default +- The `assignment_operators` feature was remove as it is now enabled by default +- Some clippy suggestions have been applied diff --git a/external/vendor/bitflags/CODE_OF_CONDUCT.md b/external/vendor/bitflags/CODE_OF_CONDUCT.md new file mode 100644 index 0000000000..f7add90ae3 --- /dev/null +++ b/external/vendor/bitflags/CODE_OF_CONDUCT.md @@ -0,0 +1,73 @@ +# Contributor Covenant Code of Conduct + +## Our Pledge + +In the interest of fostering an open and welcoming environment, we as +contributors and maintainers pledge to making participation in our project and +our community a harassment-free experience for everyone, regardless of age, body +size, disability, ethnicity, gender identity and expression, level of experience, +education, socio-economic status, nationality, personal appearance, race, +religion, or sexual identity and orientation. + +## Our Standards + +Examples of behavior that contributes to creating a positive environment +include: + +* Using welcoming and inclusive language +* Being respectful of differing viewpoints and experiences +* Gracefully accepting constructive criticism +* Focusing on what is best for the community +* Showing empathy towards other community members + +Examples of unacceptable behavior by participants include: + +* The use of sexualized language or imagery and unwelcome sexual attention or + advances +* Trolling, insulting/derogatory comments, and personal or political attacks +* Public or private harassment +* Publishing others' private information, such as a physical or electronic + address, without explicit permission +* Other conduct which could reasonably be considered inappropriate in a + professional setting + +## Our Responsibilities + +Project maintainers are responsible for clarifying the standards of acceptable +behavior and are expected to take appropriate and fair corrective action in +response to any instances of unacceptable behavior. + +Project maintainers have the right and responsibility to remove, edit, or +reject comments, commits, code, wiki edits, issues, and other contributions +that are not aligned to this Code of Conduct, or to ban temporarily or +permanently any contributor for other behaviors that they deem inappropriate, +threatening, offensive, or harmful. + +## Scope + +This Code of Conduct applies both within project spaces and in public spaces +when an individual is representing the project or its community. Examples of +representing a project or community include using an official project e-mail +address, posting via an official social media account, or acting as an appointed +representative at an online or offline event. Representation of a project may be +further defined and clarified by project maintainers. + +## Enforcement + +Instances of abusive, harassing, or otherwise unacceptable behavior may be +reported by contacting the project team at coc@senaite.org. All +complaints will be reviewed and investigated and will result in a response that +is deemed necessary and appropriate to the circumstances. The project team is +obligated to maintain confidentiality with regard to the reporter of an incident. +Further details of specific enforcement policies may be posted separately. + +Project maintainers who do not follow or enforce the Code of Conduct in good +faith may face temporary or permanent repercussions as determined by other +members of the project's leadership. + +## Attribution + +This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4, +available at https://www.contributor-covenant.org/version/1/4/code-of-conduct.html + +[homepage]: https://www.contributor-covenant.org \ No newline at end of file diff --git a/external/vendor/bitflags/Cargo.toml b/external/vendor/bitflags/Cargo.toml new file mode 100644 index 0000000000..9d54c725a1 --- /dev/null +++ b/external/vendor/bitflags/Cargo.toml @@ -0,0 +1,58 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies +# +# If you 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) + +[package] +edition = "2018" +name = "bitflags" +version = "1.3.2" +authors = ["The Rust Project Developers"] +exclude = ["bors.toml"] +description = "A macro to generate structures which behave like bitflags.\n" +homepage = "https://github.com/bitflags/bitflags" +documentation = "https://docs.rs/bitflags" +readme = "README.md" +keywords = ["bit", "bitmask", "bitflags", "flags"] +categories = ["no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/bitflags/bitflags" +[package.metadata.docs.rs] +features = ["example_generated"] +[dependencies.compiler_builtins] +version = "0.1.2" +optional = true + +[dependencies.core] +version = "1.0.0" +optional = true +package = "rustc-std-workspace-core" +[dev-dependencies.rustversion] +version = "1.0" + +[dev-dependencies.serde] +version = "1.0" + +[dev-dependencies.serde_derive] +version = "1.0" + +[dev-dependencies.serde_json] +version = "1.0" + +[dev-dependencies.trybuild] +version = "1.0" + +[dev-dependencies.walkdir] +version = "2.3" + +[features] +default = [] +example_generated = [] +rustc-dep-of-std = ["core", "compiler_builtins"] diff --git a/external/vendor/bitflags/LICENSE-APACHE b/external/vendor/bitflags/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/external/vendor/bitflags/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/external/vendor/bitflags/LICENSE-MIT b/external/vendor/bitflags/LICENSE-MIT new file mode 100644 index 0000000000..39d4bdb5ac --- /dev/null +++ b/external/vendor/bitflags/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/external/vendor/bitflags/README.md b/external/vendor/bitflags/README.md new file mode 100644 index 0000000000..0da0f85366 --- /dev/null +++ b/external/vendor/bitflags/README.md @@ -0,0 +1,32 @@ +bitflags +======== + +[![Rust](https://github.com/bitflags/bitflags/workflows/Rust/badge.svg)](https://github.com/bitflags/bitflags/actions) +[![Join the chat at https://gitter.im/bitflags/Lobby](https://badges.gitter.im/Join%20Chat.svg)](https://gitter.im/bitflags/Lobby?utm_source=badge&utm_medium=badge&utm_content=badge) +[![Latest version](https://img.shields.io/crates/v/bitflags.svg)](https://crates.io/crates/bitflags) +[![Documentation](https://docs.rs/bitflags/badge.svg)](https://docs.rs/bitflags) +![License](https://img.shields.io/crates/l/bitflags.svg) + +A Rust macro to generate structures which behave like a set of bitflags + +- [Documentation](https://docs.rs/bitflags) +- [Release notes](https://github.com/bitflags/bitflags/releases) + +## Usage + +Add this to your `Cargo.toml`: + +```toml +[dependencies] +bitflags = "1.3" +``` + +and this to your source code: + +```rust +use bitflags::bitflags; +``` + +## Rust Version Support + +The minimum supported Rust version is 1.46 due to use of associated constants and const functions. diff --git a/external/vendor/bitflags/src/example_generated.rs b/external/vendor/bitflags/src/example_generated.rs new file mode 100644 index 0000000000..cf188d99cb --- /dev/null +++ b/external/vendor/bitflags/src/example_generated.rs @@ -0,0 +1,14 @@ +//! This module shows an example of code generated by the macro. **IT MUST NOT BE USED OUTSIDE THIS +//! CRATE**. + +bitflags! { + /// This is the same `Flags` struct defined in the [crate level example](../index.html#example). + /// Note that this struct is just for documentation purposes only, it must not be used outside + /// this crate. + pub struct Flags: u32 { + const A = 0b00000001; + const B = 0b00000010; + const C = 0b00000100; + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + } +} diff --git a/external/vendor/bitflags/src/lib.rs b/external/vendor/bitflags/src/lib.rs new file mode 100644 index 0000000000..935e432f17 --- /dev/null +++ b/external/vendor/bitflags/src/lib.rs @@ -0,0 +1,1729 @@ +// Copyright 2014 The Rust Project Developers. See the COPYRIGHT +// file at the top-level directory of this distribution and at +// http://rust-lang.org/COPYRIGHT. +// +// Licensed under the Apache License, Version 2.0 or the MIT license +// , at your +// option. This file may not be copied, modified, or distributed +// except according to those terms. + +//! A typesafe bitmask flag generator useful for sets of C-style bitmask flags. +//! It can be used for creating typesafe wrappers around C APIs. +//! +//! The `bitflags!` macro generates `struct`s that manage a set of flags. The +//! flags should only be defined for integer types, otherwise unexpected type +//! errors may occur at compile time. +//! +//! # Example +//! +//! ``` +//! use bitflags::bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const A = 0b00000001; +//! const B = 0b00000010; +//! const C = 0b00000100; +//! const ABC = Self::A.bits | Self::B.bits | Self::C.bits; +//! } +//! } +//! +//! fn main() { +//! let e1 = Flags::A | Flags::C; +//! let e2 = Flags::B | Flags::C; +//! assert_eq!((e1 | e2), Flags::ABC); // union +//! assert_eq!((e1 & e2), Flags::C); // intersection +//! assert_eq!((e1 - e2), Flags::A); // set difference +//! assert_eq!(!e2, Flags::A); // set complement +//! } +//! ``` +//! +//! See [`example_generated::Flags`](./example_generated/struct.Flags.html) for documentation of code +//! generated by the above `bitflags!` expansion. +//! +//! The generated `struct`s can also be extended with type and trait +//! implementations: +//! +//! ``` +//! use std::fmt; +//! +//! use bitflags::bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const A = 0b00000001; +//! const B = 0b00000010; +//! } +//! } +//! +//! impl Flags { +//! pub fn clear(&mut self) { +//! self.bits = 0; // The `bits` field can be accessed from within the +//! // same module where the `bitflags!` macro was invoked. +//! } +//! } +//! +//! impl fmt::Display for Flags { +//! fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +//! write!(f, "hi!") +//! } +//! } +//! +//! fn main() { +//! let mut flags = Flags::A | Flags::B; +//! flags.clear(); +//! assert!(flags.is_empty()); +//! assert_eq!(format!("{}", flags), "hi!"); +//! assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); +//! assert_eq!(format!("{:?}", Flags::B), "B"); +//! } +//! ``` +//! +//! # Visibility +//! +//! The generated structs and their associated flag constants are not exported +//! out of the current module by default. A definition can be exported out of +//! the current module by adding `pub` before `struct`: +//! +//! ``` +//! mod example { +//! use bitflags::bitflags; +//! +//! bitflags! { +//! pub struct Flags1: u32 { +//! const A = 0b00000001; +//! } +//! +//! # pub +//! struct Flags2: u32 { +//! const B = 0b00000010; +//! } +//! } +//! } +//! +//! fn main() { +//! let flag1 = example::Flags1::A; +//! let flag2 = example::Flags2::B; // error: const `B` is private +//! } +//! ``` +//! +//! # Attributes +//! +//! Attributes can be attached to the generated `struct`s by placing them +//! before the `struct` keyword. +//! +//! ## Representations +//! +//! It's valid to add a `#[repr(C)]` or `#[repr(transparent)]` attribute to a type +//! generated by `bitflags!`. In these cases, the type is guaranteed to be a newtype. +//! +//! ``` +//! use bitflags::bitflags; +//! +//! bitflags! { +//! #[repr(transparent)] +//! struct Flags: u32 { +//! const A = 0b00000001; +//! const B = 0b00000010; +//! const C = 0b00000100; +//! } +//! } +//! ``` +//! +//! # Trait implementations +//! +//! The `Copy`, `Clone`, `PartialEq`, `Eq`, `PartialOrd`, `Ord` and `Hash` +//! traits are automatically derived for the `struct`s using the `derive` attribute. +//! Additional traits can be derived by providing an explicit `derive` +//! attribute on `struct`. +//! +//! The `Extend` and `FromIterator` traits are implemented for the `struct`s, +//! too: `Extend` adds the union of the instances of the `struct` iterated over, +//! while `FromIterator` calculates the union. +//! +//! The `Binary`, `Debug`, `LowerHex`, `Octal` and `UpperHex` traits are also +//! implemented by displaying the bits value of the internal struct. +//! +//! ## Operators +//! +//! The following operator traits are implemented for the generated `struct`s: +//! +//! - `BitOr` and `BitOrAssign`: union +//! - `BitAnd` and `BitAndAssign`: intersection +//! - `BitXor` and `BitXorAssign`: toggle +//! - `Sub` and `SubAssign`: set difference +//! - `Not`: set complement +//! +//! # Methods +//! +//! The following methods are defined for the generated `struct`s: +//! +//! - `empty`: an empty set of flags +//! - `all`: the set of all defined flags +//! - `bits`: the raw value of the flags currently stored +//! - `from_bits`: convert from underlying bit representation, unless that +//! representation contains bits that do not correspond to a +//! defined flag +//! - `from_bits_truncate`: convert from underlying bit representation, dropping +//! any bits that do not correspond to defined flags +//! - `from_bits_unchecked`: convert from underlying bit representation, keeping +//! all bits (even those not corresponding to defined +//! flags) +//! - `is_empty`: `true` if no flags are currently stored +//! - `is_all`: `true` if currently set flags exactly equal all defined flags +//! - `intersects`: `true` if there are flags common to both `self` and `other` +//! - `contains`: `true` if all of the flags in `other` are contained within `self` +//! - `insert`: inserts the specified flags in-place +//! - `remove`: removes the specified flags in-place +//! - `toggle`: the specified flags will be inserted if not present, and removed +//! if they are. +//! - `set`: inserts or removes the specified flags depending on the passed value +//! - `intersection`: returns a new set of flags, containing only the flags present +//! in both `self` and `other` (the argument to the function). +//! - `union`: returns a new set of flags, containing any flags present in +//! either `self` or `other` (the argument to the function). +//! - `difference`: returns a new set of flags, containing all flags present in +//! `self` without any of the flags present in `other` (the +//! argument to the function). +//! - `symmetric_difference`: returns a new set of flags, containing all flags +//! present in either `self` or `other` (the argument +//! to the function), but not both. +//! - `complement`: returns a new set of flags, containing all flags which are +//! not set in `self`, but which are allowed for this type. +//! +//! ## Default +//! +//! The `Default` trait is not automatically implemented for the generated structs. +//! +//! If your default value is equal to `0` (which is the same value as calling `empty()` +//! on the generated struct), you can simply derive `Default`: +//! +//! ``` +//! use bitflags::bitflags; +//! +//! bitflags! { +//! // Results in default value with bits: 0 +//! #[derive(Default)] +//! struct Flags: u32 { +//! const A = 0b00000001; +//! const B = 0b00000010; +//! const C = 0b00000100; +//! } +//! } +//! +//! fn main() { +//! let derived_default: Flags = Default::default(); +//! assert_eq!(derived_default.bits(), 0); +//! } +//! ``` +//! +//! If your default value is not equal to `0` you need to implement `Default` yourself: +//! +//! ``` +//! use bitflags::bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const A = 0b00000001; +//! const B = 0b00000010; +//! const C = 0b00000100; +//! } +//! } +//! +//! // explicit `Default` implementation +//! impl Default for Flags { +//! fn default() -> Flags { +//! Flags::A | Flags::C +//! } +//! } +//! +//! fn main() { +//! let implemented_default: Flags = Default::default(); +//! assert_eq!(implemented_default, (Flags::A | Flags::C)); +//! } +//! ``` +//! +//! # Zero Flags +//! +//! Flags with a value equal to zero will have some strange behavior that one should be aware of. +//! +//! ``` +//! use bitflags::bitflags; +//! +//! bitflags! { +//! struct Flags: u32 { +//! const NONE = 0b00000000; +//! const SOME = 0b00000001; +//! } +//! } +//! +//! fn main() { +//! let empty = Flags::empty(); +//! let none = Flags::NONE; +//! let some = Flags::SOME; +//! +//! // Zero flags are treated as always present +//! assert!(empty.contains(Flags::NONE)); +//! assert!(none.contains(Flags::NONE)); +//! assert!(some.contains(Flags::NONE)); +//! +//! // Zero flags will be ignored when testing for emptiness +//! assert!(none.is_empty()); +//! } +//! ``` +//! +//! Users should generally avoid defining a flag with a value of zero. + +#![cfg_attr(not(test), no_std)] +#![doc(html_root_url = "https://docs.rs/bitflags/1.3.2")] + +#[doc(hidden)] +pub extern crate core as _core; + +/// The macro used to generate the flag structures. +/// +/// See the [crate level docs](../bitflags/index.html) for complete documentation. +/// +/// # Example +/// +/// ``` +/// use bitflags::bitflags; +/// +/// bitflags! { +/// struct Flags: u32 { +/// const A = 0b00000001; +/// const B = 0b00000010; +/// const C = 0b00000100; +/// const ABC = Self::A.bits | Self::B.bits | Self::C.bits; +/// } +/// } +/// +/// fn main() { +/// let e1 = Flags::A | Flags::C; +/// let e2 = Flags::B | Flags::C; +/// assert_eq!((e1 | e2), Flags::ABC); // union +/// assert_eq!((e1 & e2), Flags::C); // intersection +/// assert_eq!((e1 - e2), Flags::A); // set difference +/// assert_eq!(!e2, Flags::A); // set complement +/// } +/// ``` +/// +/// The generated `struct`s can also be extended with type and trait +/// implementations: +/// +/// ``` +/// use std::fmt; +/// +/// use bitflags::bitflags; +/// +/// bitflags! { +/// struct Flags: u32 { +/// const A = 0b00000001; +/// const B = 0b00000010; +/// } +/// } +/// +/// impl Flags { +/// pub fn clear(&mut self) { +/// self.bits = 0; // The `bits` field can be accessed from within the +/// // same module where the `bitflags!` macro was invoked. +/// } +/// } +/// +/// impl fmt::Display for Flags { +/// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +/// write!(f, "hi!") +/// } +/// } +/// +/// fn main() { +/// let mut flags = Flags::A | Flags::B; +/// flags.clear(); +/// assert!(flags.is_empty()); +/// assert_eq!(format!("{}", flags), "hi!"); +/// assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); +/// assert_eq!(format!("{:?}", Flags::B), "B"); +/// } +/// ``` +#[macro_export(local_inner_macros)] +macro_rules! bitflags { + ( + $(#[$outer:meta])* + $vis:vis struct $BitFlags:ident: $T:ty { + $( + $(#[$inner:ident $($args:tt)*])* + const $Flag:ident = $value:expr; + )* + } + + $($t:tt)* + ) => { + $(#[$outer])* + #[derive(Copy, PartialEq, Eq, Clone, PartialOrd, Ord, Hash)] + $vis struct $BitFlags { + bits: $T, + } + + __impl_bitflags! { + $BitFlags: $T { + $( + $(#[$inner $($args)*])* + $Flag = $value; + )* + } + } + + bitflags! { + $($t)* + } + }; + () => {}; +} + +// A helper macro to implement the `all` function. +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_all_bitflags { + ( + $BitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident = $value:expr; + )+ + } + ) => { + // See `Debug::fmt` for why this approach is taken. + #[allow(non_snake_case)] + trait __BitFlags { + $( + const $Flag: $T = 0; + )+ + } + #[allow(non_snake_case)] + impl __BitFlags for $BitFlags { + $( + __impl_bitflags! { + #[allow(deprecated)] + $(? #[$attr $($args)*])* + const $Flag: $T = Self::$Flag.bits; + } + )+ + } + Self { bits: $(::$Flag)|+ } + }; + ( + $BitFlags:ident: $T:ty { } + ) => { + Self { bits: 0 } + }; +} + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __impl_bitflags { + ( + $BitFlags:ident: $T:ty { + $( + $(#[$attr:ident $($args:tt)*])* + $Flag:ident = $value:expr; + )* + } + ) => { + impl $crate::_core::fmt::Debug for $BitFlags { + fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { + // This convoluted approach is to handle #[cfg]-based flag + // omission correctly. For example it needs to support: + // + // #[cfg(unix)] const A: Flag = /* ... */; + // #[cfg(windows)] const B: Flag = /* ... */; + + // Unconditionally define a check for every flag, even disabled + // ones. + #[allow(non_snake_case)] + trait __BitFlags { + $( + #[inline] + fn $Flag(&self) -> bool { false } + )* + } + + // Conditionally override the check for just those flags that + // are not #[cfg]ed away. + #[allow(non_snake_case)] + impl __BitFlags for $BitFlags { + $( + __impl_bitflags! { + #[allow(deprecated)] + #[inline] + $(? #[$attr $($args)*])* + fn $Flag(&self) -> bool { + if Self::$Flag.bits == 0 && self.bits != 0 { + false + } else { + self.bits & Self::$Flag.bits == Self::$Flag.bits + } + } + } + )* + } + + let mut first = true; + $( + if ::$Flag(self) { + if !first { + f.write_str(" | ")?; + } + first = false; + f.write_str($crate::_core::stringify!($Flag))?; + } + )* + let extra_bits = self.bits & !Self::all().bits(); + if extra_bits != 0 { + if !first { + f.write_str(" | ")?; + } + first = false; + f.write_str("0x")?; + $crate::_core::fmt::LowerHex::fmt(&extra_bits, f)?; + } + if first { + f.write_str("(empty)")?; + } + Ok(()) + } + } + impl $crate::_core::fmt::Binary for $BitFlags { + fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { + $crate::_core::fmt::Binary::fmt(&self.bits, f) + } + } + impl $crate::_core::fmt::Octal for $BitFlags { + fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { + $crate::_core::fmt::Octal::fmt(&self.bits, f) + } + } + impl $crate::_core::fmt::LowerHex for $BitFlags { + fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { + $crate::_core::fmt::LowerHex::fmt(&self.bits, f) + } + } + impl $crate::_core::fmt::UpperHex for $BitFlags { + fn fmt(&self, f: &mut $crate::_core::fmt::Formatter) -> $crate::_core::fmt::Result { + $crate::_core::fmt::UpperHex::fmt(&self.bits, f) + } + } + + #[allow(dead_code)] + impl $BitFlags { + $( + $(#[$attr $($args)*])* + pub const $Flag: Self = Self { bits: $value }; + )* + + /// Returns an empty set of flags. + #[inline] + pub const fn empty() -> Self { + Self { bits: 0 } + } + + /// Returns the set containing all flags. + #[inline] + pub const fn all() -> Self { + __impl_all_bitflags! { + $BitFlags: $T { + $( + $(#[$attr $($args)*])* + $Flag = $value; + )* + } + } + } + + /// Returns the raw value of the flags currently stored. + #[inline] + pub const fn bits(&self) -> $T { + self.bits + } + + /// Convert from underlying bit representation, unless that + /// representation contains bits that do not correspond to a flag. + #[inline] + pub const fn from_bits(bits: $T) -> $crate::_core::option::Option { + if (bits & !Self::all().bits()) == 0 { + $crate::_core::option::Option::Some(Self { bits }) + } else { + $crate::_core::option::Option::None + } + } + + /// Convert from underlying bit representation, dropping any bits + /// that do not correspond to flags. + #[inline] + pub const fn from_bits_truncate(bits: $T) -> Self { + Self { bits: bits & Self::all().bits } + } + + /// Convert from underlying bit representation, preserving all + /// bits (even those not corresponding to a defined flag). + /// + /// # Safety + /// + /// The caller of the `bitflags!` macro can chose to allow or + /// disallow extra bits for their bitflags type. + /// + /// The caller of `from_bits_unchecked()` has to ensure that + /// all bits correspond to a defined flag or that extra bits + /// are valid for this bitflags type. + #[inline] + pub const unsafe fn from_bits_unchecked(bits: $T) -> Self { + Self { bits } + } + + /// Returns `true` if no flags are currently stored. + #[inline] + pub const fn is_empty(&self) -> bool { + self.bits() == Self::empty().bits() + } + + /// Returns `true` if all flags are currently set. + #[inline] + pub const fn is_all(&self) -> bool { + Self::all().bits | self.bits == self.bits + } + + /// Returns `true` if there are flags common to both `self` and `other`. + #[inline] + pub const fn intersects(&self, other: Self) -> bool { + !(Self { bits: self.bits & other.bits}).is_empty() + } + + /// Returns `true` if all of the flags in `other` are contained within `self`. + #[inline] + pub const fn contains(&self, other: Self) -> bool { + (self.bits & other.bits) == other.bits + } + + /// Inserts the specified flags in-place. + #[inline] + pub fn insert(&mut self, other: Self) { + self.bits |= other.bits; + } + + /// Removes the specified flags in-place. + #[inline] + pub fn remove(&mut self, other: Self) { + self.bits &= !other.bits; + } + + /// Toggles the specified flags in-place. + #[inline] + pub fn toggle(&mut self, other: Self) { + self.bits ^= other.bits; + } + + /// Inserts or removes the specified flags depending on the passed value. + #[inline] + pub fn set(&mut self, other: Self, value: bool) { + if value { + self.insert(other); + } else { + self.remove(other); + } + } + + /// Returns the intersection between the flags in `self` and + /// `other`. + /// + /// Specifically, the returned set contains only the flags which are + /// present in *both* `self` *and* `other`. + /// + /// This is equivalent to using the `&` operator (e.g. + /// [`ops::BitAnd`]), as in `flags & other`. + /// + /// [`ops::BitAnd`]: https://doc.rust-lang.org/std/ops/trait.BitAnd.html + #[inline] + #[must_use] + pub const fn intersection(self, other: Self) -> Self { + Self { bits: self.bits & other.bits } + } + + /// Returns the union of between the flags in `self` and `other`. + /// + /// Specifically, the returned set contains all flags which are + /// present in *either* `self` *or* `other`, including any which are + /// present in both (see [`Self::symmetric_difference`] if that + /// is undesirable). + /// + /// This is equivalent to using the `|` operator (e.g. + /// [`ops::BitOr`]), as in `flags | other`. + /// + /// [`ops::BitOr`]: https://doc.rust-lang.org/std/ops/trait.BitOr.html + #[inline] + #[must_use] + pub const fn union(self, other: Self) -> Self { + Self { bits: self.bits | other.bits } + } + + /// Returns the difference between the flags in `self` and `other`. + /// + /// Specifically, the returned set contains all flags present in + /// `self`, except for the ones present in `other`. + /// + /// It is also conceptually equivalent to the "bit-clear" operation: + /// `flags & !other` (and this syntax is also supported). + /// + /// This is equivalent to using the `-` operator (e.g. + /// [`ops::Sub`]), as in `flags - other`. + /// + /// [`ops::Sub`]: https://doc.rust-lang.org/std/ops/trait.Sub.html + #[inline] + #[must_use] + pub const fn difference(self, other: Self) -> Self { + Self { bits: self.bits & !other.bits } + } + + /// Returns the [symmetric difference][sym-diff] between the flags + /// in `self` and `other`. + /// + /// Specifically, the returned set contains the flags present which + /// are present in `self` or `other`, but that are not present in + /// both. Equivalently, it contains the flags present in *exactly + /// one* of the sets `self` and `other`. + /// + /// This is equivalent to using the `^` operator (e.g. + /// [`ops::BitXor`]), as in `flags ^ other`. + /// + /// [sym-diff]: https://en.wikipedia.org/wiki/Symmetric_difference + /// [`ops::BitXor`]: https://doc.rust-lang.org/std/ops/trait.BitXor.html + #[inline] + #[must_use] + pub const fn symmetric_difference(self, other: Self) -> Self { + Self { bits: self.bits ^ other.bits } + } + + /// Returns the complement of this set of flags. + /// + /// Specifically, the returned set contains all the flags which are + /// not set in `self`, but which are allowed for this type. + /// + /// Alternatively, it can be thought of as the set difference + /// between [`Self::all()`] and `self` (e.g. `Self::all() - self`) + /// + /// This is equivalent to using the `!` operator (e.g. + /// [`ops::Not`]), as in `!flags`. + /// + /// [`Self::all()`]: Self::all + /// [`ops::Not`]: https://doc.rust-lang.org/std/ops/trait.Not.html + #[inline] + #[must_use] + pub const fn complement(self) -> Self { + Self::from_bits_truncate(!self.bits) + } + + } + + impl $crate::_core::ops::BitOr for $BitFlags { + type Output = Self; + + /// Returns the union of the two sets of flags. + #[inline] + fn bitor(self, other: $BitFlags) -> Self { + Self { bits: self.bits | other.bits } + } + } + + impl $crate::_core::ops::BitOrAssign for $BitFlags { + /// Adds the set of flags. + #[inline] + fn bitor_assign(&mut self, other: Self) { + self.bits |= other.bits; + } + } + + impl $crate::_core::ops::BitXor for $BitFlags { + type Output = Self; + + /// Returns the left flags, but with all the right flags toggled. + #[inline] + fn bitxor(self, other: Self) -> Self { + Self { bits: self.bits ^ other.bits } + } + } + + impl $crate::_core::ops::BitXorAssign for $BitFlags { + /// Toggles the set of flags. + #[inline] + fn bitxor_assign(&mut self, other: Self) { + self.bits ^= other.bits; + } + } + + impl $crate::_core::ops::BitAnd for $BitFlags { + type Output = Self; + + /// Returns the intersection between the two sets of flags. + #[inline] + fn bitand(self, other: Self) -> Self { + Self { bits: self.bits & other.bits } + } + } + + impl $crate::_core::ops::BitAndAssign for $BitFlags { + /// Disables all flags disabled in the set. + #[inline] + fn bitand_assign(&mut self, other: Self) { + self.bits &= other.bits; + } + } + + impl $crate::_core::ops::Sub for $BitFlags { + type Output = Self; + + /// Returns the set difference of the two sets of flags. + #[inline] + fn sub(self, other: Self) -> Self { + Self { bits: self.bits & !other.bits } + } + } + + impl $crate::_core::ops::SubAssign for $BitFlags { + /// Disables all flags enabled in the set. + #[inline] + fn sub_assign(&mut self, other: Self) { + self.bits &= !other.bits; + } + } + + impl $crate::_core::ops::Not for $BitFlags { + type Output = Self; + + /// Returns the complement of this set of flags. + #[inline] + fn not(self) -> Self { + Self { bits: !self.bits } & Self::all() + } + } + + impl $crate::_core::iter::Extend<$BitFlags> for $BitFlags { + fn extend>(&mut self, iterator: T) { + for item in iterator { + self.insert(item) + } + } + } + + impl $crate::_core::iter::FromIterator<$BitFlags> for $BitFlags { + fn from_iter>(iterator: T) -> Self { + let mut result = Self::empty(); + result.extend(iterator); + result + } + } + }; + + // Every attribute that the user writes on a const is applied to the + // corresponding const that we generate, but within the implementation of + // Debug and all() we want to ignore everything but #[cfg] attributes. In + // particular, including a #[deprecated] attribute on those items would fail + // to compile. + // https://github.com/bitflags/bitflags/issues/109 + // + // Input: + // + // ? #[cfg(feature = "advanced")] + // ? #[deprecated(note = "Use something else.")] + // ? #[doc = r"High quality documentation."] + // fn f() -> i32 { /* ... */ } + // + // Output: + // + // #[cfg(feature = "advanced")] + // fn f() -> i32 { /* ... */ } + ( + $(#[$filtered:meta])* + ? #[cfg $($cfgargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + fn $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + #[cfg $($cfgargs)*] + $(? #[$rest $($restargs)*])* + fn $($item)* + } + }; + ( + $(#[$filtered:meta])* + // $next != `cfg` + ? #[$next:ident $($nextargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + fn $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + // $next filtered out + $(? #[$rest $($restargs)*])* + fn $($item)* + } + }; + ( + $(#[$filtered:meta])* + fn $($item:tt)* + ) => { + $(#[$filtered])* + fn $($item)* + }; + + // Every attribute that the user writes on a const is applied to the + // corresponding const that we generate, but within the implementation of + // Debug and all() we want to ignore everything but #[cfg] attributes. In + // particular, including a #[deprecated] attribute on those items would fail + // to compile. + // https://github.com/bitflags/bitflags/issues/109 + // + // const version + // + // Input: + // + // ? #[cfg(feature = "advanced")] + // ? #[deprecated(note = "Use something else.")] + // ? #[doc = r"High quality documentation."] + // const f: i32 { /* ... */ } + // + // Output: + // + // #[cfg(feature = "advanced")] + // const f: i32 { /* ... */ } + ( + $(#[$filtered:meta])* + ? #[cfg $($cfgargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + const $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + #[cfg $($cfgargs)*] + $(? #[$rest $($restargs)*])* + const $($item)* + } + }; + ( + $(#[$filtered:meta])* + // $next != `cfg` + ? #[$next:ident $($nextargs:tt)*] + $(? #[$rest:ident $($restargs:tt)*])* + const $($item:tt)* + ) => { + __impl_bitflags! { + $(#[$filtered])* + // $next filtered out + $(? #[$rest $($restargs)*])* + const $($item)* + } + }; + ( + $(#[$filtered:meta])* + const $($item:tt)* + ) => { + $(#[$filtered])* + const $($item)* + }; +} + +#[cfg(feature = "example_generated")] +pub mod example_generated; + +#[cfg(test)] +mod tests { + use std::collections::hash_map::DefaultHasher; + use std::hash::{Hash, Hasher}; + + bitflags! { + #[doc = "> The first principle is that you must not fool yourself — and"] + #[doc = "> you are the easiest person to fool."] + #[doc = "> "] + #[doc = "> - Richard Feynman"] + #[derive(Default)] + struct Flags: u32 { + const A = 0b00000001; + #[doc = " macros are way better at generating code than trans is"] + const B = 0b00000010; + const C = 0b00000100; + #[doc = "* cmr bed"] + #[doc = "* strcat table"] + #[doc = " wait what?"] + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + } + + struct _CfgFlags: u32 { + #[cfg(unix)] + const _CFG_A = 0b01; + #[cfg(windows)] + const _CFG_B = 0b01; + #[cfg(unix)] + const _CFG_C = Self::_CFG_A.bits | 0b10; + } + + struct AnotherSetOfFlags: i8 { + const ANOTHER_FLAG = -1_i8; + } + + struct LongFlags: u32 { + const LONG_A = 0b1111111111111111; + } + } + + bitflags! { + struct EmptyFlags: u32 { + } + } + + #[test] + fn test_bits() { + assert_eq!(Flags::empty().bits(), 0b00000000); + assert_eq!(Flags::A.bits(), 0b00000001); + assert_eq!(Flags::ABC.bits(), 0b00000111); + + assert_eq!(AnotherSetOfFlags::empty().bits(), 0b00); + assert_eq!(AnotherSetOfFlags::ANOTHER_FLAG.bits(), !0_i8); + + assert_eq!(EmptyFlags::empty().bits(), 0b00000000); + } + + #[test] + fn test_from_bits() { + assert_eq!(Flags::from_bits(0), Some(Flags::empty())); + assert_eq!(Flags::from_bits(0b1), Some(Flags::A)); + assert_eq!(Flags::from_bits(0b10), Some(Flags::B)); + assert_eq!(Flags::from_bits(0b11), Some(Flags::A | Flags::B)); + assert_eq!(Flags::from_bits(0b1000), None); + + assert_eq!( + AnotherSetOfFlags::from_bits(!0_i8), + Some(AnotherSetOfFlags::ANOTHER_FLAG) + ); + + assert_eq!(EmptyFlags::from_bits(0), Some(EmptyFlags::empty())); + assert_eq!(EmptyFlags::from_bits(0b1), None); + } + + #[test] + fn test_from_bits_truncate() { + assert_eq!(Flags::from_bits_truncate(0), Flags::empty()); + assert_eq!(Flags::from_bits_truncate(0b1), Flags::A); + assert_eq!(Flags::from_bits_truncate(0b10), Flags::B); + assert_eq!(Flags::from_bits_truncate(0b11), (Flags::A | Flags::B)); + assert_eq!(Flags::from_bits_truncate(0b1000), Flags::empty()); + assert_eq!(Flags::from_bits_truncate(0b1001), Flags::A); + + assert_eq!( + AnotherSetOfFlags::from_bits_truncate(0_i8), + AnotherSetOfFlags::empty() + ); + + assert_eq!(EmptyFlags::from_bits_truncate(0), EmptyFlags::empty()); + assert_eq!(EmptyFlags::from_bits_truncate(0b1), EmptyFlags::empty()); + } + + #[test] + fn test_from_bits_unchecked() { + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + assert_eq!(unsafe { Flags::from_bits_unchecked(0) }, Flags::empty()); + assert_eq!(unsafe { Flags::from_bits_unchecked(0b1) }, Flags::A); + assert_eq!(unsafe { Flags::from_bits_unchecked(0b10) }, Flags::B); + + assert_eq!( + unsafe { Flags::from_bits_unchecked(0b11) }, + (Flags::A | Flags::B) + ); + assert_eq!( + unsafe { Flags::from_bits_unchecked(0b1000) }, + (extra | Flags::empty()) + ); + assert_eq!( + unsafe { Flags::from_bits_unchecked(0b1001) }, + (extra | Flags::A) + ); + + let extra = unsafe { EmptyFlags::from_bits_unchecked(0b1000) }; + assert_eq!( + unsafe { EmptyFlags::from_bits_unchecked(0b1000) }, + (extra | EmptyFlags::empty()) + ); + } + + #[test] + fn test_is_empty() { + assert!(Flags::empty().is_empty()); + assert!(!Flags::A.is_empty()); + assert!(!Flags::ABC.is_empty()); + + assert!(!AnotherSetOfFlags::ANOTHER_FLAG.is_empty()); + + assert!(EmptyFlags::empty().is_empty()); + assert!(EmptyFlags::all().is_empty()); + } + + #[test] + fn test_is_all() { + assert!(Flags::all().is_all()); + assert!(!Flags::A.is_all()); + assert!(Flags::ABC.is_all()); + + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + assert!(!extra.is_all()); + assert!(!(Flags::A | extra).is_all()); + assert!((Flags::ABC | extra).is_all()); + + assert!(AnotherSetOfFlags::ANOTHER_FLAG.is_all()); + + assert!(EmptyFlags::all().is_all()); + assert!(EmptyFlags::empty().is_all()); + } + + #[test] + fn test_two_empties_do_not_intersect() { + let e1 = Flags::empty(); + let e2 = Flags::empty(); + assert!(!e1.intersects(e2)); + + assert!(AnotherSetOfFlags::ANOTHER_FLAG.intersects(AnotherSetOfFlags::ANOTHER_FLAG)); + } + + #[test] + fn test_empty_does_not_intersect_with_full() { + let e1 = Flags::empty(); + let e2 = Flags::ABC; + assert!(!e1.intersects(e2)); + } + + #[test] + fn test_disjoint_intersects() { + let e1 = Flags::A; + let e2 = Flags::B; + assert!(!e1.intersects(e2)); + } + + #[test] + fn test_overlapping_intersects() { + let e1 = Flags::A; + let e2 = Flags::A | Flags::B; + assert!(e1.intersects(e2)); + } + + #[test] + fn test_contains() { + let e1 = Flags::A; + let e2 = Flags::A | Flags::B; + assert!(!e1.contains(e2)); + assert!(e2.contains(e1)); + assert!(Flags::ABC.contains(e2)); + + assert!(AnotherSetOfFlags::ANOTHER_FLAG.contains(AnotherSetOfFlags::ANOTHER_FLAG)); + + assert!(EmptyFlags::empty().contains(EmptyFlags::empty())); + } + + #[test] + fn test_insert() { + let mut e1 = Flags::A; + let e2 = Flags::A | Flags::B; + e1.insert(e2); + assert_eq!(e1, e2); + + let mut e3 = AnotherSetOfFlags::empty(); + e3.insert(AnotherSetOfFlags::ANOTHER_FLAG); + assert_eq!(e3, AnotherSetOfFlags::ANOTHER_FLAG); + } + + #[test] + fn test_remove() { + let mut e1 = Flags::A | Flags::B; + let e2 = Flags::A | Flags::C; + e1.remove(e2); + assert_eq!(e1, Flags::B); + + let mut e3 = AnotherSetOfFlags::ANOTHER_FLAG; + e3.remove(AnotherSetOfFlags::ANOTHER_FLAG); + assert_eq!(e3, AnotherSetOfFlags::empty()); + } + + #[test] + fn test_operators() { + let e1 = Flags::A | Flags::C; + let e2 = Flags::B | Flags::C; + assert_eq!((e1 | e2), Flags::ABC); // union + assert_eq!((e1 & e2), Flags::C); // intersection + assert_eq!((e1 - e2), Flags::A); // set difference + assert_eq!(!e2, Flags::A); // set complement + assert_eq!(e1 ^ e2, Flags::A | Flags::B); // toggle + let mut e3 = e1; + e3.toggle(e2); + assert_eq!(e3, Flags::A | Flags::B); + + let mut m4 = AnotherSetOfFlags::empty(); + m4.toggle(AnotherSetOfFlags::empty()); + assert_eq!(m4, AnotherSetOfFlags::empty()); + } + + #[test] + fn test_operators_unchecked() { + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + let e1 = Flags::A | Flags::C | extra; + let e2 = Flags::B | Flags::C; + assert_eq!((e1 | e2), (Flags::ABC | extra)); // union + assert_eq!((e1 & e2), Flags::C); // intersection + assert_eq!((e1 - e2), (Flags::A | extra)); // set difference + assert_eq!(!e2, Flags::A); // set complement + assert_eq!(!e1, Flags::B); // set complement + assert_eq!(e1 ^ e2, Flags::A | Flags::B | extra); // toggle + let mut e3 = e1; + e3.toggle(e2); + assert_eq!(e3, Flags::A | Flags::B | extra); + } + + #[test] + fn test_set_ops_basic() { + let ab = Flags::A.union(Flags::B); + let ac = Flags::A.union(Flags::C); + let bc = Flags::B.union(Flags::C); + assert_eq!(ab.bits, 0b011); + assert_eq!(bc.bits, 0b110); + assert_eq!(ac.bits, 0b101); + + assert_eq!(ab, Flags::B.union(Flags::A)); + assert_eq!(ac, Flags::C.union(Flags::A)); + assert_eq!(bc, Flags::C.union(Flags::B)); + + assert_eq!(ac, Flags::A | Flags::C); + assert_eq!(bc, Flags::B | Flags::C); + assert_eq!(ab.union(bc), Flags::ABC); + + assert_eq!(ac, Flags::A | Flags::C); + assert_eq!(bc, Flags::B | Flags::C); + + assert_eq!(ac.union(bc), ac | bc); + assert_eq!(ac.union(bc), Flags::ABC); + assert_eq!(bc.union(ac), Flags::ABC); + + assert_eq!(ac.intersection(bc), ac & bc); + assert_eq!(ac.intersection(bc), Flags::C); + assert_eq!(bc.intersection(ac), Flags::C); + + assert_eq!(ac.difference(bc), ac - bc); + assert_eq!(bc.difference(ac), bc - ac); + assert_eq!(ac.difference(bc), Flags::A); + assert_eq!(bc.difference(ac), Flags::B); + + assert_eq!(bc.complement(), !bc); + assert_eq!(bc.complement(), Flags::A); + assert_eq!(ac.symmetric_difference(bc), Flags::A.union(Flags::B)); + assert_eq!(bc.symmetric_difference(ac), Flags::A.union(Flags::B)); + } + + #[test] + fn test_set_ops_const() { + // These just test that these compile and don't cause use-site panics + // (would be possible if we had some sort of UB) + const INTERSECT: Flags = Flags::all().intersection(Flags::C); + const UNION: Flags = Flags::A.union(Flags::C); + const DIFFERENCE: Flags = Flags::all().difference(Flags::A); + const COMPLEMENT: Flags = Flags::C.complement(); + const SYM_DIFFERENCE: Flags = UNION.symmetric_difference(DIFFERENCE); + assert_eq!(INTERSECT, Flags::C); + assert_eq!(UNION, Flags::A | Flags::C); + assert_eq!(DIFFERENCE, Flags::all() - Flags::A); + assert_eq!(COMPLEMENT, !Flags::C); + assert_eq!(SYM_DIFFERENCE, (Flags::A | Flags::C) ^ (Flags::all() - Flags::A)); + } + + #[test] + fn test_set_ops_unchecked() { + let extra = unsafe { Flags::from_bits_unchecked(0b1000) }; + let e1 = Flags::A.union(Flags::C).union(extra); + let e2 = Flags::B.union(Flags::C); + assert_eq!(e1.bits, 0b1101); + assert_eq!(e1.union(e2), (Flags::ABC | extra)); + assert_eq!(e1.intersection(e2), Flags::C); + assert_eq!(e1.difference(e2), Flags::A | extra); + assert_eq!(e2.difference(e1), Flags::B); + assert_eq!(e2.complement(), Flags::A); + assert_eq!(e1.complement(), Flags::B); + assert_eq!(e1.symmetric_difference(e2), Flags::A | Flags::B | extra); // toggle + } + + #[test] + fn test_set_ops_exhaustive() { + // Define a flag that contains gaps to help exercise edge-cases, + // especially around "unknown" flags (e.g. ones outside of `all()` + // `from_bits_unchecked`). + // - when lhs and rhs both have different sets of unknown flags. + // - unknown flags at both ends, and in the middle + // - cases with "gaps". + bitflags! { + struct Test: u16 { + // Intentionally no `A` + const B = 0b000000010; + // Intentionally no `C` + const D = 0b000001000; + const E = 0b000010000; + const F = 0b000100000; + const G = 0b001000000; + // Intentionally no `H` + const I = 0b100000000; + } + } + let iter_test_flags = + || (0..=0b111_1111_1111).map(|bits| unsafe { Test::from_bits_unchecked(bits) }); + + for a in iter_test_flags() { + assert_eq!( + a.complement(), + Test::from_bits_truncate(!a.bits), + "wrong result: !({:?})", + a, + ); + assert_eq!(a.complement(), !a, "named != op: !({:?})", a); + for b in iter_test_flags() { + // Check that the named operations produce the expected bitwise + // values. + assert_eq!( + a.union(b).bits, + a.bits | b.bits, + "wrong result: `{:?}` | `{:?}`", + a, + b, + ); + assert_eq!( + a.intersection(b).bits, + a.bits & b.bits, + "wrong result: `{:?}` & `{:?}`", + a, + b, + ); + assert_eq!( + a.symmetric_difference(b).bits, + a.bits ^ b.bits, + "wrong result: `{:?}` ^ `{:?}`", + a, + b, + ); + assert_eq!( + a.difference(b).bits, + a.bits & !b.bits, + "wrong result: `{:?}` - `{:?}`", + a, + b, + ); + // Note: Difference is checked as both `a - b` and `b - a` + assert_eq!( + b.difference(a).bits, + b.bits & !a.bits, + "wrong result: `{:?}` - `{:?}`", + b, + a, + ); + // Check that the named set operations are equivalent to the + // bitwise equivalents + assert_eq!(a.union(b), a | b, "named != op: `{:?}` | `{:?}`", a, b,); + assert_eq!( + a.intersection(b), + a & b, + "named != op: `{:?}` & `{:?}`", + a, + b, + ); + assert_eq!( + a.symmetric_difference(b), + a ^ b, + "named != op: `{:?}` ^ `{:?}`", + a, + b, + ); + assert_eq!(a.difference(b), a - b, "named != op: `{:?}` - `{:?}`", a, b,); + // Note: Difference is checked as both `a - b` and `b - a` + assert_eq!(b.difference(a), b - a, "named != op: `{:?}` - `{:?}`", b, a,); + // Verify that the operations which should be symmetric are + // actually symmetric. + assert_eq!(a.union(b), b.union(a), "asymmetry: `{:?}` | `{:?}`", a, b,); + assert_eq!( + a.intersection(b), + b.intersection(a), + "asymmetry: `{:?}` & `{:?}`", + a, + b, + ); + assert_eq!( + a.symmetric_difference(b), + b.symmetric_difference(a), + "asymmetry: `{:?}` ^ `{:?}`", + a, + b, + ); + } + } + } + + #[test] + fn test_set() { + let mut e1 = Flags::A | Flags::C; + e1.set(Flags::B, true); + e1.set(Flags::C, false); + + assert_eq!(e1, Flags::A | Flags::B); + } + + #[test] + fn test_assignment_operators() { + let mut m1 = Flags::empty(); + let e1 = Flags::A | Flags::C; + // union + m1 |= Flags::A; + assert_eq!(m1, Flags::A); + // intersection + m1 &= e1; + assert_eq!(m1, Flags::A); + // set difference + m1 -= m1; + assert_eq!(m1, Flags::empty()); + // toggle + m1 ^= e1; + assert_eq!(m1, e1); + } + + #[test] + fn test_const_fn() { + const _M1: Flags = Flags::empty(); + + const M2: Flags = Flags::A; + assert_eq!(M2, Flags::A); + + const M3: Flags = Flags::C; + assert_eq!(M3, Flags::C); + } + + #[test] + fn test_extend() { + let mut flags; + + flags = Flags::empty(); + flags.extend([].iter().cloned()); + assert_eq!(flags, Flags::empty()); + + flags = Flags::empty(); + flags.extend([Flags::A, Flags::B].iter().cloned()); + assert_eq!(flags, Flags::A | Flags::B); + + flags = Flags::A; + flags.extend([Flags::A, Flags::B].iter().cloned()); + assert_eq!(flags, Flags::A | Flags::B); + + flags = Flags::B; + flags.extend([Flags::A, Flags::ABC].iter().cloned()); + assert_eq!(flags, Flags::ABC); + } + + #[test] + fn test_from_iterator() { + assert_eq!([].iter().cloned().collect::(), Flags::empty()); + assert_eq!( + [Flags::A, Flags::B].iter().cloned().collect::(), + Flags::A | Flags::B + ); + assert_eq!( + [Flags::A, Flags::ABC].iter().cloned().collect::(), + Flags::ABC + ); + } + + #[test] + fn test_lt() { + let mut a = Flags::empty(); + let mut b = Flags::empty(); + + assert!(!(a < b) && !(b < a)); + b = Flags::B; + assert!(a < b); + a = Flags::C; + assert!(!(a < b) && b < a); + b = Flags::C | Flags::B; + assert!(a < b); + } + + #[test] + fn test_ord() { + let mut a = Flags::empty(); + let mut b = Flags::empty(); + + assert!(a <= b && a >= b); + a = Flags::A; + assert!(a > b && a >= b); + assert!(b < a && b <= a); + b = Flags::B; + assert!(b > a && b >= a); + assert!(a < b && a <= b); + } + + fn hash(t: &T) -> u64 { + let mut s = DefaultHasher::new(); + t.hash(&mut s); + s.finish() + } + + #[test] + fn test_hash() { + let mut x = Flags::empty(); + let mut y = Flags::empty(); + assert_eq!(hash(&x), hash(&y)); + x = Flags::all(); + y = Flags::ABC; + assert_eq!(hash(&x), hash(&y)); + } + + #[test] + fn test_default() { + assert_eq!(Flags::empty(), Flags::default()); + } + + #[test] + fn test_debug() { + assert_eq!(format!("{:?}", Flags::A | Flags::B), "A | B"); + assert_eq!(format!("{:?}", Flags::empty()), "(empty)"); + assert_eq!(format!("{:?}", Flags::ABC), "A | B | C | ABC"); + let extra = unsafe { Flags::from_bits_unchecked(0xb8) }; + assert_eq!(format!("{:?}", extra), "0xb8"); + assert_eq!(format!("{:?}", Flags::A | extra), "A | 0xb8"); + + assert_eq!( + format!("{:?}", Flags::ABC | extra), + "A | B | C | ABC | 0xb8" + ); + + assert_eq!(format!("{:?}", EmptyFlags::empty()), "(empty)"); + } + + #[test] + fn test_binary() { + assert_eq!(format!("{:b}", Flags::ABC), "111"); + assert_eq!(format!("{:#b}", Flags::ABC), "0b111"); + let extra = unsafe { Flags::from_bits_unchecked(0b1010000) }; + assert_eq!(format!("{:b}", Flags::ABC | extra), "1010111"); + assert_eq!(format!("{:#b}", Flags::ABC | extra), "0b1010111"); + } + + #[test] + fn test_octal() { + assert_eq!(format!("{:o}", LongFlags::LONG_A), "177777"); + assert_eq!(format!("{:#o}", LongFlags::LONG_A), "0o177777"); + let extra = unsafe { LongFlags::from_bits_unchecked(0o5000000) }; + assert_eq!(format!("{:o}", LongFlags::LONG_A | extra), "5177777"); + assert_eq!(format!("{:#o}", LongFlags::LONG_A | extra), "0o5177777"); + } + + #[test] + fn test_lowerhex() { + assert_eq!(format!("{:x}", LongFlags::LONG_A), "ffff"); + assert_eq!(format!("{:#x}", LongFlags::LONG_A), "0xffff"); + let extra = unsafe { LongFlags::from_bits_unchecked(0xe00000) }; + assert_eq!(format!("{:x}", LongFlags::LONG_A | extra), "e0ffff"); + assert_eq!(format!("{:#x}", LongFlags::LONG_A | extra), "0xe0ffff"); + } + + #[test] + fn test_upperhex() { + assert_eq!(format!("{:X}", LongFlags::LONG_A), "FFFF"); + assert_eq!(format!("{:#X}", LongFlags::LONG_A), "0xFFFF"); + let extra = unsafe { LongFlags::from_bits_unchecked(0xe00000) }; + assert_eq!(format!("{:X}", LongFlags::LONG_A | extra), "E0FFFF"); + assert_eq!(format!("{:#X}", LongFlags::LONG_A | extra), "0xE0FFFF"); + } + + mod submodule { + bitflags! { + pub struct PublicFlags: i8 { + const X = 0; + } + + struct PrivateFlags: i8 { + const Y = 0; + } + } + + #[test] + fn test_private() { + let _ = PrivateFlags::Y; + } + } + + #[test] + fn test_public() { + let _ = submodule::PublicFlags::X; + } + + mod t1 { + mod foo { + pub type Bar = i32; + } + + bitflags! { + /// baz + struct Flags: foo::Bar { + const A = 0b00000001; + #[cfg(foo)] + const B = 0b00000010; + #[cfg(foo)] + const C = 0b00000010; + } + } + } + + #[test] + fn test_in_function() { + bitflags! { + struct Flags: u8 { + const A = 1; + #[cfg(any())] // false + const B = 2; + } + } + assert_eq!(Flags::all(), Flags::A); + assert_eq!(format!("{:?}", Flags::A), "A"); + } + + #[test] + fn test_deprecated() { + bitflags! { + pub struct TestFlags: u32 { + #[deprecated(note = "Use something else.")] + const ONE = 1; + } + } + } + + #[test] + fn test_pub_crate() { + mod module { + bitflags! { + pub (crate) struct Test: u8 { + const FOO = 1; + } + } + } + + assert_eq!(module::Test::FOO.bits(), 1); + } + + #[test] + fn test_pub_in_module() { + mod module { + mod submodule { + bitflags! { + // `pub (in super)` means only the module `module` will + // be able to access this. + pub (in super) struct Test: u8 { + const FOO = 1; + } + } + } + + mod test { + // Note: due to `pub (in super)`, + // this cannot be accessed directly by the testing code. + pub(super) fn value() -> u8 { + super::submodule::Test::FOO.bits() + } + } + + pub fn value() -> u8 { + test::value() + } + } + + assert_eq!(module::value(), 1) + } + + #[test] + fn test_zero_value_flags() { + bitflags! { + struct Flags: u32 { + const NONE = 0b0; + const SOME = 0b1; + } + } + + assert!(Flags::empty().contains(Flags::NONE)); + assert!(Flags::SOME.contains(Flags::NONE)); + assert!(Flags::NONE.is_empty()); + + assert_eq!(format!("{:?}", Flags::empty()), "NONE"); + assert_eq!(format!("{:?}", Flags::SOME), "SOME"); + } + + #[test] + fn test_empty_bitflags() { + bitflags! {} + } + + #[test] + fn test_u128_bitflags() { + bitflags! { + struct Flags128: u128 { + const A = 0x0000_0000_0000_0000_0000_0000_0000_0001; + const B = 0x0000_0000_0000_1000_0000_0000_0000_0000; + const C = 0x8000_0000_0000_0000_0000_0000_0000_0000; + const ABC = Self::A.bits | Self::B.bits | Self::C.bits; + } + } + + assert_eq!(Flags128::ABC, Flags128::A | Flags128::B | Flags128::C); + assert_eq!(Flags128::A.bits, 0x0000_0000_0000_0000_0000_0000_0000_0001); + assert_eq!(Flags128::B.bits, 0x0000_0000_0000_1000_0000_0000_0000_0000); + assert_eq!(Flags128::C.bits, 0x8000_0000_0000_0000_0000_0000_0000_0000); + assert_eq!( + Flags128::ABC.bits, + 0x8000_0000_0000_1000_0000_0000_0000_0001 + ); + assert_eq!(format!("{:?}", Flags128::A), "A"); + assert_eq!(format!("{:?}", Flags128::B), "B"); + assert_eq!(format!("{:?}", Flags128::C), "C"); + assert_eq!(format!("{:?}", Flags128::ABC), "A | B | C | ABC"); + } + + #[test] + fn test_serde_bitflags_serialize() { + let flags = SerdeFlags::A | SerdeFlags::B; + + let serialized = serde_json::to_string(&flags).unwrap(); + + assert_eq!(serialized, r#"{"bits":3}"#); + } + + #[test] + fn test_serde_bitflags_deserialize() { + let deserialized: SerdeFlags = serde_json::from_str(r#"{"bits":12}"#).unwrap(); + + let expected = SerdeFlags::C | SerdeFlags::D; + + assert_eq!(deserialized.bits, expected.bits); + } + + #[test] + fn test_serde_bitflags_roundtrip() { + let flags = SerdeFlags::A | SerdeFlags::B; + + let deserialized: SerdeFlags = serde_json::from_str(&serde_json::to_string(&flags).unwrap()).unwrap(); + + assert_eq!(deserialized.bits, flags.bits); + } + + bitflags! { + #[derive(serde::Serialize, serde::Deserialize)] + struct SerdeFlags: u32 { + const A = 1; + const B = 2; + const C = 4; + const D = 8; + } + } +} diff --git a/external/vendor/bitflags/tests/basic.rs b/external/vendor/bitflags/tests/basic.rs new file mode 100644 index 0000000000..73a52bec50 --- /dev/null +++ b/external/vendor/bitflags/tests/basic.rs @@ -0,0 +1,20 @@ +#![no_std] + +use bitflags::bitflags; + +bitflags! { + /// baz + struct Flags: u32 { + const A = 0b00000001; + #[doc = "bar"] + const B = 0b00000010; + const C = 0b00000100; + #[doc = "foo"] + const ABC = Flags::A.bits | Flags::B.bits | Flags::C.bits; + } +} + +#[test] +fn basic() { + assert_eq!(Flags::ABC, Flags::A | Flags::B | Flags::C); +} diff --git a/external/vendor/bitflags/tests/compile-fail/impls/copy.rs b/external/vendor/bitflags/tests/compile-fail/impls/copy.rs new file mode 100644 index 0000000000..38f4822f5a --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/impls/copy.rs @@ -0,0 +1,10 @@ +use bitflags::bitflags; + +bitflags! { + #[derive(Clone, Copy)] + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-fail/impls/copy.stderr.beta b/external/vendor/bitflags/tests/compile-fail/impls/copy.stderr.beta new file mode 100644 index 0000000000..0c13aa5024 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/impls/copy.stderr.beta @@ -0,0 +1,27 @@ +error[E0119]: conflicting implementations of trait `std::clone::Clone` for type `Flags` + --> $DIR/copy.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(Clone, Copy)] + | | ----- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `Clone` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `std::marker::Copy` for type `Flags` + --> $DIR/copy.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(Clone, Copy)] + | | ---- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/bitflags/tests/compile-fail/impls/eq.rs b/external/vendor/bitflags/tests/compile-fail/impls/eq.rs new file mode 100644 index 0000000000..4abbd630c6 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/impls/eq.rs @@ -0,0 +1,10 @@ +use bitflags::bitflags; + +bitflags! { + #[derive(PartialEq, Eq)] + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-fail/impls/eq.stderr.beta b/external/vendor/bitflags/tests/compile-fail/impls/eq.stderr.beta new file mode 100644 index 0000000000..8a1a3b410a --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/impls/eq.stderr.beta @@ -0,0 +1,55 @@ +error[E0119]: conflicting implementations of trait `std::cmp::PartialEq` for type `Flags` + --> $DIR/eq.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(PartialEq, Eq)] + | | --------- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `std::cmp::Eq` for type `Flags` + --> $DIR/eq.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(PartialEq, Eq)] + | | -- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `std::marker::StructuralPartialEq` for type `Flags` + --> $DIR/eq.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(PartialEq, Eq)] + | | --------- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `PartialEq` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0119]: conflicting implementations of trait `std::marker::StructuralEq` for type `Flags` + --> $DIR/eq.rs:3:1 + | +3 | / bitflags! { +4 | | #[derive(PartialEq, Eq)] + | | -- first implementation here +5 | | struct Flags: u32 { +6 | | const A = 0b00000001; +7 | | } +8 | | } + | |_^ conflicting implementation for `Flags` + | + = note: this error originates in the derive macro `Eq` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.rs b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.rs new file mode 100644 index 0000000000..c2856b1083 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.rs @@ -0,0 +1,123 @@ +use std::{ + fmt::{ + self, + Debug, + Display, + LowerHex, + UpperHex, + Octal, + Binary, + }, + ops::{ + BitAnd, + BitOr, + BitXor, + BitAndAssign, + BitOrAssign, + BitXorAssign, + Not, + }, +}; + +use bitflags::bitflags; + +// Ideally we'd actually want this to work, but currently need something like `num`'s `Zero` +// With some design work it could be made possible +#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] +struct MyInt(u8); + +impl BitAnd for MyInt { + type Output = Self; + + fn bitand(self, other: Self) -> Self { + MyInt(self.0 & other.0) + } +} + +impl BitOr for MyInt { + type Output = Self; + + fn bitor(self, other: Self) -> Self { + MyInt(self.0 | other.0) + } +} + +impl BitXor for MyInt { + type Output = Self; + + fn bitxor(self, other: Self) -> Self { + MyInt(self.0 ^ other.0) + } +} + +impl BitAndAssign for MyInt { + fn bitand_assign(&mut self, other: Self) { + self.0 &= other.0 + } +} + +impl BitOrAssign for MyInt { + fn bitor_assign(&mut self, other: Self) { + self.0 |= other.0 + } +} + +impl BitXorAssign for MyInt { + fn bitxor_assign(&mut self, other: Self) { + self.0 ^= other.0 + } +} + +impl Debug for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Debug::fmt(&self.0, f) + } +} + +impl Display for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Display::fmt(&self.0, f) + } +} + +impl LowerHex for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + LowerHex::fmt(&self.0, f) + } +} + +impl UpperHex for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + UpperHex::fmt(&self.0, f) + } +} + +impl Octal for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Octal::fmt(&self.0, f) + } +} + +impl Binary for MyInt { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + Binary::fmt(&self.0, f) + } +} + +impl Not for MyInt { + type Output = MyInt; + + fn not(self) -> Self { + MyInt(!self.0) + } +} + +bitflags! { + struct Flags128: MyInt { + const A = MyInt(0b0000_0001u8); + const B = MyInt(0b0000_0010u8); + const C = MyInt(0b0000_0100u8); + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.stderr.beta b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.stderr.beta new file mode 100644 index 0000000000..1f0fb5cf7a --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_defined.stderr.beta @@ -0,0 +1,27 @@ +error[E0308]: mismatched types + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ expected struct `MyInt`, found integer + | + = note: this error originates in the macro `__impl_all_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0308]: mismatched types + --> $DIR/all_defined.rs:115:1 + | +115 | / bitflags! { +116 | | struct Flags128: MyInt { +117 | | const A = MyInt(0b0000_0001u8); +118 | | const B = MyInt(0b0000_0010u8); +119 | | const C = MyInt(0b0000_0100u8); +120 | | } +121 | | } + | |_^ expected struct `MyInt`, found integer + | + = note: this error originates in the macro `__impl_bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.rs b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.rs new file mode 100644 index 0000000000..fff6b2cc13 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.rs @@ -0,0 +1,13 @@ +use bitflags::bitflags; + +struct MyInt(u8); + +bitflags! { + struct Flags128: MyInt { + const A = MyInt(0b0000_0001); + const B = MyInt(0b0000_0010); + const C = MyInt(0b0000_0100); + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.stderr.beta b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.stderr.beta new file mode 100644 index 0000000000..ee95f8365e --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/non_integer_base/all_missing.stderr.beta @@ -0,0 +1,13 @@ +error[E0204]: the trait `Copy` may not be implemented for this type + --> $DIR/all_missing.rs:5:1 + | +5 | / bitflags! { +6 | | struct Flags128: MyInt { +7 | | const A = MyInt(0b0000_0001); +8 | | const B = MyInt(0b0000_0010); +9 | | const C = MyInt(0b0000_0100); +10 | | } +11 | | } + | |_^ this field does not implement `Copy` + | + = note: this error originates in the derive macro `Copy` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/private_field.rs b/external/vendor/bitflags/tests/compile-fail/visibility/private_field.rs new file mode 100644 index 0000000000..a6a3912aea --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/private_field.rs @@ -0,0 +1,13 @@ +mod example { + use bitflags::bitflags; + + bitflags! { + pub struct Flags1: u32 { + const FLAG_A = 0b00000001; + } + } +} + +fn main() { + let flag1 = example::Flags1::FLAG_A.bits; +} diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/private_field.stderr.beta b/external/vendor/bitflags/tests/compile-fail/visibility/private_field.stderr.beta new file mode 100644 index 0000000000..58a0466016 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/private_field.stderr.beta @@ -0,0 +1,10 @@ +error[E0616]: field `bits` of struct `Flags1` is private + --> $DIR/private_field.rs:12:41 + | +12 | let flag1 = example::Flags1::FLAG_A.bits; + | ^^^^ private field + | +help: a method `bits` also exists, call it with parentheses + | +12 | let flag1 = example::Flags1::FLAG_A.bits(); + | ^^ diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.rs b/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.rs new file mode 100644 index 0000000000..85a5b1863d --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.rs @@ -0,0 +1,18 @@ +mod example { + use bitflags::bitflags; + + bitflags! { + pub struct Flags1: u32 { + const FLAG_A = 0b00000001; + } + + struct Flags2: u32 { + const FLAG_B = 0b00000010; + } + } +} + +fn main() { + let flag1 = example::Flags1::FLAG_A; + let flag2 = example::Flags2::FLAG_B; +} diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.stderr.beta b/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.stderr.beta new file mode 100644 index 0000000000..d23f83209b --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/private_flags.stderr.beta @@ -0,0 +1,18 @@ +error[E0603]: struct `Flags2` is private + --> $DIR/private_flags.rs:17:26 + | +17 | let flag2 = example::Flags2::FLAG_B; + | ^^^^^^ private struct + | +note: the struct `Flags2` is defined here + --> $DIR/private_flags.rs:4:5 + | +4 | / bitflags! { +5 | | pub struct Flags1: u32 { +6 | | const FLAG_A = 0b00000001; +7 | | } +... | +11 | | } +12 | | } + | |_____^ + = note: this error originates in the macro `bitflags` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.rs b/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.rs new file mode 100644 index 0000000000..b90f0ce92d --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.rs @@ -0,0 +1,9 @@ +use bitflags::bitflags; + +bitflags! { + pub struct Flags1: u32 { + pub const FLAG_A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.stderr.beta b/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.stderr.beta new file mode 100644 index 0000000000..b01122c7ad --- /dev/null +++ b/external/vendor/bitflags/tests/compile-fail/visibility/pub_const.stderr.beta @@ -0,0 +1,5 @@ +error: no rules expected the token `pub` + --> $DIR/pub_const.rs:5:9 + | +5 | pub const FLAG_A = 0b00000001; + | ^^^ no rules expected this token in macro call diff --git a/external/vendor/bitflags/tests/compile-pass/impls/convert.rs b/external/vendor/bitflags/tests/compile-pass/impls/convert.rs new file mode 100644 index 0000000000..1f02982a8f --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/impls/convert.rs @@ -0,0 +1,17 @@ +use bitflags::bitflags; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + } +} + +impl From for Flags { + fn from(v: u32) -> Flags { + Flags::from_bits_truncate(v) + } +} + +fn main() { + +} diff --git a/external/vendor/bitflags/tests/compile-pass/impls/default.rs b/external/vendor/bitflags/tests/compile-pass/impls/default.rs new file mode 100644 index 0000000000..a97b6536f2 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/impls/default.rs @@ -0,0 +1,10 @@ +use bitflags::bitflags; + +bitflags! { + #[derive(Default)] + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-pass/impls/inherent_methods.rs b/external/vendor/bitflags/tests/compile-pass/impls/inherent_methods.rs new file mode 100644 index 0000000000..3052c460ec --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/impls/inherent_methods.rs @@ -0,0 +1,15 @@ +use bitflags::bitflags; + +bitflags! { + struct Flags: u32 { + const A = 0b00000001; + } +} + +impl Flags { + pub fn new() -> Flags { + Flags::A + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-pass/redefinition/core.rs b/external/vendor/bitflags/tests/compile-pass/redefinition/core.rs new file mode 100644 index 0000000000..4754921594 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/redefinition/core.rs @@ -0,0 +1,14 @@ +use bitflags::bitflags; + +// Checks for possible errors caused by overriding names used by `bitflags!` internally. + +mod core {} +mod _core {} + +bitflags! { + struct Test: u8 { + const A = 1; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-pass/redefinition/stringify.rs b/external/vendor/bitflags/tests/compile-pass/redefinition/stringify.rs new file mode 100644 index 0000000000..b04f2f6a49 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/redefinition/stringify.rs @@ -0,0 +1,19 @@ +use bitflags::bitflags; + +// Checks for possible errors caused by overriding names used by `bitflags!` internally. + +#[allow(unused_macros)] +macro_rules! stringify { + ($($t:tt)*) => { "..." }; +} + +bitflags! { + struct Test: u8 { + const A = 1; + } +} + +fn main() { + // Just make sure we don't call the redefined `stringify` macro + assert_eq!(format!("{:?}", Test::A), "A"); +} diff --git a/external/vendor/bitflags/tests/compile-pass/repr/c.rs b/external/vendor/bitflags/tests/compile-pass/repr/c.rs new file mode 100644 index 0000000000..6feba36ed8 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/repr/c.rs @@ -0,0 +1,10 @@ +use bitflags::bitflags; + +bitflags! { + #[repr(C)] + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-pass/repr/transparent.rs b/external/vendor/bitflags/tests/compile-pass/repr/transparent.rs new file mode 100644 index 0000000000..e38db4dd11 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/repr/transparent.rs @@ -0,0 +1,10 @@ +use bitflags::bitflags; + +bitflags! { + #[repr(transparent)] + struct Flags: u32 { + const A = 0b00000001; + } +} + +fn main() {} diff --git a/external/vendor/bitflags/tests/compile-pass/visibility/bits_field.rs b/external/vendor/bitflags/tests/compile-pass/visibility/bits_field.rs new file mode 100644 index 0000000000..33a7967e62 --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/visibility/bits_field.rs @@ -0,0 +1,11 @@ +use bitflags::bitflags; + +bitflags! { + pub struct Flags1: u32 { + const FLAG_A = 0b00000001; + } +} + +fn main() { + assert_eq!(0b00000001, Flags1::FLAG_A.bits); +} diff --git a/external/vendor/bitflags/tests/compile-pass/visibility/pub_in.rs b/external/vendor/bitflags/tests/compile-pass/visibility/pub_in.rs new file mode 100644 index 0000000000..c11050e3ba --- /dev/null +++ b/external/vendor/bitflags/tests/compile-pass/visibility/pub_in.rs @@ -0,0 +1,19 @@ +mod a { + mod b { + use bitflags::bitflags; + + bitflags! { + pub(in crate::a) struct Flags: u32 { + const FLAG_A = 0b00000001; + } + } + } + + pub fn flags() -> u32 { + b::Flags::FLAG_A.bits() + } +} + +fn main() { + assert_eq!(0b00000001, a::flags()); +} diff --git a/external/vendor/bitflags/tests/compile.rs b/external/vendor/bitflags/tests/compile.rs new file mode 100644 index 0000000000..ed02d01e9c --- /dev/null +++ b/external/vendor/bitflags/tests/compile.rs @@ -0,0 +1,63 @@ +use std::{ + fs, + ffi::OsStr, + io, + path::Path, +}; + +use walkdir::WalkDir; + +#[test] +fn fail() { + prepare_stderr_files("tests/compile-fail").unwrap(); + + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile-fail/**/*.rs"); +} + +#[test] +fn pass() { + let t = trybuild::TestCases::new(); + t.pass("tests/compile-pass/**/*.rs"); +} + +// Compiler messages may change between versions +// We don't want to have to track these too closely for `bitflags`, but +// having some message to check makes sure user-facing errors are sensical. +// +// The approach we use is to run the test on all compilers, but only check stderr +// output on beta (which is the next stable release). We do this by default ignoring +// any `.stderr` files in the `compile-fail` directory, and copying `.stderr.beta` files +// when we happen to be running on a beta compiler. +fn prepare_stderr_files(path: impl AsRef) -> io::Result<()> { + for entry in WalkDir::new(path) { + let entry = entry?; + + if entry.path().extension().and_then(OsStr::to_str) == Some("beta") { + let renamed = entry.path().with_extension(""); + + // Unconditionally remove a corresponding `.stderr` file for a `.stderr.beta` + // file if it exists. On `beta` compilers, we'll recreate it. On other compilers, + // we don't want to end up checking it anyways. + if renamed.exists() { + fs::remove_file(&renamed)?; + } + + rename_beta_stderr(entry.path(), renamed)?; + } + } + + Ok(()) +} + +#[rustversion::beta] +fn rename_beta_stderr(from: impl AsRef, to: impl AsRef) -> io::Result<()> { + fs::copy(from, to)?; + + Ok(()) +} + +#[rustversion::not(beta)] +fn rename_beta_stderr(_: impl AsRef, _: impl AsRef) -> io::Result<()> { + Ok(()) +} diff --git a/external/vendor/lazy_static/.cargo-checksum.json b/external/vendor/lazy_static/.cargo-checksum.json new file mode 100644 index 0000000000..c6db77f5e1 --- /dev/null +++ b/external/vendor/lazy_static/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"144648cf731d6d025b8054a57b05632e49ad5880cd2b66464660d98b079ce286","Cargo.toml":"7556429fefb497526c5abdaa2c36d8ce4eb86c23d72763eb396652b9eaffc210","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0621878e61f0d0fda054bcbe02df75192c28bde1ecc8289cbd86aeba2dd72720","README.md":"41e8c243b3e89d7ba8ef3cf1dbd1e0a8e5eb88741288ef9e122437d6d4f8895d","examples/mutex_map.rs":"dc011598c2a2e920846870848a8a4fd323449a69bf97b56083d760cee22e6406","src/core_lazy.rs":"dfb195f44a62b19a32542297edfd281bc40837e48905603dfec20d62b12711d0","src/inline_lazy.rs":"cd8a9babcc3af7d0d39f9874dc575a1da000f0d6048a66296f3ca197c2c00b46","src/lib.rs":"680e2ac624b3000ba17e9c3d49138332c15c5caf3a0143601b4fc6d9fbd5dd85","tests/compile_fail/incorrect_visibility_restriction.rs":"5324831d99653d5a287faf8ad1d4e64aaf2e3c99be8e462751d9f3a2ab08e9cd","tests/compile_fail/incorrect_visibility_restriction.stderr":"2ca900c1b7afcffd61f8bd422f8ce3180271166a193c721b7193a98d7ba774dd","tests/compile_fail/static_is_private.rs":"a7275028881d4f3d2aea0ac8a78d3b436ac6d12a7a6ec89172ee33102c4d8658","tests/compile_fail/static_is_private.stderr":"e0b228be7e1d2465b107642f9af32c4e794bd6dfce6781005d9b12b7bd9bbb6a","tests/compile_fail/static_is_sized.rs":"7706dcb499fedd2e97314799d7c82ad6b41b7e18034bc37755bd17889b4db4c3","tests/compile_fail/static_is_sized.stderr":"68052ad4311fa43f832c42486ca102f1175dc676158bdf95d26494b3ce498ee6","tests/no_std.rs":"6ff9f50ccacd30fb27e1c448b26b26343e5d7372f2c7718ca8bf130c302557e0","tests/test.rs":"a83dfefa1a3c291af9368cbfd3c252c45919004758496cdaa108b79c58d8ebc3","tests/ui.rs":"4897752b12c882b512aab0a153ad9ce727e6b4c72f74a6b379d8939c217f98b7"},"package":"bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe"} \ No newline at end of file diff --git a/external/vendor/lazy_static/Cargo.lock b/external/vendor/lazy_static/Cargo.lock new file mode 100644 index 0000000000..16ee6fbda9 --- /dev/null +++ b/external/vendor/lazy_static/Cargo.lock @@ -0,0 +1,293 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "doc-comment" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fea41bba32d969b513997752735605054bc0dfa92b4c56bf1189f2e174be7a10" + +[[package]] +name = "equivalent" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5443807d6dff69373d433ab9ef5378ad8df50ca6298caf15de6e52e24aaf54d5" + +[[package]] +name = "glob" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2fabcfbdc87f4758337ca535fb41a6d701b65693ce38287d856d1674551ec9b" + +[[package]] +name = "hashbrown" +version = "0.14.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5274423e17b7c9fc20b6e7e208532f9b19825d82dfd615708b70edd83df41f1" + +[[package]] +name = "indexmap" +version = "2.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "168fb715dda47215e360912c096649d23d58bf392ac62f73919e831745e40f26" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "itoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49f1f14873335454500d59611f1cf4a4b0f786f9ac11f4312a78e4cf2566695b" + +[[package]] +name = "lazy_static" +version = "1.5.0" +dependencies = [ + "doc-comment", + "spin", + "trybuild", +] + +[[package]] +name = "memchr" +version = "2.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78ca9ab1a0babb1e7d5695e3530886289c18cf2f87ec19a575a0abdce112e3a3" + +[[package]] +name = "proc-macro2" +version = "1.0.86" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e719e8df665df0d1c8fbfd238015744736151d4445ec0836b8e628aae103b77" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "quote" +version = "1.0.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fa76aaf39101c457836aec0ce2316dbdc3ab723cdda1c6bd4e6ad4208acaca7" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "ryu" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3cb5ba0dc43242ce17de99c180e96db90b235b8a9fdc9543c96d2209116bd9f" + +[[package]] +name = "serde" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7253ab4de971e72fb7be983802300c30b5a7f0c2e56fab8abfc6a214307c0094" +dependencies = [ + "serde_derive", +] + +[[package]] +name = "serde_derive" +version = "1.0.203" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500cbc0ebeb6f46627f50f3f5811ccf6bf00643be300b4c3eabc0ef55dc5b5ba" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "serde_json" +version = "1.0.117" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "455182ea6142b14f93f4bc5320a2b31c1f266b66a4a5c858b013302a5d8cbfc3" +dependencies = [ + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "serde_spanned" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "79e674e01f999af37c49f70a6ede167a8a60b2503e56c5599532a65baa5969a0" +dependencies = [ + "serde", +] + +[[package]] +name = "spin" +version = "0.9.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" + +[[package]] +name = "syn" +version = "2.0.67" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff8655ed1d86f3af4ee3fd3263786bc14245ad17c4c7e85ba7187fb3ae028c90" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "termcolor" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "06794f8f6c5c898b3275aebefa6b8a1cb24cd2c6c79397ab15774837a0bc5755" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "toml" +version = "0.8.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f49eb2ab21d2f26bd6db7bf383edc527a7ebaee412d17af4d40fdccd442f335" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime", + "toml_edit", +] + +[[package]] +name = "toml_datetime" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4badfd56924ae69bcc9039335b2e017639ce3f9b001c393c1b2d1ef846ce2cbf" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_edit" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f21c7aaf97f1bd9ca9d4f9e73b0a6c74bd5afef56f2bc931943a6e1c37e04e38" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime", + "winnow", +] + +[[package]] +name = "trybuild" +version = "1.0.96" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33a5f13f11071020bb12de7a16b925d2d58636175c20c11dc5f96cb64bb6c9b3" +dependencies = [ + "glob", + "serde", + "serde_derive", + "serde_json", + "termcolor", + "toml", +] + +[[package]] +name = "unicode-ident" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3354b9ac3fae1ff6755cb6db53683adb661634f67557942dea4facebec0fee4b" + +[[package]] +name = "winapi-util" +version = "0.1.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4d4cc384e1e73b93bafa6fb4f1df8c41695c8a91cf9c4c64358067d15a7b6c6b" +dependencies = [ + "windows-sys", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets", +] + +[[package]] +name = "windows-targets" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f0713a46559409d202e70e28227288446bf7841d3211583a4b53e3f6d96e7eb" +dependencies = [ + "windows_aarch64_gnullvm", + "windows_aarch64_msvc", + "windows_i686_gnu", + "windows_i686_gnullvm", + "windows_i686_msvc", + "windows_x86_64_gnu", + "windows_x86_64_gnullvm", + "windows_x86_64_msvc", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7088eed71e8b8dda258ecc8bac5fb1153c5cffaf2578fc8ff5d61e23578d3263" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9985fd1504e250c615ca5f281c3f7a6da76213ebd5ccc9561496568a2752afb6" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88ba073cf16d5372720ec942a8ccbf61626074c6d4dd2e745299726ce8b89670" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87f4261229030a858f36b459e748ae97545d6f1ec60e5e0d6a3d32e0dc232ee9" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db3c2bf3d13d5b658be73463284eaf12830ac9a26a90c717b7f771dfe97487bf" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e4246f76bdeff09eb48875a0fd3e2af6aada79d409d33011886d3e1581517d9" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "852298e482cd67c356ddd9570386e2862b5673c85bd5f88df9ab6802b334c596" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bec47e5bfd1bff0eeaf6d8b485cc1074891a197ab4225d504cb7a1ab88b02bf0" + +[[package]] +name = "winnow" +version = "0.6.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59b5e5f6c299a3c7890b876a2a587f3115162487e704907d9b6cd29473052ba1" +dependencies = [ + "memchr", +] diff --git a/external/vendor/lazy_static/Cargo.toml b/external/vendor/lazy_static/Cargo.toml new file mode 100644 index 0000000000..12c147a3c0 --- /dev/null +++ b/external/vendor/lazy_static/Cargo.toml @@ -0,0 +1,46 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +name = "lazy_static" +version = "1.5.0" +authors = ["Marvin Löbel "] +exclude = [".github"] +description = "A macro for declaring lazily evaluated statics in Rust." +documentation = "https://docs.rs/lazy_static" +readme = "README.md" +keywords = [ + "macro", + "lazy", + "static", +] +categories = [ + "no-std", + "rust-patterns", + "memory-management", +] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang-nursery/lazy-static.rs" + +[dependencies.spin] +version = "0.9.8" +features = ["once"] +optional = true +default-features = false + +[dev-dependencies.doc-comment] +version = "0.3.1" + +[dev-dependencies.trybuild] +version = "1" + +[features] +spin_no_std = ["spin"] diff --git a/external/vendor/lazy_static/LICENSE-APACHE b/external/vendor/lazy_static/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/external/vendor/lazy_static/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/external/vendor/lazy_static/LICENSE-MIT b/external/vendor/lazy_static/LICENSE-MIT new file mode 100644 index 0000000000..25597d5838 --- /dev/null +++ b/external/vendor/lazy_static/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2010 The Rust Project Developers + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/external/vendor/lazy_static/README.md b/external/vendor/lazy_static/README.md new file mode 100644 index 0000000000..93edbe8a6b --- /dev/null +++ b/external/vendor/lazy_static/README.md @@ -0,0 +1,105 @@ +lazy-static.rs +============== + +A macro for declaring lazily evaluated statics in Rust. + +Using this macro, it is possible to have `static`s that require code to be +executed at runtime in order to be initialized. +This includes anything requiring heap allocations, like vectors or hash maps, +as well as anything that requires non-const function calls to be computed. + +[![Rust](https://github.com/rust-lang-nursery/lazy-static.rs/actions/workflows/rust.yml/badge.svg)](https://github.com/rust-lang-nursery/lazy-static.rs/actions/workflows/rust.yml) +[![Latest version](https://img.shields.io/crates/v/lazy_static.svg)](https://crates.io/crates/lazy_static) +[![Documentation](https://docs.rs/lazy_static/badge.svg)](https://docs.rs/lazy_static) +[![License](https://img.shields.io/crates/l/lazy_static.svg)](https://github.com/rust-lang-nursery/lazy-static.rs#license) + +## Minimum supported `rustc` + +`1.40.0+` + +This version is explicitly tested in CI and may only be bumped in new minor versions. Any changes to the supported minimum version will be called out in the release notes. + + +# Getting Started + +[lazy-static.rs is available on crates.io](https://crates.io/crates/lazy_static). +It is recommended to look there for the newest released version, as well as links to the newest builds of the docs. + +At the point of the last update of this README, the latest published version could be used like this: + +Add the following dependency to your Cargo manifest... + +```toml +[dependencies] +lazy_static = "1.5.0" +``` + +...and see the [docs](https://docs.rs/lazy_static) for how to use it. + +# Example + +```rust +use lazy_static::lazy_static; +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + m + }; +} + +fn main() { + // First access to `HASHMAP` initializes it + println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); + + // Any further access to `HASHMAP` just returns the computed value + println!("The entry for `1` is \"{}\".", HASHMAP.get(&1).unwrap()); +} +``` + +# Standard library + +It is now possible to easily replicate this crate's functionality in Rust's standard library with [`std::sync::OnceLock`](https://doc.rust-lang.org/std/sync/struct.OnceLock.html). The example above could be also be written as: + +```rust +use std::collections::HashMap; +use std::sync::OnceLock; + +fn hashmap() -> &'static HashMap { + static HASHMAP: OnceLock> = OnceLock::new(); + HASHMAP.get_or_init(|| { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + m + }) +} + +fn main() { + // First access to `HASHMAP` initializes it + println!("The entry for `0` is \"{}\".", hashmap().get(&0).unwrap()); + + // Any further access to `HASHMAP` just returns the computed value + println!("The entry for `1` is \"{}\".", hashmap().get(&1).unwrap()); +} +``` + +## License + +Licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or https://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/external/vendor/lazy_static/examples/mutex_map.rs b/external/vendor/lazy_static/examples/mutex_map.rs new file mode 100644 index 0000000000..92b07ab9d4 --- /dev/null +++ b/external/vendor/lazy_static/examples/mutex_map.rs @@ -0,0 +1,23 @@ +//! This example shows how to wrap a data structure in a mutex to achieve safe mutability. +extern crate lazy_static; +use lazy_static::lazy_static; +use std::collections::HashMap; +use std::sync::Mutex; + +lazy_static! { + static ref MUTEX_MAP: Mutex> = { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + Mutex::new(m) + }; +} + +fn main() { + MUTEX_MAP.lock().unwrap().insert(0, "boo"); + println!( + "The entry for `0` is \"{}\".", + MUTEX_MAP.lock().unwrap().get(&0).unwrap() + ); +} diff --git a/external/vendor/lazy_static/src/core_lazy.rs b/external/vendor/lazy_static/src/core_lazy.rs new file mode 100644 index 0000000000..e2f16bcde8 --- /dev/null +++ b/external/vendor/lazy_static/src/core_lazy.rs @@ -0,0 +1,32 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate spin; + +use self::spin::Once; + +pub struct Lazy(Once); + +impl Lazy { + pub const INIT: Self = Lazy(Once::INIT); + + #[inline(always)] + pub fn get(&'static self, builder: F) -> &T + where + F: FnOnce() -> T, + { + self.0.call_once(builder) + } +} + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT; + }; +} diff --git a/external/vendor/lazy_static/src/inline_lazy.rs b/external/vendor/lazy_static/src/inline_lazy.rs new file mode 100644 index 0000000000..36d52d347b --- /dev/null +++ b/external/vendor/lazy_static/src/inline_lazy.rs @@ -0,0 +1,48 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate core; +extern crate std; + +use self::std::cell::Cell; +use self::std::mem::MaybeUninit; +use self::std::prelude::v1::*; +use self::std::sync::Once; +#[allow(deprecated)] +pub use self::std::sync::ONCE_INIT; + +#[allow(dead_code)] // Used in macros +pub struct Lazy(Cell>, Once); + +impl Lazy { + #[allow(deprecated)] + pub const INIT: Self = Lazy(Cell::new(MaybeUninit::uninit()), ONCE_INIT); + + #[inline(always)] + pub fn get(&'static self, f: F) -> &T + where + F: FnOnce() -> T, + { + self.1.call_once(|| { + self.0.set(MaybeUninit::new(f())); + }); + + // `self.0` is guaranteed to be initialized by this point + // The `Once` will catch and propagate panics + unsafe { &*(*self.0.as_ptr()).as_ptr() } + } +} + +unsafe impl Sync for Lazy {} + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT; + }; +} diff --git a/external/vendor/lazy_static/src/lib.rs b/external/vendor/lazy_static/src/lib.rs new file mode 100644 index 0000000000..5003fa2c99 --- /dev/null +++ b/external/vendor/lazy_static/src/lib.rs @@ -0,0 +1,208 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, or the MIT license , at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +/*! +A macro for declaring lazily evaluated statics. + +Using this macro, it is possible to have `static`s that require code to be +executed at runtime in order to be initialized. +This includes anything requiring heap allocations, like vectors or hash maps, +as well as anything that requires function calls to be computed. + +# Syntax + +```ignore +lazy_static! { + [pub] static ref NAME_1: TYPE_1 = EXPR_1; + [pub] static ref NAME_2: TYPE_2 = EXPR_2; + ... + [pub] static ref NAME_N: TYPE_N = EXPR_N; +} +``` + +Attributes (including doc comments) are supported as well: + +```rust +use lazy_static::lazy_static; + +# fn main() { +lazy_static! { + /// This is an example for using doc comment attributes + static ref EXAMPLE: u8 = 42; +} +# } +``` + +# Semantics + +For a given `static ref NAME: TYPE = EXPR;`, the macro generates a unique type that +implements `Deref` and stores it in a static with name `NAME`. (Attributes end up +attaching to this type.) + +On first deref, `EXPR` gets evaluated and stored internally, such that all further derefs +can return a reference to the same object. Note that this can lead to deadlocks +if you have multiple lazy statics that depend on each other in their initialization. + +Apart from the lazy initialization, the resulting "static ref" variables +have generally the same properties as regular "static" variables: + +- Any type in them needs to fulfill the `Sync` trait. +- If the type has a destructor, then it will not run when the process exits. + +# Example + +Using the macro: + +```rust +use lazy_static::lazy_static; +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "foo"); + m.insert(1, "bar"); + m.insert(2, "baz"); + m + }; + static ref COUNT: usize = HASHMAP.len(); + static ref NUMBER: u32 = times_two(21); +} + +fn times_two(n: u32) -> u32 { n * 2 } + +fn main() { + println!("The map has {} entries.", *COUNT); + println!("The entry for `0` is \"{}\".", HASHMAP.get(&0).unwrap()); + println!("A expensive calculation on a static results in: {}.", *NUMBER); +} +``` + +# Implementation details + +The `Deref` implementation uses a hidden static variable that is guarded by an atomic check on each access. + +# Cargo features + +This crate provides one cargo feature: + +- `spin_no_std`: This allows using this crate in a no-std environment, by depending on the standalone `spin` crate. + +*/ + +#![doc(html_root_url = "https://docs.rs/lazy_static/1.5.0")] +#![no_std] + +#[cfg(doctest)] +#[macro_use] +extern crate doc_comment; + +#[cfg(doctest)] +doctest!("../README.md"); + +#[cfg_attr(feature = "spin_no_std", path = "core_lazy.rs")] +#[cfg_attr(not(feature = "spin_no_std"), path = "inline_lazy.rs")] +#[doc(hidden)] +pub mod lazy; + +#[doc(hidden)] +pub use core::ops::Deref as __Deref; + +#[macro_export(local_inner_macros)] +#[doc(hidden)] +macro_rules! __lazy_static_internal { + // optional visibility restrictions are wrapped in `()` to allow for + // explicitly passing otherwise implicit information about private items + ($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!(@MAKE TY, $(#[$attr])*, ($($vis)*), $N); + __lazy_static_internal!(@TAIL, $N : $T = $e); + lazy_static!($($t)*); + }; + (@TAIL, $N:ident : $T:ty = $e:expr) => { + impl $crate::__Deref for $N { + type Target = $T; + fn deref(&self) -> &$T { + #[inline(always)] + fn __static_ref_initialize() -> $T { $e } + + #[inline(always)] + fn __stability() -> &'static $T { + __lazy_static_create!(LAZY, $T); + LAZY.get(__static_ref_initialize) + } + __stability() + } + } + impl $crate::LazyStatic for $N { + fn initialize(lazy: &Self) { + let _ = &**lazy; + } + } + }; + // `vis` is wrapped in `()` to prevent parsing ambiguity + (@MAKE TY, $(#[$attr:meta])*, ($($vis:tt)*), $N:ident) => { + #[allow(missing_copy_implementations)] + #[allow(non_camel_case_types)] + #[allow(dead_code)] + $(#[$attr])* + $($vis)* struct $N {__private_field: ()} + #[doc(hidden)] + #[allow(non_upper_case_globals)] + $($vis)* static $N: $N = $N {__private_field: ()}; + }; + () => () +} + +#[macro_export(local_inner_macros)] +macro_rules! lazy_static { + ($(#[$attr:meta])* static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + // use `()` to explicitly forward the information about private items + __lazy_static_internal!($(#[$attr])* () static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!($(#[$attr])* (pub) static ref $N : $T = $e; $($t)*); + }; + ($(#[$attr:meta])* pub ($($vis:tt)+) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => { + __lazy_static_internal!($(#[$attr])* (pub ($($vis)+)) static ref $N : $T = $e; $($t)*); + }; + () => () +} + +/// Support trait for enabling a few common operation on lazy static values. +/// +/// This is implemented by each defined lazy static, and +/// used by the free functions in this crate. +pub trait LazyStatic { + #[doc(hidden)] + fn initialize(lazy: &Self); +} + +/// Takes a shared reference to a lazy static and initializes +/// it if it has not been already. +/// +/// This can be used to control the initialization point of a lazy static. +/// +/// Example: +/// +/// ```rust +/// use lazy_static::lazy_static; +/// +/// lazy_static! { +/// static ref BUFFER: Vec = (0..255).collect(); +/// } +/// +/// fn main() { +/// lazy_static::initialize(&BUFFER); +/// +/// // ... +/// work_with_initialized_data(&BUFFER); +/// } +/// # fn work_with_initialized_data(_: &[u8]) {} +/// ``` +pub fn initialize(lazy: &T) { + LazyStatic::initialize(lazy); +} diff --git a/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.rs b/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.rs new file mode 100644 index 0000000000..5d44f02dcb --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.rs @@ -0,0 +1,8 @@ +#[macro_use] +extern crate lazy_static; + +lazy_static! { + pub(nonsense) static ref WRONG: () = (); +} + +fn main() { } diff --git a/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.stderr b/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.stderr new file mode 100644 index 0000000000..045ce14b8f --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/incorrect_visibility_restriction.stderr @@ -0,0 +1,10 @@ +error[E0704]: incorrect visibility restriction + --> tests/compile_fail/incorrect_visibility_restriction.rs:5:9 + | +5 | pub(nonsense) static ref WRONG: () = (); + | ^^^^^^^^ help: make this visible only to module `nonsense` with `in`: `in nonsense` + | + = help: some possible visibility restrictions are: + `pub(crate)`: visible only on the current crate + `pub(super)`: visible only in the current module's parent + `pub(in path::to::module)`: visible only on the specified path diff --git a/external/vendor/lazy_static/tests/compile_fail/static_is_private.rs b/external/vendor/lazy_static/tests/compile_fail/static_is_private.rs new file mode 100644 index 0000000000..4486f013d3 --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/static_is_private.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate lazy_static; + +mod outer { + pub mod inner { + lazy_static! { + pub(in outer) static ref FOO: () = (); + } + } +} + +fn main() { + assert_eq!(*outer::inner::FOO, ()); +} diff --git a/external/vendor/lazy_static/tests/compile_fail/static_is_private.stderr b/external/vendor/lazy_static/tests/compile_fail/static_is_private.stderr new file mode 100644 index 0000000000..38007d475e --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/static_is_private.stderr @@ -0,0 +1,14 @@ +error[E0603]: static `FOO` is private + --> tests/compile_fail/static_is_private.rs:13:31 + | +13 | assert_eq!(*outer::inner::FOO, ()); + | ^^^ private static + | +note: the static `FOO` is defined here + --> tests/compile_fail/static_is_private.rs:6:9 + | +6 | / lazy_static! { +7 | | pub(in outer) static ref FOO: () = (); +8 | | } + | |_________^ + = note: this error originates in the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/lazy_static/tests/compile_fail/static_is_sized.rs b/external/vendor/lazy_static/tests/compile_fail/static_is_sized.rs new file mode 100644 index 0000000000..69a9a06228 --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/static_is_sized.rs @@ -0,0 +1,9 @@ +#[macro_use] +extern crate lazy_static; + +lazy_static! { + pub static ref FOO: str = panic!(); +} + + +fn main() { } diff --git a/external/vendor/lazy_static/tests/compile_fail/static_is_sized.stderr b/external/vendor/lazy_static/tests/compile_fail/static_is_sized.stderr new file mode 100644 index 0000000000..49407ab6a6 --- /dev/null +++ b/external/vendor/lazy_static/tests/compile_fail/static_is_sized.stderr @@ -0,0 +1,64 @@ +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/static_is_sized.rs:4:1 + | +4 | / lazy_static! { +5 | | pub static ref FOO: str = panic!(); +6 | | } + | |_^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Lazy` + --> src/inline_lazy.rs + | + | pub struct Lazy(Cell>, Once); + | ^ required by the implicit `Sized` requirement on this type parameter in `Lazy` + = note: this error originates in the macro `__lazy_static_create` which comes from the expansion of the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/static_is_sized.rs:4:1 + | +4 | / lazy_static! { +5 | | pub static ref FOO: str = panic!(); +6 | | } + | |_^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` +note: required by an implicit `Sized` bound in `Lazy` + --> src/inline_lazy.rs + | + | pub struct Lazy(Cell>, Once); + | ^ required by the implicit `Sized` requirement on this type parameter in `Lazy` + = note: this error originates in the macro `__lazy_static_create` which comes from the expansion of the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/static_is_sized.rs:5:25 + | +5 | pub static ref FOO: str = panic!(); + | ^^^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: the return type of a function must have a statically known size + +error[E0599]: the method `get` exists for struct `Lazy`, but its trait bounds were not satisfied + --> tests/compile_fail/static_is_sized.rs:4:1 + | +4 | / lazy_static! { +5 | | pub static ref FOO: str = panic!(); +6 | | } + | |_^ method cannot be called on `Lazy` due to unsatisfied trait bounds + | + = note: the following trait bounds were not satisfied: + `str: Sized` + = note: this error originates in the macro `__lazy_static_internal` which comes from the expansion of the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info) + +error[E0277]: the size for values of type `str` cannot be known at compilation time + --> tests/compile_fail/static_is_sized.rs:4:1 + | +4 | / lazy_static! { +5 | | pub static ref FOO: str = panic!(); +6 | | } + | |_^ doesn't have a size known at compile-time + | + = help: the trait `Sized` is not implemented for `str` + = note: the return type of a function must have a statically known size + = note: this error originates in the macro `__lazy_static_internal` which comes from the expansion of the macro `lazy_static` (in Nightly builds, run with -Z macro-backtrace for more info) diff --git a/external/vendor/lazy_static/tests/no_std.rs b/external/vendor/lazy_static/tests/no_std.rs new file mode 100644 index 0000000000..e3324949a1 --- /dev/null +++ b/external/vendor/lazy_static/tests/no_std.rs @@ -0,0 +1,19 @@ +#![cfg(feature = "spin_no_std")] +#![no_std] + +#[macro_use] +extern crate lazy_static; + +lazy_static! { + /// Documentation! + pub static ref NUMBER: u32 = times_two(3); +} + +fn times_two(n: u32) -> u32 { + n * 2 +} + +#[test] +fn test_basic() { + assert_eq!(*NUMBER, 6); +} diff --git a/external/vendor/lazy_static/tests/test.rs b/external/vendor/lazy_static/tests/test.rs new file mode 100644 index 0000000000..eb659d426d --- /dev/null +++ b/external/vendor/lazy_static/tests/test.rs @@ -0,0 +1,185 @@ +#![deny(warnings)] + +#[macro_use] +extern crate lazy_static; +use std::collections::HashMap; + +lazy_static! { + /// Documentation! + pub static ref NUMBER: u32 = times_two(3); + + static ref ARRAY_BOXES: [Box; 3] = [Box::new(1), Box::new(2), Box::new(3)]; + + /// More documentation! + #[allow(unused_variables)] + #[derive(Copy, Clone, Debug)] + pub static ref STRING: String = "hello".to_string(); + + static ref HASHMAP: HashMap = { + let mut m = HashMap::new(); + m.insert(0, "abc"); + m.insert(1, "def"); + m.insert(2, "ghi"); + m + }; + + // This should not compile if the unsafe is removed. + static ref UNSAFE: u32 = unsafe { + std::mem::transmute::(-1) + }; +} + +lazy_static! { + static ref S1: &'static str = "a"; + static ref S2: &'static str = "b"; +} +lazy_static! { + static ref S3: String = [*S1, *S2].join(""); +} + +lazy_static! { + #[allow(non_upper_case_globals)] + pub static ref string: String = "hello".to_string(); +} + +#[test] +fn s3() { + assert_eq!(&*S3, "ab"); +} + +fn times_two(n: u32) -> u32 { + n * 2 +} + +#[test] +fn test_basic() { + assert_eq!(&**STRING, "hello"); + assert_eq!(*NUMBER, 6); + assert!(HASHMAP.get(&1).is_some()); + assert!(HASHMAP.get(&3).is_none()); + assert_eq!(&*ARRAY_BOXES, &[Box::new(1), Box::new(2), Box::new(3)]); + assert_eq!(*UNSAFE, std::u32::MAX); +} + +#[test] +fn test_repeat() { + assert_eq!(*NUMBER, 6); + assert_eq!(*NUMBER, 6); + assert_eq!(*NUMBER, 6); +} + +#[test] +fn test_meta() { + // this would not compile if STRING were not marked #[derive(Copy, Clone)] + let copy_of_string = STRING; + // just to make sure it was copied + assert!(&STRING as *const _ != ©_of_string as *const _); + + // this would not compile if STRING were not marked #[derive(Debug)] + assert_eq!( + format!("{:?}", STRING), + "STRING { __private_field: () }".to_string() + ); +} + +mod visibility { + lazy_static! { + pub static ref FOO: Box = Box::new(0); + static ref BAR: Box = Box::new(98); + } + + pub mod inner { + lazy_static! { + pub(in visibility) static ref BAZ: Box = Box::new(42); + pub(crate) static ref BAG: Box = Box::new(37); + } + } + + #[test] + fn sub_test() { + assert_eq!(**FOO, 0); + assert_eq!(**BAR, 98); + assert_eq!(**inner::BAZ, 42); + assert_eq!(**inner::BAG, 37); + } +} + +#[test] +fn test_visibility() { + assert_eq!(*visibility::FOO, Box::new(0)); + assert_eq!(*visibility::inner::BAG, Box::new(37)); +} + +// This should not cause a warning about a missing Copy implementation +lazy_static! { + pub static ref VAR: i32 = 0; +} + +#[derive(Copy, Clone, Debug, PartialEq)] +struct X; +struct Once(X); +const ONCE_INIT: Once = Once(X); +static DATA: X = X; +static ONCE: X = X; +fn require_sync() -> X { + X +} +fn transmute() -> X { + X +} +fn __static_ref_initialize() -> X { + X +} +fn test(_: Vec) -> X { + X +} + +// All these names should not be shadowed +lazy_static! { + static ref ITEM_NAME_TEST: X = { + test(vec![X, Once(X).0, ONCE_INIT.0, DATA, ONCE, + require_sync(), transmute(), + // Except this, which will sadly be shadowed by internals: + // __static_ref_initialize() + ]) + }; +} + +#[test] +fn item_name_shadowing() { + assert_eq!(*ITEM_NAME_TEST, X); +} + +use std::sync::atomic::AtomicBool; +use std::sync::atomic::Ordering::SeqCst; +#[allow(deprecated)] +use std::sync::atomic::ATOMIC_BOOL_INIT; + +#[allow(deprecated)] +static PRE_INIT_FLAG: AtomicBool = ATOMIC_BOOL_INIT; + +lazy_static! { + static ref PRE_INIT: () = { + PRE_INIT_FLAG.store(true, SeqCst); + () + }; +} + +#[test] +fn pre_init() { + assert_eq!(PRE_INIT_FLAG.load(SeqCst), false); + lazy_static::initialize(&PRE_INIT); + assert_eq!(PRE_INIT_FLAG.load(SeqCst), true); +} + +lazy_static! { + static ref LIFETIME_NAME: for<'a> fn(&'a u8) = { + fn f(_: &u8) {} + f + }; +} + +#[test] +fn lifetime_name() { + let _ = LIFETIME_NAME; +} diff --git a/external/vendor/lazy_static/tests/ui.rs b/external/vendor/lazy_static/tests/ui.rs new file mode 100644 index 0000000000..af007cd274 --- /dev/null +++ b/external/vendor/lazy_static/tests/ui.rs @@ -0,0 +1,6 @@ +#[test] +#[cfg(not(miri))] +fn ui() { + let t = trybuild::TestCases::new(); + t.compile_fail("tests/compile_fail/*.rs"); +} diff --git a/external/vendor/pkg-config/.cargo-checksum.json b/external/vendor/pkg-config/.cargo-checksum.json new file mode 100644 index 0000000000..286e0c266b --- /dev/null +++ b/external/vendor/pkg-config/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"CHANGELOG.md":"f613cde47a4a2b477e30660e80c0f91ddd99564ca60e7ccacc05db8e47558ac3","Cargo.lock":"7072b11a157cb5696facb19f0816eb5cfe00b804356da9dfb3eb1c297e31594b","Cargo.lock.msrv":"6401e6e4a20302502ab12eff9ac75c8aa66e96ed5ca32824d2a8d92d16f2e91b","Cargo.toml":"19b7808a36b6f42c812ba154cdd7b48347511158a7f69f52bcf2c4d073ee4a37","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"378f5840b258e2779c39418f3f2d7b2ba96f1c7917dd6be0713f88305dbda397","README.md":"184dd47cdbb3168bdddccaa594f1e56604cb07034b06c1129ac91d41800902da","src/lib.rs":"afee92eaacd83e2bb6426d45a83e01218b3493ccf0dc8b5403413e37ad86b3ee","tests/escape.pc":"00caa4136799dbe5bd504239ba90d1156c12def365c8d761da319fe8a83b398e","tests/foo.pc":"4a1c442c5d1c10761ea1644f8fd58f93cc5a706391bc67b04c243bbd35d70d79","tests/framework.pc":"304fdb6cea92973650e410ab1f70ce1ebeb7718af3f139e806efbf182acd565c","tests/rpath.pc":"424a844e844edfef02692492def9864833391f581338962946646989a69c1180","tests/test.rs":"aa60972a93f57fbc17620739996a94877de523a57e1de7541ee3541539ae2bb9"},"package":"7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c"} \ No newline at end of file diff --git a/external/vendor/pkg-config/CHANGELOG.md b/external/vendor/pkg-config/CHANGELOG.md new file mode 100644 index 0000000000..3484738f7c --- /dev/null +++ b/external/vendor/pkg-config/CHANGELOG.md @@ -0,0 +1,218 @@ +# Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/) +and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html). + +## [0.3.32] - 2025-03-03 + +### Fixed + +- Suggest installing pkgconf via homebrew on macOS instead of pkg-config (#173) + +- Quote failed pkg-config command correctly in error messages to allow for + directly copy&pasting it into a shell (#175) + +## [0.3.31] - 2024-09-23 + +### Fixed + +- Remove double `cargo:` prefix from linker line (#168). + +## [0.3.30] - 2024-02-14 + +### Changed + +- Update documentation for cross-compilation (#161). + +- Update GitHub Action CI (#160). + +## [0.3.29] - 2024-01-17 + +### Fixed + +- Detection and usage of Windows static libraries (#154). + +- Passing `-Wl,-u` to the linker if specified in the pkg-config file (#154). + +## [0.3.28] - 2023-12-20 + +### Fixed + +- Pass -l:libfoo.a to linker directly (#149). + +### Changed + +- Improve error message when library not found (#158). + +## [0.3.27] - 2023-05-03 + +### Added + +- Support falling back to `pkgconf` if `pkg-config` is not available (#145). + +### Changed + +- Simplify running `pkg-config` (#144). + +- Document MSRV in `Cargo.toml` via `rust-version`. + +- Fix a couple of minor clippy warnings (#147). + +## [0.3.26] - 2022-10-26 + +### Added + +- Support for handling full paths to libraries in addition to normal `-l` + linker flags (#134). + +## [0.3.25] - 2022-03-31 + +### Added + +- Support for parsing `-Wl` linker arguments from the `Libs` lines and + passing them to the linker as well as making them available via + `Library::ld_args` (#131). + +### Changed + +- Use SPDX license format and remove obsolete badge info (#129). + +## [0.3.24] - 2021-12-11 + +### Fixed + +- Re-add `target_supported()`, which was accidentally removed in 0.3.15 (#128). + +## [0.3.23] - 2021-12-06 + +### Changed + +- Improve error messages when a `pkg-config` package can't be found (#127). + +## [0.3.22] - 2021-10-24 + +### Fixed + +- `pkg-config` compiles again with Rust 1.30 or newer. 0.3.21 accidentally + made use of API only available since 1.40 (#124, #125). + +### Changed + +- Switched from Travis to GitHub Actions for the CI. Travis is dysfunctional + since quite some time (#126). + +## [0.3.21] - 2021-10-22 + +### Fixed + +- Tests succeed again on macOS (#122). + +### Changed + +- Improve error message in case of missing pkg-config and provide instructions + how it can be installed (#121). + +## [0.3.20] - 2021-09-25 + +### Fixed + +- Use target-specific pkg-config consistently everywhere (#121, #118). + +## [0.3.19] - 2020-10-13 + +### Added + +- Add `README.md` to be displayed on crates.io (#111). + +- Support for `-isystem`, `-iquote` and `-idirafter` include flags (#115). + +### Changed + +- Improve documentation for cross-compilation (#113). + +- Allow overriding system root via the `PKG_CONFIG_SYSROOT_DIR` or `SYSROOT` + environment variable (#82). + +## [0.3.18] - 2020-07-11 + +### Fixed + +- Use `env::var_os()` almost everywhere to handle non-UTF8 paths in + environment variables, and also improve error handling around environment + variable handling (#106). + +### Changed + +- Default the `env_metadata` build parameter to `true` instead of `false`. + Whenever a pkg-config related environment variable changes it would make + sense to rebuild crates that use pkg-config, or otherwise changes might not + be picked up. As such the previous default didn't make much sense (#105). + +## [0.3.17] - 2019-11-02 + +### Fixed + +- Fix support for multiple version number constraints (#95) + +## [0.3.16] - 2019-09-09 + +### Changed +- Stop using deprecated functions and require Rust 1.30 (#84) + +### Fixed +- Fix repository URL in README.md +- Fix various clippy warnings + +### Added +- Run `cargo fmt` as part of the CI (#89) +- Derive `Clone` for `Library` and `Debug` for `Config (#91) +- Add support for `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` and enable by default (#93) + +## [0.3.15] - 2019-07-25 + +### Changed +- Changes minimum documented rust version to 1.28 (#76) + +### Fixed +- Fix Travis CI badge url (#78) +- Fix project name in README.md (#81) + +### Added +- Support specifying range of versions (#75) +- Allow cross-compilation if pkg-config is customized (#44, #86) + +## [0.3.14] - 2018-08-28 + +### Fixed +- Don't append .lib suffix on MSVC builds (#72) + +## [0.3.13] - 2018-08-06 + +### Fixed +- Fix MSVC support to actually work and consider library paths too (#71) + +## [0.3.12] - 2018-06-18 + +### Added +- Support for MSVC (#70) +- Document and test Rust 1.13 as minimally supported version (#66) + +## [0.3.11] - 2018-04-24 + +### Fixed +- Re-added AsciiExt import (#65) + +## [0.3.10] - 2018-04-23 + +### Added +- Allow static linking of /usr/ on macOS (#42) +- Add support for parsing `-Wl,` style framework flags (#48) +- Parse defines in `pkg-config` output (#49) +- Rerun on `PKG_CONFIG_PATH` changes (#50) +- Introduce target-scoped variables (#58) +- Respect pkg-config escaping rules used with --cflags and --libs (#61) + +### Changed +- Use `?` instead of `try!()` in the codebase (#63) diff --git a/external/vendor/pkg-config/Cargo.lock b/external/vendor/pkg-config/Cargo.lock new file mode 100644 index 0000000000..5693cccfeb --- /dev/null +++ b/external/vendor/pkg-config/Cargo.lock @@ -0,0 +1,16 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "pkg-config" +version = "0.3.32" +dependencies = [ + "lazy_static 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum lazy_static 1.5.0 (registry+https://github.com/rust-lang/crates.io-index)" = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" diff --git a/external/vendor/pkg-config/Cargo.lock.msrv b/external/vendor/pkg-config/Cargo.lock.msrv new file mode 100644 index 0000000000..6b5f4c2ddb --- /dev/null +++ b/external/vendor/pkg-config/Cargo.lock.msrv @@ -0,0 +1,14 @@ +[[package]] +name = "lazy_static" +version = "1.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "pkg-config" +version = "0.3.32" +dependencies = [ + "lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[metadata] +"checksum lazy_static 1.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "e2abad23fbc42b3700f2f279844dc832adb2b2eb069b2df918f455c4e18cc646" diff --git a/external/vendor/pkg-config/Cargo.toml b/external/vendor/pkg-config/Cargo.toml new file mode 100644 index 0000000000..4429ce78b5 --- /dev/null +++ b/external/vendor/pkg-config/Cargo.toml @@ -0,0 +1,43 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +rust-version = "1.31" +name = "pkg-config" +version = "0.3.32" +authors = ["Alex Crichton "] +build = false +autolib = false +autobins = false +autoexamples = false +autotests = false +autobenches = false +description = """ +A library to run the pkg-config system tool at build time in order to be used in +Cargo build scripts. +""" +documentation = "https://docs.rs/pkg-config" +readme = "README.md" +keywords = ["build-dependencies"] +license = "MIT OR Apache-2.0" +repository = "https://github.com/rust-lang/pkg-config-rs" + +[lib] +name = "pkg_config" +path = "src/lib.rs" + +[[test]] +name = "test" +path = "tests/test.rs" + +[dev-dependencies.lazy_static] +version = "1" diff --git a/external/vendor/pkg-config/LICENSE-APACHE b/external/vendor/pkg-config/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/external/vendor/pkg-config/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + +TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + +1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + +2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + +3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + +4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + +5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + +6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + +7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + +8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + +9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + +END OF TERMS AND CONDITIONS + +APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + +Copyright [yyyy] [name of copyright owner] + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/external/vendor/pkg-config/LICENSE-MIT b/external/vendor/pkg-config/LICENSE-MIT new file mode 100644 index 0000000000..39e0ed6602 --- /dev/null +++ b/external/vendor/pkg-config/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2014 Alex Crichton + +Permission is hereby granted, free of charge, to any +person obtaining a copy of this software and associated +documentation files (the "Software"), to deal in the +Software without restriction, including without +limitation the rights to use, copy, modify, merge, +publish, distribute, sublicense, and/or sell copies of +the Software, and to permit persons to whom the Software +is furnished to do so, subject to the following +conditions: + +The above copyright notice and this permission notice +shall be included in all copies or substantial portions +of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF +ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED +TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A +PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT +SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION +OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR +IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER +DEALINGS IN THE SOFTWARE. diff --git a/external/vendor/pkg-config/README.md b/external/vendor/pkg-config/README.md new file mode 100644 index 0000000000..fea82139f6 --- /dev/null +++ b/external/vendor/pkg-config/README.md @@ -0,0 +1,79 @@ +# pkg-config-rs + +[![Build Status](https://github.com/rust-lang/pkg-config-rs/actions/workflows/ci.yml/badge.svg)](https://github.com/rust-lang/pkg-config-rs/actions) +[![Rust](https://img.shields.io/badge/rust-1.31%2B-blue.svg?maxAge=3600)](https://github.com/rust-lang/pkg-config-rs/) + +[Documentation](https://docs.rs/pkg-config) + +A simple library meant to be used as a build dependency with Cargo packages in +order to use the system `pkg-config` tool (if available) to determine where a +library is located. + +You can use this crate directly to probe for specific libraries, or use +[system-deps](https://github.com/gdesmott/system-deps) to declare all your +`pkg-config` dependencies in `Cargo.toml`. + +This library requires Rust 1.31+. + +# Example + +Find the system library named `foo`, with minimum version 1.2.3: + +```rust +extern crate pkg_config; + +fn main() { + pkg_config::Config::new().atleast_version("1.2.3").probe("foo").unwrap(); +} +``` + +Find the system library named `foo`, with no version requirement (not +recommended): + +```rust +extern crate pkg_config; + +fn main() { + pkg_config::probe_library("foo").unwrap(); +} +``` + +# External configuration via target-scoped environment variables + +In cross-compilation context, it is useful to manage separately `PKG_CONFIG_PATH` +and a few other variables for the `host` and the `target` platform. + +The supported variables are: `PKG_CONFIG_PATH`, `PKG_CONFIG_LIBDIR`, and +`PKG_CONFIG_SYSROOT_DIR`. + +Each of these variables can also be supplied with certain prefixes and suffixes, in the following prioritized order: + +1. `_` - for example, `PKG_CONFIG_PATH_x86_64-unknown-linux-gnu` +2. `_` - for example, `PKG_CONFIG_PATH_x86_64_unknown_linux_gnu` +3. `_` - for example, `HOST_PKG_CONFIG_PATH` or `TARGET_PKG_CONFIG_PATH` +4. `` - a plain `PKG_CONFIG_PATH` + +This crate will allow `pkg-config` to be used in cross-compilation +if `PKG_CONFIG_SYSROOT_DIR` or `PKG_CONFIG` is set. You can set `PKG_CONFIG_ALLOW_CROSS=1` +to bypass the compatibility check, but please note that enabling use of `pkg-config` in +cross-compilation without appropriate sysroot and search paths set is likely to break builds. + +Some Rust sys crates support building vendored libraries from source, which may be a work +around for lack of cross-compilation support in `pkg-config`. + +# License + +This project is licensed under either of + + * Apache License, Version 2.0, ([LICENSE-APACHE](LICENSE-APACHE) or + https://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or + https://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in pkg-config-rs by you, as defined in the Apache-2.0 license, shall be +dual licensed as above, without any additional terms or conditions. diff --git a/external/vendor/pkg-config/src/lib.rs b/external/vendor/pkg-config/src/lib.rs new file mode 100644 index 0000000000..93e34c6dd8 --- /dev/null +++ b/external/vendor/pkg-config/src/lib.rs @@ -0,0 +1,1205 @@ +//! A build dependency for Cargo libraries to find system artifacts through the +//! `pkg-config` utility. +//! +//! This library will shell out to `pkg-config` as part of build scripts and +//! probe the system to determine how to link to a specified library. The +//! `Config` structure serves as a method of configuring how `pkg-config` is +//! invoked in a builder style. +//! +//! After running `pkg-config` all appropriate Cargo metadata will be printed on +//! stdout if the search was successful. +//! +//! # Environment variables +//! +//! A number of environment variables are available to globally configure how +//! this crate will invoke `pkg-config`: +//! +//! * `FOO_NO_PKG_CONFIG` - if set, this will disable running `pkg-config` when +//! probing for the library named `foo`. +//! +//! ### Linking +//! +//! There are also a number of environment variables which can configure how a +//! library is linked to (dynamically vs statically). These variables control +//! whether the `--static` flag is passed. Note that this behavior can be +//! overridden by configuring explicitly on `Config`. The variables are checked +//! in the following order: +//! +//! * `FOO_STATIC` - pass `--static` for the library `foo` +//! * `FOO_DYNAMIC` - do not pass `--static` for the library `foo` +//! * `PKG_CONFIG_ALL_STATIC` - pass `--static` for all libraries +//! * `PKG_CONFIG_ALL_DYNAMIC` - do not pass `--static` for all libraries +//! +//! ### Cross-compilation +//! +//! In cross-compilation context, it is useful to manage separately +//! `PKG_CONFIG_PATH` and a few other variables for the `host` and the `target` +//! platform. +//! +//! The supported variables are: `PKG_CONFIG_PATH`, `PKG_CONFIG_LIBDIR`, and +//! `PKG_CONFIG_SYSROOT_DIR`. +//! +//! Each of these variables can also be supplied with certain prefixes and +//! suffixes, in the following prioritized order: +//! +//! 1. `_` - for example, `PKG_CONFIG_PATH_x86_64-unknown-linux-gnu` +//! 2. `_` - for example, +//! `PKG_CONFIG_PATH_x86_64_unknown_linux_gnu` +//! 3. `_` - for example, `HOST_PKG_CONFIG_PATH` or +//! `TARGET_PKG_CONFIG_PATH` +//! 4. `` - a plain `PKG_CONFIG_PATH` +//! +//! This crate will allow `pkg-config` to be used in cross-compilation +//! if `PKG_CONFIG_SYSROOT_DIR` or `PKG_CONFIG` is set. You can set +//! `PKG_CONFIG_ALLOW_CROSS=1` to bypass the compatibility check, but please +//! note that enabling use of `pkg-config` in cross-compilation without +//! appropriate sysroot and search paths set is likely to break builds. +//! +//! # Example +//! +//! Find the system library named `foo`, with minimum version 1.2.3: +//! +//! ```no_run +//! fn main() { +//! pkg_config::Config::new().atleast_version("1.2.3").probe("foo").unwrap(); +//! } +//! ``` +//! +//! Find the system library named `foo`, with no version requirement (not +//! recommended): +//! +//! ```no_run +//! fn main() { +//! pkg_config::probe_library("foo").unwrap(); +//! } +//! ``` +//! +//! Configure how library `foo` is linked to. +//! +//! ```no_run +//! fn main() { +//! pkg_config::Config::new().atleast_version("1.2.3").statik(true).probe("foo").unwrap(); +//! } +//! ``` + +#![doc(html_root_url = "https://docs.rs/pkg-config/0.3")] + +use std::collections::HashMap; +use std::env; +use std::error; +use std::ffi::{OsStr, OsString}; +use std::fmt; +use std::fmt::Display; +use std::io; +use std::ops::{Bound, RangeBounds}; +use std::path::PathBuf; +use std::process::{Command, Output}; +use std::str; + +/// Wrapper struct to polyfill methods introduced in 1.57 (`get_envs`, `get_args` etc). +/// This is needed to reconstruct the pkg-config command for output in a copy- +/// paste friendly format via `Display`. +struct WrappedCommand { + inner: Command, + program: OsString, + env_vars: Vec<(OsString, OsString)>, + args: Vec, +} + +#[derive(Clone, Debug)] +pub struct Config { + statik: Option, + min_version: Bound, + max_version: Bound, + extra_args: Vec, + cargo_metadata: bool, + env_metadata: bool, + print_system_libs: bool, + print_system_cflags: bool, +} + +#[derive(Clone, Debug)] +pub struct Library { + /// Libraries specified by -l + pub libs: Vec, + /// Library search paths specified by -L + pub link_paths: Vec, + /// Library file paths specified without -l + pub link_files: Vec, + /// Darwin frameworks specified by -framework + pub frameworks: Vec, + /// Darwin framework search paths specified by -F + pub framework_paths: Vec, + /// C/C++ header include paths specified by -I + pub include_paths: Vec, + /// Linker options specified by -Wl + pub ld_args: Vec>, + /// C/C++ definitions specified by -D + pub defines: HashMap>, + /// Version specified by .pc file's Version field + pub version: String, + /// Ensure that this struct can only be created via its private `[Library::new]` constructor. + /// Users of this crate can only access the struct via `[Config::probe]`. + _priv: (), +} + +/// Represents all reasons `pkg-config` might not succeed or be run at all. +pub enum Error { + /// Aborted because of `*_NO_PKG_CONFIG` environment variable. + /// + /// Contains the name of the responsible environment variable. + EnvNoPkgConfig(String), + + /// Detected cross compilation without a custom sysroot. + /// + /// Ignore the error with `PKG_CONFIG_ALLOW_CROSS=1`, + /// which may let `pkg-config` select libraries + /// for the host's architecture instead of the target's. + CrossCompilation, + + /// Failed to run `pkg-config`. + /// + /// Contains the command and the cause. + Command { command: String, cause: io::Error }, + + /// `pkg-config` did not exit successfully after probing a library. + /// + /// Contains the command and output. + Failure { command: String, output: Output }, + + /// `pkg-config` did not exit successfully on the first attempt to probe a library. + /// + /// Contains the command and output. + ProbeFailure { + name: String, + command: String, + output: Output, + }, + + #[doc(hidden)] + // please don't match on this, we're likely to add more variants over time + __Nonexhaustive, +} + +impl WrappedCommand { + fn new>(program: S) -> Self { + Self { + inner: Command::new(program.as_ref()), + program: program.as_ref().to_os_string(), + env_vars: Vec::new(), + args: Vec::new(), + } + } + + fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator + Clone, + S: AsRef, + { + self.inner.args(args.clone()); + self.args + .extend(args.into_iter().map(|arg| arg.as_ref().to_os_string())); + + self + } + + fn arg>(&mut self, arg: S) -> &mut Self { + self.inner.arg(arg.as_ref()); + self.args.push(arg.as_ref().to_os_string()); + + self + } + + fn env(&mut self, key: K, value: V) -> &mut Self + where + K: AsRef, + V: AsRef, + { + self.inner.env(key.as_ref(), value.as_ref()); + self.env_vars + .push((key.as_ref().to_os_string(), value.as_ref().to_os_string())); + + self + } + + fn output(&mut self) -> io::Result { + self.inner.output() + } +} + +/// Quote an argument that has spaces in it. +/// When our `WrappedCommand` is printed to the terminal, arguments that contain spaces needed to be quoted. +/// Otherwise, we will have output such as: +/// `pkg-config --libs --cflags foo foo < 3.11` +/// which cannot be used in a terminal - it will attempt to read a file named 3.11 and provide it as stdin for pkg-config. +/// Using this function, we instead get the correct output: +/// `pkg-config --libs --cflags foo 'foo < 3.11'` +fn quote_if_needed(arg: String) -> String { + if arg.contains(' ') { + format!("'{}'", arg) + } else { + arg + } +} + +/// Output a command invocation that can be copy-pasted into the terminal. +/// `Command`'s existing debug implementation is not used for that reason, +/// as it can sometimes lead to output such as: +/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS="1" PKG_CONFIG_ALLOW_SYSTEM_LIBS="1" "pkg-config" "--libs" "--cflags" "mylibrary"` +/// Which cannot be copy-pasted into terminals such as nushell, and is a bit noisy. +/// This will look something like: +/// `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS=1 PKG_CONFIG_ALLOW_SYSTEM_LIBS=1 pkg-config --libs --cflags mylibrary` +impl Display for WrappedCommand { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + // Format all explicitly defined environment variables + let envs = self + .env_vars + .iter() + .map(|(env, arg)| format!("{}={}", env.to_string_lossy(), arg.to_string_lossy())) + .collect::>() + .join(" "); + + // Format all pkg-config arguments + let args = self + .args + .iter() + .map(|arg| quote_if_needed(arg.to_string_lossy().to_string())) + .collect::>() + .join(" "); + + write!(f, "{} {} {}", envs, self.program.to_string_lossy(), args) + } +} + +impl error::Error for Error {} + +impl fmt::Debug for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + // Failed `unwrap()` prints Debug representation, but the default debug format lacks helpful instructions for the end users + ::fmt(self, f) + } +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> { + match *self { + Error::EnvNoPkgConfig(ref name) => write!(f, "Aborted because {} is set", name), + Error::CrossCompilation => f.write_str( + "pkg-config has not been configured to support cross-compilation.\n\ + \n\ + Install a sysroot for the target platform and configure it via\n\ + PKG_CONFIG_SYSROOT_DIR and PKG_CONFIG_PATH, or install a\n\ + cross-compiling wrapper for pkg-config and set it via\n\ + PKG_CONFIG environment variable.", + ), + Error::Command { + ref command, + ref cause, + } => { + match cause.kind() { + io::ErrorKind::NotFound => { + let crate_name = + std::env::var("CARGO_PKG_NAME").unwrap_or_else(|_| "sys".to_owned()); + let instructions = if cfg!(target_os = "macos") { + "Try `brew install pkgconf` if you have Homebrew.\n" + } else if cfg!(target_os = "ios") { + "" // iOS cross-compilation requires a custom setup, no easy fix + } else if cfg!(unix) { + "Try `apt install pkg-config`, or `yum install pkg-config`, or `brew install pkgconf`\n\ + or `pkg install pkg-config`, or `apk add pkgconfig` \ + depending on your distribution.\n" + } else { + "" // There's no easy fix for Windows users + }; + write!(f, "Could not run `{command}`\n\ + The pkg-config command could not be found.\n\ + \n\ + Most likely, you need to install a pkg-config package for your OS.\n\ + {instructions}\ + \n\ + If you've already installed it, ensure the pkg-config command is one of the\n\ + directories in the PATH environment variable.\n\ + \n\ + If you did not expect this build to link to a pre-installed system library,\n\ + then check documentation of the {crate_name} crate for an option to\n\ + build the library from source, or disable features or dependencies\n\ + that require pkg-config.", command = command, instructions = instructions, crate_name = crate_name) + } + _ => write!(f, "Failed to run command `{}`, because: {}", command, cause), + } + } + Error::ProbeFailure { + ref name, + ref command, + ref output, + } => { + let crate_name = + env::var("CARGO_PKG_NAME").unwrap_or(String::from("")); + + writeln!(f, "")?; + + // Give a short explanation of what the error is + writeln!( + f, + "pkg-config {}", + match output.status.code() { + Some(code) => format!("exited with status code {}", code), + None => "was terminated by signal".to_string(), + } + )?; + + // Give the command run so users can reproduce the error + writeln!(f, "> {}\n", command)?; + + // Explain how it was caused + writeln!( + f, + "The system library `{}` required by crate `{}` was not found.", + name, crate_name + )?; + writeln!( + f, + "The file `{}.pc` needs to be installed and the PKG_CONFIG_PATH environment variable must contain its parent directory.", + name + )?; + + // There will be no status code if terminated by signal + if let Some(_code) = output.status.code() { + // Nix uses a wrapper script for pkg-config that sets the custom + // environment variable PKG_CONFIG_PATH_FOR_TARGET + let search_locations = ["PKG_CONFIG_PATH_FOR_TARGET", "PKG_CONFIG_PATH"]; + + // Find a search path to use + let mut search_data = None; + for location in search_locations.iter() { + if let Ok(search_path) = env::var(location) { + search_data = Some((location, search_path)); + break; + } + } + + // Guess the most reasonable course of action + let hint = if let Some((search_location, search_path)) = search_data { + writeln!( + f, + "{} contains the following:\n{}", + search_location, + search_path + .split(':') + .map(|path| format!(" - {}", path)) + .collect::>() + .join("\n"), + )?; + + format!("you may need to install a package such as {name}, {name}-dev or {name}-devel.", name=name) + } else { + // Even on Nix, setting PKG_CONFIG_PATH seems to be a viable option + writeln!(f, "The PKG_CONFIG_PATH environment variable is not set.")?; + + format!( + "if you have installed the library, try setting PKG_CONFIG_PATH to the directory containing `{}.pc`.", + name + ) + }; + + // Try and nudge the user in the right direction so they don't get stuck + writeln!(f, "\nHINT: {}", hint)?; + } + + Ok(()) + } + Error::Failure { + ref command, + ref output, + } => { + write!( + f, + "`{}` did not exit successfully: {}", + command, output.status + )?; + format_output(output, f) + } + Error::__Nonexhaustive => panic!(), + } + } +} + +fn format_output(output: &Output, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let stdout = String::from_utf8_lossy(&output.stdout); + if !stdout.is_empty() { + write!(f, "\n--- stdout\n{}", stdout)?; + } + let stderr = String::from_utf8_lossy(&output.stderr); + if !stderr.is_empty() { + write!(f, "\n--- stderr\n{}", stderr)?; + } + Ok(()) +} + +/// Deprecated in favor of the probe_library function +#[doc(hidden)] +pub fn find_library(name: &str) -> Result { + probe_library(name).map_err(|e| e.to_string()) +} + +/// Simple shortcut for using all default options for finding a library. +pub fn probe_library(name: &str) -> Result { + Config::new().probe(name) +} + +#[doc(hidden)] +#[deprecated(note = "use config.target_supported() instance method instead")] +pub fn target_supported() -> bool { + Config::new().target_supported() +} + +/// Run `pkg-config` to get the value of a variable from a package using +/// `--variable`. +/// +/// The content of `PKG_CONFIG_SYSROOT_DIR` is not injected in paths that are +/// returned by `pkg-config --variable`, which makes them unsuitable to use +/// during cross-compilation unless specifically designed to be used +/// at that time. +pub fn get_variable(package: &str, variable: &str) -> Result { + let arg = format!("--variable={}", variable); + let cfg = Config::new(); + let out = cfg.run(package, &[&arg])?; + Ok(str::from_utf8(&out).unwrap().trim_end().to_owned()) +} + +impl Config { + /// Creates a new set of configuration options which are all initially set + /// to "blank". + pub fn new() -> Config { + Config { + statik: None, + min_version: Bound::Unbounded, + max_version: Bound::Unbounded, + extra_args: vec![], + print_system_cflags: true, + print_system_libs: true, + cargo_metadata: true, + env_metadata: true, + } + } + + /// Indicate whether the `--static` flag should be passed. + /// + /// This will override the inference from environment variables described in + /// the crate documentation. + pub fn statik(&mut self, statik: bool) -> &mut Config { + self.statik = Some(statik); + self + } + + /// Indicate that the library must be at least version `vers`. + pub fn atleast_version(&mut self, vers: &str) -> &mut Config { + self.min_version = Bound::Included(vers.to_string()); + self.max_version = Bound::Unbounded; + self + } + + /// Indicate that the library must be equal to version `vers`. + pub fn exactly_version(&mut self, vers: &str) -> &mut Config { + self.min_version = Bound::Included(vers.to_string()); + self.max_version = Bound::Included(vers.to_string()); + self + } + + /// Indicate that the library's version must be in `range`. + pub fn range_version<'a, R>(&mut self, range: R) -> &mut Config + where + R: RangeBounds<&'a str>, + { + self.min_version = match range.start_bound() { + Bound::Included(vers) => Bound::Included(vers.to_string()), + Bound::Excluded(vers) => Bound::Excluded(vers.to_string()), + Bound::Unbounded => Bound::Unbounded, + }; + self.max_version = match range.end_bound() { + Bound::Included(vers) => Bound::Included(vers.to_string()), + Bound::Excluded(vers) => Bound::Excluded(vers.to_string()), + Bound::Unbounded => Bound::Unbounded, + }; + self + } + + /// Add an argument to pass to pkg-config. + /// + /// It's placed after all of the arguments generated by this library. + pub fn arg>(&mut self, arg: S) -> &mut Config { + self.extra_args.push(arg.as_ref().to_os_string()); + self + } + + /// Define whether metadata should be emitted for cargo allowing it to + /// automatically link the binary. Defaults to `true`. + pub fn cargo_metadata(&mut self, cargo_metadata: bool) -> &mut Config { + self.cargo_metadata = cargo_metadata; + self + } + + /// Define whether metadata should be emitted for cargo allowing to + /// automatically rebuild when environment variables change. Defaults to + /// `true`. + pub fn env_metadata(&mut self, env_metadata: bool) -> &mut Config { + self.env_metadata = env_metadata; + self + } + + /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_LIBS` environment + /// variable. + /// + /// This env var is enabled by default. + pub fn print_system_libs(&mut self, print: bool) -> &mut Config { + self.print_system_libs = print; + self + } + + /// Enable or disable the `PKG_CONFIG_ALLOW_SYSTEM_CFLAGS` environment + /// variable. + /// + /// This env var is enabled by default. + pub fn print_system_cflags(&mut self, print: bool) -> &mut Config { + self.print_system_cflags = print; + self + } + + /// Deprecated in favor fo the `probe` function + #[doc(hidden)] + pub fn find(&self, name: &str) -> Result { + self.probe(name).map_err(|e| e.to_string()) + } + + /// Run `pkg-config` to find the library `name`. + /// + /// This will use all configuration previously set to specify how + /// `pkg-config` is run. + pub fn probe(&self, name: &str) -> Result { + let abort_var_name = format!("{}_NO_PKG_CONFIG", envify(name)); + if self.env_var_os(&abort_var_name).is_some() { + return Err(Error::EnvNoPkgConfig(abort_var_name)); + } else if !self.target_supported() { + return Err(Error::CrossCompilation); + } + + let mut library = Library::new(); + + let output = self + .run(name, &["--libs", "--cflags"]) + .map_err(|e| match e { + Error::Failure { command, output } => Error::ProbeFailure { + name: name.to_owned(), + command, + output, + }, + other => other, + })?; + library.parse_libs_cflags(name, &output, self); + + let output = self.run(name, &["--modversion"])?; + library.parse_modversion(str::from_utf8(&output).unwrap()); + + Ok(library) + } + + /// True if pkg-config is used for the host system, or configured for cross-compilation + pub fn target_supported(&self) -> bool { + let target = env::var_os("TARGET").unwrap_or_default(); + let host = env::var_os("HOST").unwrap_or_default(); + + // Only use pkg-config in host == target situations by default (allowing an + // override). + if host == target { + return true; + } + + // pkg-config may not be aware of cross-compilation, and require + // a wrapper script that sets up platform-specific prefixes. + match self.targeted_env_var("PKG_CONFIG_ALLOW_CROSS") { + // don't use pkg-config if explicitly disabled + Some(ref val) if val == "0" => false, + Some(_) => true, + None => { + // if not disabled, and pkg-config is customized, + // then assume it's prepared for cross-compilation + self.targeted_env_var("PKG_CONFIG").is_some() + || self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR").is_some() + } + } + } + + /// Deprecated in favor of the top level `get_variable` function + #[doc(hidden)] + pub fn get_variable(package: &str, variable: &str) -> Result { + get_variable(package, variable).map_err(|e| e.to_string()) + } + + fn targeted_env_var(&self, var_base: &str) -> Option { + match (env::var("TARGET"), env::var("HOST")) { + (Ok(target), Ok(host)) => { + let kind = if host == target { "HOST" } else { "TARGET" }; + let target_u = target.replace('-', "_"); + + self.env_var_os(&format!("{}_{}", var_base, target)) + .or_else(|| self.env_var_os(&format!("{}_{}", var_base, target_u))) + .or_else(|| self.env_var_os(&format!("{}_{}", kind, var_base))) + .or_else(|| self.env_var_os(var_base)) + } + (Err(env::VarError::NotPresent), _) | (_, Err(env::VarError::NotPresent)) => { + self.env_var_os(var_base) + } + (Err(env::VarError::NotUnicode(s)), _) | (_, Err(env::VarError::NotUnicode(s))) => { + panic!( + "HOST or TARGET environment variable is not valid unicode: {:?}", + s + ) + } + } + } + + fn env_var_os(&self, name: &str) -> Option { + if self.env_metadata { + println!("cargo:rerun-if-env-changed={}", name); + } + env::var_os(name) + } + + fn is_static(&self, name: &str) -> bool { + self.statik.unwrap_or_else(|| self.infer_static(name)) + } + + fn run(&self, name: &str, args: &[&str]) -> Result, Error> { + let pkg_config_exe = self.targeted_env_var("PKG_CONFIG"); + let fallback_exe = if pkg_config_exe.is_none() { + Some(OsString::from("pkgconf")) + } else { + None + }; + let exe = pkg_config_exe.unwrap_or_else(|| OsString::from("pkg-config")); + + let mut cmd = self.command(exe, name, args); + + match cmd.output().or_else(|e| { + if let Some(exe) = fallback_exe { + self.command(exe, name, args).output() + } else { + Err(e) + } + }) { + Ok(output) => { + if output.status.success() { + Ok(output.stdout) + } else { + Err(Error::Failure { + command: format!("{}", cmd), + output, + }) + } + } + Err(cause) => Err(Error::Command { + command: format!("{}", cmd), + cause, + }), + } + } + + fn command(&self, exe: OsString, name: &str, args: &[&str]) -> WrappedCommand { + let mut cmd = WrappedCommand::new(exe); + if self.is_static(name) { + cmd.arg("--static"); + } + cmd.args(args).args(&self.extra_args); + + if let Some(value) = self.targeted_env_var("PKG_CONFIG_PATH") { + cmd.env("PKG_CONFIG_PATH", value); + } + if let Some(value) = self.targeted_env_var("PKG_CONFIG_LIBDIR") { + cmd.env("PKG_CONFIG_LIBDIR", value); + } + if let Some(value) = self.targeted_env_var("PKG_CONFIG_SYSROOT_DIR") { + cmd.env("PKG_CONFIG_SYSROOT_DIR", value); + } + if self.print_system_libs { + cmd.env("PKG_CONFIG_ALLOW_SYSTEM_LIBS", "1"); + } + if self.print_system_cflags { + cmd.env("PKG_CONFIG_ALLOW_SYSTEM_CFLAGS", "1"); + } + cmd.arg(name); + match self.min_version { + Bound::Included(ref version) => { + cmd.arg(&format!("{} >= {}", name, version)); + } + Bound::Excluded(ref version) => { + cmd.arg(&format!("{} > {}", name, version)); + } + _ => (), + } + match self.max_version { + Bound::Included(ref version) => { + cmd.arg(&format!("{} <= {}", name, version)); + } + Bound::Excluded(ref version) => { + cmd.arg(&format!("{} < {}", name, version)); + } + _ => (), + } + cmd + } + + fn print_metadata(&self, s: &str) { + if self.cargo_metadata { + println!("cargo:{}", s); + } + } + + fn infer_static(&self, name: &str) -> bool { + let name = envify(name); + if self.env_var_os(&format!("{}_STATIC", name)).is_some() { + true + } else if self.env_var_os(&format!("{}_DYNAMIC", name)).is_some() { + false + } else if self.env_var_os("PKG_CONFIG_ALL_STATIC").is_some() { + true + } else if self.env_var_os("PKG_CONFIG_ALL_DYNAMIC").is_some() { + false + } else { + false + } + } +} + +// Implement Default manually since Bound does not implement Default. +impl Default for Config { + fn default() -> Config { + Config { + statik: None, + min_version: Bound::Unbounded, + max_version: Bound::Unbounded, + extra_args: vec![], + print_system_cflags: false, + print_system_libs: false, + cargo_metadata: false, + env_metadata: false, + } + } +} + +impl Library { + fn new() -> Library { + Library { + libs: Vec::new(), + link_paths: Vec::new(), + link_files: Vec::new(), + include_paths: Vec::new(), + ld_args: Vec::new(), + frameworks: Vec::new(), + framework_paths: Vec::new(), + defines: HashMap::new(), + version: String::new(), + _priv: (), + } + } + + /// Extract the &str to pass to cargo:rustc-link-lib from a filename (just the file name, not including directories) + /// using target-specific logic. + fn extract_lib_from_filename<'a>(target: &str, filename: &'a str) -> Option<&'a str> { + fn test_suffixes<'b>(filename: &'b str, suffixes: &[&str]) -> Option<&'b str> { + for suffix in suffixes { + if filename.ends_with(suffix) { + return Some(&filename[..filename.len() - suffix.len()]); + } + } + None + } + + let prefix = "lib"; + if target.contains("windows") { + if target.contains("gnu") && filename.starts_with(prefix) { + // GNU targets for Windows, including gnullvm, use `LinkerFlavor::Gcc` internally in rustc, + // which tells rustc to use the GNU linker. rustc does not prepend/append to the string it + // receives via the -l command line argument before passing it to the linker: + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L446 + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L457 + // GNU ld can work with more types of files than just the .lib files that MSVC's link.exe needs. + // GNU ld will prepend the `lib` prefix to the filename if necessary, so it is okay to remove + // the `lib` prefix from the filename. The `.a` suffix *requires* the `lib` prefix. + // https://sourceware.org/binutils/docs-2.39/ld.html#index-direct-linking-to-a-dll + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]); + } else { + // According to link.exe documentation: + // https://learn.microsoft.com/en-us/cpp/build/reference/link-input-files?view=msvc-170 + // + // LINK doesn't use file extensions to make assumptions about the contents of a file. + // Instead, LINK examines each input file to determine what kind of file it is. + // + // However, rustc appends `.lib` to the string it receives from the -l command line argument, + // which it receives from Cargo via cargo:rustc-link-lib: + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L828 + // https://github.com/rust-lang/rust/blob/657f246812ab2684e3c3954b1c77f98fd59e0b21/compiler/rustc_codegen_ssa/src/back/linker.rs#L843 + // So the only file extension that works for MSVC targets is `.lib` + // However, for externally created libraries, there's no + // guarantee that the extension is ".lib" so we need to + // consider all options. + // See: + // https://github.com/mesonbuild/meson/issues/8153 + // https://github.com/rust-lang/rust/issues/114013 + return test_suffixes(filename, &[".dll.a", ".dll", ".lib", ".a"]); + } + } else if target.contains("apple") { + if filename.starts_with(prefix) { + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".a", ".so", ".dylib"]); + } + return None; + } else { + if filename.starts_with(prefix) { + let filename = &filename[prefix.len()..]; + return test_suffixes(filename, &[".a", ".so"]); + } + return None; + } + } + + fn parse_libs_cflags(&mut self, name: &str, output: &[u8], config: &Config) { + let target = env::var("TARGET"); + let is_msvc = target + .as_ref() + .map(|target| target.contains("msvc")) + .unwrap_or(false); + + let system_roots = if cfg!(target_os = "macos") { + vec![PathBuf::from("/Library"), PathBuf::from("/System")] + } else { + let sysroot = config + .env_var_os("PKG_CONFIG_SYSROOT_DIR") + .or_else(|| config.env_var_os("SYSROOT")) + .map(PathBuf::from); + + if cfg!(target_os = "windows") { + if let Some(sysroot) = sysroot { + vec![sysroot] + } else { + vec![] + } + } else { + vec![sysroot.unwrap_or_else(|| PathBuf::from("/usr"))] + } + }; + + let mut dirs = Vec::new(); + let statik = config.is_static(name); + + let words = split_flags(output); + + // Handle single-character arguments like `-I/usr/include` + let parts = words + .iter() + .filter(|l| l.len() > 2) + .map(|arg| (&arg[0..2], &arg[2..])); + for (flag, val) in parts { + match flag { + "-L" => { + let meta = format!("rustc-link-search=native={}", val); + config.print_metadata(&meta); + dirs.push(PathBuf::from(val)); + self.link_paths.push(PathBuf::from(val)); + } + "-F" => { + let meta = format!("rustc-link-search=framework={}", val); + config.print_metadata(&meta); + self.framework_paths.push(PathBuf::from(val)); + } + "-I" => { + self.include_paths.push(PathBuf::from(val)); + } + "-l" => { + // These are provided by the CRT with MSVC + if is_msvc && ["m", "c", "pthread"].contains(&val) { + continue; + } + + if val.starts_with(':') { + // Pass this flag to linker directly. + let meta = format!("rustc-link-arg={}{}", flag, val); + config.print_metadata(&meta); + } else if statik && is_static_available(val, &system_roots, &dirs) { + let meta = format!("rustc-link-lib=static={}", val); + config.print_metadata(&meta); + } else { + let meta = format!("rustc-link-lib={}", val); + config.print_metadata(&meta); + } + + self.libs.push(val.to_string()); + } + "-D" => { + let mut iter = val.split('='); + self.defines.insert( + iter.next().unwrap().to_owned(), + iter.next().map(|s| s.to_owned()), + ); + } + "-u" => { + let meta = format!("rustc-link-arg=-Wl,-u,{}", val); + config.print_metadata(&meta); + } + _ => {} + } + } + + // Handle multi-character arguments with space-separated value like `-framework foo` + let mut iter = words.iter().flat_map(|arg| { + if arg.starts_with("-Wl,") { + arg[4..].split(',').collect() + } else { + vec![arg.as_ref()] + } + }); + while let Some(part) = iter.next() { + match part { + "-framework" => { + if let Some(lib) = iter.next() { + let meta = format!("rustc-link-lib=framework={}", lib); + config.print_metadata(&meta); + self.frameworks.push(lib.to_string()); + } + } + "-isystem" | "-iquote" | "-idirafter" => { + if let Some(inc) = iter.next() { + self.include_paths.push(PathBuf::from(inc)); + } + } + "-undefined" | "--undefined" => { + if let Some(symbol) = iter.next() { + let meta = format!("rustc-link-arg=-Wl,{},{}", part, symbol); + config.print_metadata(&meta); + } + } + _ => { + let path = std::path::Path::new(part); + if path.is_file() { + // Cargo doesn't have a means to directly specify a file path to link, + // so split up the path into the parent directory and library name. + // TODO: pass file path directly when link-arg library type is stabilized + // https://github.com/rust-lang/rust/issues/99427 + if let (Some(dir), Some(file_name), Ok(target)) = + (path.parent(), path.file_name(), &target) + { + match Self::extract_lib_from_filename( + target, + &file_name.to_string_lossy(), + ) { + Some(lib_basename) => { + let link_search = + format!("rustc-link-search={}", dir.display()); + config.print_metadata(&link_search); + + let link_lib = format!("rustc-link-lib={}", lib_basename); + config.print_metadata(&link_lib); + self.link_files.push(PathBuf::from(path)); + } + None => { + println!("cargo:warning=File path {} found in pkg-config file for {}, but could not extract library base name to pass to linker command line", path.display(), name); + } + } + } + } + } + } + } + + let linker_options = words.iter().filter(|arg| arg.starts_with("-Wl,")); + for option in linker_options { + let mut pop = false; + let mut ld_option = vec![]; + for subopt in option[4..].split(',') { + if pop { + pop = false; + continue; + } + + if subopt == "-framework" { + pop = true; + continue; + } + + ld_option.push(subopt); + } + + let meta = format!("rustc-link-arg=-Wl,{}", ld_option.join(",")); + config.print_metadata(&meta); + + self.ld_args + .push(ld_option.into_iter().map(String::from).collect()); + } + } + + fn parse_modversion(&mut self, output: &str) { + self.version.push_str(output.lines().next().unwrap().trim()); + } +} + +fn envify(name: &str) -> String { + name.chars() + .map(|c| c.to_ascii_uppercase()) + .map(|c| if c == '-' { '_' } else { c }) + .collect() +} + +/// System libraries should only be linked dynamically +fn is_static_available(name: &str, system_roots: &[PathBuf], dirs: &[PathBuf]) -> bool { + let libnames = { + let mut names = vec![format!("lib{}.a", name)]; + + if cfg!(target_os = "windows") { + names.push(format!("{}.lib", name)); + } + + names + }; + + dirs.iter().any(|dir| { + let library_exists = libnames.iter().any(|libname| dir.join(&libname).exists()); + library_exists && !system_roots.iter().any(|sys| dir.starts_with(sys)) + }) +} + +/// Split output produced by pkg-config --cflags and / or --libs into separate flags. +/// +/// Backslash in output is used to preserve literal meaning of following byte. Different words are +/// separated by unescaped space. Other whitespace characters generally should not occur unescaped +/// at all, apart from the newline at the end of output. For compatibility with what others +/// consumers of pkg-config output would do in this scenario, they are used here for splitting as +/// well. +fn split_flags(output: &[u8]) -> Vec { + let mut word = Vec::new(); + let mut words = Vec::new(); + let mut escaped = false; + + for &b in output { + match b { + _ if escaped => { + escaped = false; + word.push(b); + } + b'\\' => escaped = true, + b'\t' | b'\n' | b'\r' | b' ' => { + if !word.is_empty() { + words.push(String::from_utf8(word).unwrap()); + word = Vec::new(); + } + } + _ => word.push(b), + } + } + + if !word.is_empty() { + words.push(String::from_utf8(word).unwrap()); + } + + words +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + #[cfg(target_os = "macos")] + fn system_library_mac_test() { + use std::path::Path; + + let system_roots = vec![PathBuf::from("/Library"), PathBuf::from("/System")]; + + assert!(!is_static_available( + "PluginManager", + &system_roots, + &[PathBuf::from("/Library/Frameworks")] + )); + assert!(!is_static_available( + "python2.7", + &system_roots, + &[PathBuf::from( + "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/config" + )] + )); + assert!(!is_static_available( + "ffi_convenience", + &system_roots, + &[PathBuf::from( + "/Library/Ruby/Gems/2.0.0/gems/ffi-1.9.10/ext/ffi_c/libffi-x86_64/.libs" + )] + )); + + // Homebrew is in /usr/local, and it's not a part of the OS + if Path::new("/usr/local/lib/libpng16.a").exists() { + assert!(is_static_available( + "png16", + &system_roots, + &[PathBuf::from("/usr/local/lib")] + )); + + let libpng = Config::new() + .range_version("1".."99") + .probe("libpng16") + .unwrap(); + assert!(libpng.version.find('\n').is_none()); + } + } + + #[test] + #[cfg(target_os = "linux")] + fn system_library_linux_test() { + assert!(!is_static_available( + "util", + &[PathBuf::from("/usr")], + &[PathBuf::from("/usr/lib/x86_64-linux-gnu")] + )); + assert!(!is_static_available( + "dialog", + &[PathBuf::from("/usr")], + &[PathBuf::from("/usr/lib")] + )); + } + + fn test_library_filename(target: &str, filename: &str) { + assert_eq!( + Library::extract_lib_from_filename(target, filename), + Some("foo") + ); + } + + #[test] + fn link_filename_linux() { + let target = "x86_64-unknown-linux-gnu"; + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "libfoo.so"); + } + + #[test] + fn link_filename_apple() { + let target = "x86_64-apple-darwin"; + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "libfoo.so"); + test_library_filename(target, "libfoo.dylib"); + } + + #[test] + fn link_filename_msvc() { + let target = "x86_64-pc-windows-msvc"; + // static and dynamic libraries have the same .lib suffix + test_library_filename(target, "foo.lib"); + } + + #[test] + fn link_filename_mingw() { + let target = "x86_64-pc-windows-gnu"; + test_library_filename(target, "foo.lib"); + test_library_filename(target, "libfoo.a"); + test_library_filename(target, "foo.dll"); + test_library_filename(target, "foo.dll.a"); + } +} diff --git a/external/vendor/pkg-config/tests/escape.pc b/external/vendor/pkg-config/tests/escape.pc new file mode 100644 index 0000000000..701c4bf73f --- /dev/null +++ b/external/vendor/pkg-config/tests/escape.pc @@ -0,0 +1,5 @@ +Name: Escape +Version: 4.2.0 +Description: Escape utility library +Libs: -Llink\ path\ with\ spaces +Cflags: -Iinclude\ path\ with\ spaces -DA=\"escaped\ string\'\ literal\" -DB=ESCAPED\ IDENTIFIER -DFOX=🦊 diff --git a/external/vendor/pkg-config/tests/foo.pc b/external/vendor/pkg-config/tests/foo.pc new file mode 100644 index 0000000000..ce63ceb558 --- /dev/null +++ b/external/vendor/pkg-config/tests/foo.pc @@ -0,0 +1,16 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/valgrind +arch=amd64 +os=linux +platform=amd64-linux +valt_load_address=0x38000000 + +Name: Valgrind +Description: A dynamic binary instrumentation framework +Version: 3.10.0.SVN +Requires: +Libs: -L${libdir}/valgrind -lcoregrind-amd64-linux -lvex-amd64-linux -lgcc +Cflags: -I${includedir} -isystem /usr/foo + diff --git a/external/vendor/pkg-config/tests/framework.pc b/external/vendor/pkg-config/tests/framework.pc new file mode 100644 index 0000000000..fec17f47a6 --- /dev/null +++ b/external/vendor/pkg-config/tests/framework.pc @@ -0,0 +1,16 @@ +prefix=/usr +exec_prefix=${prefix} +libdir=${exec_prefix}/lib +includedir=${prefix}/include/valgrind +arch=amd64 +os=linux +platform=amd64-linux +valt_load_address=0x38000000 + +Name: Valgrind +Description: A dynamic binary instrumentation framework +Version: 3.10.0.SVN +Requires: +Libs: -F${libdir} -framework foo -Wl,-framework,bar -Wl,-framework -Wl,baz -Wl,-framework,foobar,-framework,foobaz +Cflags: -I${includedir} + diff --git a/external/vendor/pkg-config/tests/rpath.pc b/external/vendor/pkg-config/tests/rpath.pc new file mode 100644 index 0000000000..7c36c5cb71 --- /dev/null +++ b/external/vendor/pkg-config/tests/rpath.pc @@ -0,0 +1,7 @@ +prefix=/usr/local + +Name: rpath +Version: 4.2.0 +Description: RPath example library +Libs: -L${prefix}/lib -Wl,-rpath,${prefix}/lib -lrpath +Cflags: -I${prefix}/include diff --git a/external/vendor/pkg-config/tests/test.rs b/external/vendor/pkg-config/tests/test.rs new file mode 100644 index 0000000000..ef80fc7142 --- /dev/null +++ b/external/vendor/pkg-config/tests/test.rs @@ -0,0 +1,317 @@ +use lazy_static::lazy_static; +use pkg_config::Error; +use std::env; +use std::path::PathBuf; +use std::sync::Mutex; + +lazy_static! { + static ref LOCK: Mutex<()> = Mutex::new(()); +} + +fn reset() { + for (k, _) in env::vars() { + if k.contains("DYNAMIC") + || k.contains("STATIC") + || k.contains("PKG_CONFIG_ALLOW_CROSS") + || k.contains("PKG_CONFIG_SYSROOT_DIR") + || k.contains("FOO_NO_PKG_CONFIG") + { + env::remove_var(&k); + } + } + env::remove_var("TARGET"); + env::remove_var("HOST"); + env::set_var("PKG_CONFIG_PATH", env::current_dir().unwrap().join("tests")); +} + +fn find(name: &str) -> Result { + pkg_config::probe_library(name) +} + +#[test] +fn cross_disabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + match find("foo") { + Err(Error::CrossCompilation) => {} + x => panic!("Error::CrossCompilation expected, found `{:?}`", x), + } +} + +#[test] +fn cross_enabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_ALLOW_CROSS", "1"); + find("foo").unwrap(); +} + +#[test] +fn cross_enabled_if_customized() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_SYSROOT_DIR", "/tmp/cross-test"); + find("foo").unwrap(); +} + +#[test] +fn cross_disabled_if_customized() { + let _g = LOCK.lock(); + reset(); + env::set_var("TARGET", "foo"); + env::set_var("HOST", "bar"); + env::set_var("PKG_CONFIG_ALLOW_CROSS", "0"); + env::set_var("PKG_CONFIG_SYSROOT_DIR", "/tmp/cross-test"); + match find("foo") { + Err(Error::CrossCompilation) => {} + _ => panic!("expected CrossCompilation failure"), + } +} + +#[test] +fn package_disabled() { + let _g = LOCK.lock(); + reset(); + env::set_var("FOO_NO_PKG_CONFIG", "1"); + match find("foo") { + Err(Error::EnvNoPkgConfig(name)) => assert_eq!(name, "FOO_NO_PKG_CONFIG"), + x => panic!("Error::EnvNoPkgConfig expected, found `{:?}`", x), + } +} + +#[test] +fn output_ok() { + let _g = LOCK.lock(); + reset(); + let lib = find("foo").unwrap(); + assert!(lib.libs.contains(&"gcc".to_string())); + assert!(lib.libs.contains(&"coregrind-amd64-linux".to_string())); + assert!(lib.link_paths.contains(&PathBuf::from("/usr/lib/valgrind"))); + assert!(lib + .include_paths + .contains(&PathBuf::from("/usr/include/valgrind"))); + assert!(lib.include_paths.contains(&PathBuf::from("/usr/foo"))); +} + +#[test] +fn escapes() { + let _g = LOCK.lock(); + reset(); + let lib = find("escape").unwrap(); + assert!(lib + .include_paths + .contains(&PathBuf::from("include path with spaces"))); + assert!(lib + .link_paths + .contains(&PathBuf::from("link path with spaces"))); + assert_eq!( + lib.defines.get("A"), + Some(&Some("\"escaped string' literal\"".to_owned())) + ); + assert_eq!( + lib.defines.get("B"), + Some(&Some("ESCAPED IDENTIFIER".to_owned())) + ); + assert_eq!(lib.defines.get("FOX"), Some(&Some("🦊".to_owned()))); +} + +#[test] +fn framework() { + let _g = LOCK.lock(); + reset(); + let lib = find("framework").unwrap(); + assert!(lib.frameworks.contains(&"foo".to_string())); + assert!(lib.frameworks.contains(&"bar".to_string())); + assert!(lib.frameworks.contains(&"baz".to_string())); + assert!(lib.frameworks.contains(&"foobar".to_string())); + assert!(lib.frameworks.contains(&"foobaz".to_string())); + assert!(lib.framework_paths.contains(&PathBuf::from("/usr/lib"))); +} + +#[test] +fn get_variable() { + let _g = LOCK.lock(); + reset(); + let prefix = pkg_config::get_variable("foo", "prefix").unwrap(); + assert_eq!(prefix, "/usr"); +} + +#[test] +fn version() { + let _g = LOCK.lock(); + reset(); + assert_eq!(&find("foo").unwrap().version[..], "3.10.0.SVN"); +} + +#[test] +fn atleast_version_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .atleast_version("3.10") + .probe("foo") + .unwrap(); +} + +#[test] +#[should_panic] +fn atleast_version_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .atleast_version("3.11") + .probe("foo") + .unwrap(); +} + +#[test] +fn exactly_version_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .exactly_version("3.10.0.SVN") + .probe("foo") + .unwrap(); +} + +#[test] +#[should_panic] +fn exactly_version_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .exactly_version("3.10.0") + .probe("foo") + .unwrap(); +} + +#[test] +fn range_version_range_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.2.0".."4.4.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0".."4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_inclusive_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0"..="4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_inclusive_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("3.8.0"..="4.0.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_from_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.0.0"..) + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_from_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version("4.4.0"..) + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_to_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(.."4.4.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_to_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(.."4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_range_to_inclusive_ok() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..="4.2.0") + .probe("escape") + .unwrap(); +} + +#[test] +#[should_panic] +fn range_version_range_to_inclusive_ng() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..="4.0.0") + .probe("escape") + .unwrap(); +} + +#[test] +fn range_version_full() { + let _g = LOCK.lock(); + reset(); + pkg_config::Config::new() + .range_version(..) + .probe("escape") + .unwrap(); +} + +#[test] +fn rpath() { + let _g = LOCK.lock(); + reset(); + let lib = find("rpath").unwrap(); + assert!(lib + .ld_args + .contains(&vec!["-rpath".to_string(), "/usr/local/lib".to_string(),])); +} diff --git a/external/vendor/version-compare/.cargo-checksum.json b/external/vendor/version-compare/.cargo-checksum.json new file mode 100644 index 0000000000..42155fa43b --- /dev/null +++ b/external/vendor/version-compare/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.lock":"b86de918a2485e476bc6c0e0f8193a67bf10bc843fc34c9477ac90db61392a55","Cargo.toml":"9bd47ba86b9f09468f8bb8c93f9807ad3098de7f2a9f91c4a1489b7a64c8416a","LICENSE":"cedfcc7ace1639adb054bd4a19b6f8585ccb2429a60b4bf51bfeb0601058c22c","README.md":"df1b1cde18269d7685a65c13262b2d370fafbe2d6c9d1c31fe79fc2507630e7a","examples/example.rs":"058df6b799fa0447838e90384f64da6b20fed9c3b8baf8ce05518587fcd71d11","examples/minimal.rs":"aa86eae9d778d966d1fbd49f7c3005693e9229b299b0e4eac2ec427628b68a75","src/cmp.rs":"b5b87785bd16a872d67d4c265f434097ff3802b0717513a2ff2f8d917b0e326a","src/compare.rs":"9447a1c0994e92de7ed5ba5d97b0604c056c9efbe235d410a5c9a57a666d9cf8","src/lib.rs":"75cbc287dff38cc28a9ee9ce4e7c3010805df64ba0354f7fd28641d4918ac42d","src/manifest.rs":"cb01e7eed55c200ec8f45e61cb2cd88c6d61df9bb414b57fee6d30bee800935d","src/part.rs":"f6b453cb8f166744ad9a793c66df8e9011443319d1bbd6b5786c586bb49d9322","src/test.rs":"1ca7c09f7b8b7e159335ab13d1f2ee4ada06c20f91492f8c0a85006fee4720d6","src/version.rs":"e994b9db3860897a3d37be5f4d53bb5cca44c42fb5bebf27289fea16136630cc"},"package":"579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29"} \ No newline at end of file diff --git a/external/vendor/version-compare/Cargo.lock b/external/vendor/version-compare/Cargo.lock new file mode 100644 index 0000000000..b3561771ad --- /dev/null +++ b/external/vendor/version-compare/Cargo.lock @@ -0,0 +1,5 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +[[package]] +name = "version-compare" +version = "0.1.1" diff --git a/external/vendor/version-compare/Cargo.toml b/external/vendor/version-compare/Cargo.toml new file mode 100644 index 0000000000..64f001a7fd --- /dev/null +++ b/external/vendor/version-compare/Cargo.toml @@ -0,0 +1,39 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "version-compare" +version = "0.1.1" +authors = ["Tim Visee <3a4fb3964f@sinenomine.email>"] +include = [ + "/src", + "/examples", + "Cargo.toml", + "LICENSE", + "README.md", +] +description = "Rust library to easily compare version numbers with no specific format, and test against various comparison operators." +homepage = "https://timvisee.com/projects/version-compare/" +documentation = "https://docs.rs/version-compare" +readme = "README.md" +keywords = [ + "version", + "compare", + "comparison", + "comparing", +] +categories = [ + "parser-implementations", + "parsing", +] +license = "MIT" +repository = "https://gitlab.com/timvisee/version-compare" diff --git a/external/vendor/version-compare/LICENSE b/external/vendor/version-compare/LICENSE new file mode 100644 index 0000000000..4a49e788b1 --- /dev/null +++ b/external/vendor/version-compare/LICENSE @@ -0,0 +1,20 @@ +Copyright (c) 2017 Tim Visée + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. + diff --git a/external/vendor/version-compare/README.md b/external/vendor/version-compare/README.md new file mode 100644 index 0000000000..602992ffc5 --- /dev/null +++ b/external/vendor/version-compare/README.md @@ -0,0 +1,137 @@ +[![Build status on GitLab CI][gitlab-ci-master-badge]][gitlab-ci-link] +[![Crate version][crate-version-badge]][crate-link] +[![Documentation][docs-badge]][docs] +[![Download statistics][crate-download-badge]][crate-link] +[![Coverage status][coverage-badge]][coverage-link] +[![Dependencies][dependency-badge]][crate-link] +[![License][crate-license-badge]][crate-link] + +[coverage-badge]: https://gitlab.com/timvisee/version-compare/badges/master/coverage.svg +[coverage-link]: https://coveralls.io/gitlab/timvisee/version-compare +[crate-download-badge]: https://img.shields.io/crates/d/version-compare.svg +[crate-license-badge]: https://img.shields.io/crates/l/version-compare.svg +[crate-link]: https://crates.io/crates/version-compare +[crate-version-badge]: https://img.shields.io/crates/v/version-compare.svg +[dependency-badge]: https://img.shields.io/badge/dependencies-none!-green.svg +[docs-badge]: https://img.shields.io/docsrs/version-compare +[docs]: https://docs.rs/version-compare +[gitlab-ci-link]: https://gitlab.com/timvisee/version-compare/pipelines +[gitlab-ci-master-badge]: https://gitlab.com/timvisee/version-compare/badges/master/pipeline.svg + +# Rust library: version-compare + +> Rust library to easily compare version numbers with no specific format, and test against various comparison operators. + +Comparing version numbers is hard, especially with weird version number formats. + +This library helps you to easily compare any kind of version number with no +specific format using a best-effort approach. +Two version numbers can be compared to each other to get a comparison operator +(`<`, `==`, `>`), or test them against a comparison operator. + +Along with version comparison, the library provides various other tools for +working with version numbers. + +Inspired by PHPs [version_compare()](http://php.net/manual/en/function.version-compare.php). + +_Note: Still a work in progress. Configurability is currently very limited. Things will change._ + +### Formats + +Version numbers that would parse successfully include: +`1`, `3.10.4.1`, `1.2.alpha`, `1.2.dev.4`, ` `, ` . -32 . 1`, `MyApp 3.2.0 / build 0932` ... + +See a list of how version numbers compare [here](https://github.com/timvisee/version-compare/blob/411ed7135741ed7cf2fcf4919012fb5412dc122b/src/test.rs#L50-L103). + +## Example + +This library is very easy to use. Here's a basic usage example: + +`Cargo.toml`: +```toml +[dependencies] +version-compare = "0.1" +``` + +[`example.rs`](examples/example.rs): +```rust +use version_compare::{compare, compare_to, Cmp, Version}; + +fn main() { + let a = "1.2"; + let b = "1.5.1"; + + // The following comparison operators are used: + // - Cmp::Eq -> Equal + // - Cmp::Ne -> Not equal + // - Cmp::Lt -> Less than + // - Cmp::Le -> Less than or equal + // - Cmp::Ge -> Greater than or equal + // - Cmp::Gt -> Greater than + + // Easily compare version strings + assert_eq!(compare(a, b), Ok(Cmp::Lt)); + assert_eq!(compare_to(a, b, Cmp::Le), Ok(true)); + assert_eq!(compare_to(a, b, Cmp::Gt), Ok(false)); + + // Parse and wrap version strings as a Version + let a = Version::from(a).unwrap(); + let b = Version::from(b).unwrap(); + + // The Version can easily be compared with + assert_eq!(a < b, true); + assert_eq!(a <= b, true); + assert_eq!(a > b, false); + assert_eq!(a != b, true); + assert_eq!(a.compare(&b), Cmp::Lt); + assert_eq!(a.compare_to(&b, Cmp::Lt), true); + + // Or match the comparison operators + match a.compare(b) { + Cmp::Lt => println!("Version a is less than b"), + Cmp::Eq => println!("Version a is equal to b"), + Cmp::Gt => println!("Version a is greater than b"), + _ => unreachable!(), + } +} +``` + +See the [`examples`](examples) directory for more. + +## Features + +* Compare version numbers, get: `<`, `==`, `>` +* Compare against a comparison operator + (`<`, `<=`, `==`, `!=`, `>=`, `>`) +* Parse complex and unspecified formats +* Static, standalone methods to easily compare version strings in a single line + of code + +#### Future ideas + +* Version ranges +* Support for [npm-style](https://semver.npmjs.com/) operators (e.g. `^1.0` or `~1.0`) +* Manifest: extend `Manifest` for to support a wide set of constraints +* Building blocks for building your own specific version number parser +* Batch comparisons + +#### Semver + +Version numbers using the [semver](http://semver.org/) format are compared +correctly with no additional configuration. + +If your version number strings follow this exact format you may be better off +using the [`semver`](https://crates.io/crates/semver) crate for more format +specific features. + +If that isn't certain however, `version-compare` makes comparing a breeze. + +## Builds + +This library is automatically build and tested every day and for each commit using CI services. + +See the current status here: https://gitlab.com/timvisee/version-compare/-/pipelines + +## License + +This project is released under the MIT license. Check out the [LICENSE](LICENSE) file for more information. diff --git a/external/vendor/version-compare/examples/example.rs b/external/vendor/version-compare/examples/example.rs new file mode 100644 index 0000000000..6859f062de --- /dev/null +++ b/external/vendor/version-compare/examples/example.rs @@ -0,0 +1,46 @@ +//! Usage examples of the version-compare crate. +//! +//! This shows various ways this library provides for comparing version numbers. +//! The `assert_eq!(...)` macros are used to assert and show the expected output. +//! +//! Run this example by invoking `cargo run --example example`. + +use version_compare::{compare, compare_to, Cmp, Version}; + +fn main() { + let a = "1.2"; + let b = "1.5.1"; + + // The following comparison operators are used: + // - Cmp::Eq -> Equal + // - Cmp::Ne -> Not equal + // - Cmp::Lt -> Less than + // - Cmp::Le -> Less than or equal + // - Cmp::Ge -> Greater than or equal + // - Cmp::Gt -> Greater than + + // Easily compare version strings + assert_eq!(compare(a, b), Ok(Cmp::Lt)); + assert_eq!(compare_to(a, b, Cmp::Le), Ok(true)); + assert_eq!(compare_to(a, b, Cmp::Gt), Ok(false)); + + // Parse and wrap version strings as a Version + let a = Version::from(a).unwrap(); + let b = Version::from(b).unwrap(); + + // The Version can easily be compared with + assert_eq!(a < b, true); + assert_eq!(a <= b, true); + assert_eq!(a > b, false); + assert_eq!(a != b, true); + assert_eq!(a.compare(&b), Cmp::Lt); + assert_eq!(a.compare_to(&b, Cmp::Lt), true); + + // Or match the comparison operators + match a.compare(b) { + Cmp::Lt => println!("Version a is less than b"), + Cmp::Eq => println!("Version a is equal to b"), + Cmp::Gt => println!("Version a is greater than b"), + _ => unreachable!(), + } +} diff --git a/external/vendor/version-compare/examples/minimal.rs b/external/vendor/version-compare/examples/minimal.rs new file mode 100644 index 0000000000..37413c80bd --- /dev/null +++ b/external/vendor/version-compare/examples/minimal.rs @@ -0,0 +1,19 @@ +//! A minimal usage example of the version-compare crate. +//! +//! This compares two given version number strings, and outputs which is greater. +//! +//! Run this example by invoking `cargo run --example minimal`. + +use version_compare::{compare, Cmp}; + +fn main() { + let a = "1.3"; + let b = "1.2.4"; + + match compare(a, b) { + Ok(Cmp::Lt) => println!("Version a is less than b"), + Ok(Cmp::Eq) => println!("Version a is equal to b"), + Ok(Cmp::Gt) => println!("Version a is greater than b"), + _ => panic!("Invalid version number"), + } +} diff --git a/external/vendor/version-compare/src/cmp.rs b/external/vendor/version-compare/src/cmp.rs new file mode 100644 index 0000000000..1e3ef2f5f4 --- /dev/null +++ b/external/vendor/version-compare/src/cmp.rs @@ -0,0 +1,436 @@ +//! Module with all supported comparison operators. +//! +//! This module provides an enum with all comparison operators that can be used with this library. +//! The enum provides various useful helper functions to inverse or flip an operator. +//! +//! Methods like `Cmp::from_sign(">");` can be used to get a comparison operator by it's logical +//! sign from a string. + +use std::cmp::Ordering; + +/// Comparison operators enum. +#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)] +pub enum Cmp { + /// Equal (`==`, `=`). + /// When version `A` is equal to `B`. + Eq, + + /// Not equal (`!=`, `!`, `<>`). + /// When version `A` is not equal to `B`. + Ne, + + /// Less than (`<`). + /// When version `A` is less than `B` but not equal. + Lt, + + /// Less or equal (`<=`). + /// When version `A` is less than or equal to `B`. + Le, + + /// Greater or equal (`>=`). + /// When version `A` is greater than or equal to `B`. + Ge, + + /// Greater than (`>`). + /// When version `A` is greater than `B` but not equal. + Gt, +} + +impl Cmp { + /// Get a comparison operator by it's sign. + /// Whitespaces are stripped from the sign string. + /// An error is returned if the sign isn't recognized. + /// + /// The following signs are supported: + /// + /// * `==` _or_ `=` -> `Eq` + /// * `!=` _or_ `!` _or_ `<>` -> `Ne` + /// * `< ` -> `Lt` + /// * `<=` -> `Le` + /// * `>=` -> `Ge` + /// * `> ` -> `Gt` + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::from_sign("=="), Ok(Cmp::Eq)); + /// assert_eq!(Cmp::from_sign("<"), Ok(Cmp::Lt)); + /// assert_eq!(Cmp::from_sign(" >= "), Ok(Cmp::Ge)); + /// assert!(Cmp::from_sign("*").is_err()); + /// ``` + #[allow(clippy::result_map_unit_fn)] + pub fn from_sign>(sign: S) -> Result { + match sign.as_ref().trim() { + "==" | "=" => Ok(Cmp::Eq), + "!=" | "!" | "<>" => Ok(Cmp::Ne), + "<" => Ok(Cmp::Lt), + "<=" => Ok(Cmp::Le), + ">=" => Ok(Cmp::Ge), + ">" => Ok(Cmp::Gt), + _ => Err(()), + } + } + + /// Get a comparison operator by it's name. + /// Names are case-insensitive, and whitespaces are stripped from the string. + /// An error is returned if the name isn't recognized. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::from_name("eq"), Ok(Cmp::Eq)); + /// assert_eq!(Cmp::from_name("lt"), Ok(Cmp::Lt)); + /// assert_eq!(Cmp::from_name(" Ge "), Ok(Cmp::Ge)); + /// assert!(Cmp::from_name("abc").is_err()); + /// ``` + #[allow(clippy::result_map_unit_fn)] + pub fn from_name>(sign: S) -> Result { + match sign.as_ref().trim().to_lowercase().as_str() { + "eq" => Ok(Cmp::Eq), + "ne" => Ok(Cmp::Ne), + "lt" => Ok(Cmp::Lt), + "le" => Ok(Cmp::Le), + "ge" => Ok(Cmp::Ge), + "gt" => Ok(Cmp::Gt), + _ => Err(()), + } + } + + /// Get the comparison operator from Rusts `Ordering` enum. + /// + /// The following comparison operators are returned: + /// + /// * `Ordering::Less` -> `Lt` + /// * `Ordering::Equal` -> `Eq` + /// * `Ordering::Greater` -> `Gt` + pub fn from_ord(ord: Ordering) -> Cmp { + match ord { + Ordering::Less => Cmp::Lt, + Ordering::Equal => Cmp::Eq, + Ordering::Greater => Cmp::Gt, + } + } + + /// Get the name of this comparison operator. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::Eq.name(), "eq"); + /// assert_eq!(Cmp::Lt.name(), "lt"); + /// assert_eq!(Cmp::Ge.name(), "ge"); + /// ``` + pub fn name<'a>(self) -> &'a str { + match self { + Cmp::Eq => "eq", + Cmp::Ne => "ne", + Cmp::Lt => "lt", + Cmp::Le => "le", + Cmp::Ge => "ge", + Cmp::Gt => "gt", + } + } + + /// Get the inverted comparison operator. + /// + /// This uses the following bidirectional rules: + /// + /// * `Eq` <-> `Ne` + /// * `Lt` <-> `Ge` + /// * `Le` <-> `Gt` + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::Eq.invert(), Cmp::Ne); + /// assert_eq!(Cmp::Lt.invert(), Cmp::Ge); + /// assert_eq!(Cmp::Gt.invert(), Cmp::Le); + /// ``` + #[must_use] + pub fn invert(self) -> Self { + match self { + Cmp::Eq => Cmp::Ne, + Cmp::Ne => Cmp::Eq, + Cmp::Lt => Cmp::Ge, + Cmp::Le => Cmp::Gt, + Cmp::Ge => Cmp::Lt, + Cmp::Gt => Cmp::Le, + } + } + + /// Get the opposite comparison operator. + /// + /// This uses the following bidirectional rules: + /// + /// * `Eq` <-> `Ne` + /// * `Lt` <-> `Gt` + /// * `Le` <-> `Ge` + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::Eq.opposite(), Cmp::Ne); + /// assert_eq!(Cmp::Lt.opposite(), Cmp::Gt); + /// assert_eq!(Cmp::Ge.opposite(), Cmp::Le); + /// ``` + #[must_use] + pub fn opposite(self) -> Self { + match self { + Cmp::Eq => Cmp::Ne, + Cmp::Ne => Cmp::Eq, + Cmp::Lt => Cmp::Gt, + Cmp::Le => Cmp::Ge, + Cmp::Ge => Cmp::Le, + Cmp::Gt => Cmp::Lt, + } + } + + /// Get the flipped comparison operator. + /// + /// This uses the following bidirectional rules: + /// + /// * `Lt` <-> `Gt` + /// * `Le` <-> `Ge` + /// * Other operators are returned as is. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::Eq.flip(), Cmp::Eq); + /// assert_eq!(Cmp::Lt.flip(), Cmp::Gt); + /// assert_eq!(Cmp::Ge.flip(), Cmp::Le); + /// ``` + #[must_use] + pub fn flip(self) -> Self { + match self { + Cmp::Lt => Cmp::Gt, + Cmp::Le => Cmp::Ge, + Cmp::Ge => Cmp::Le, + Cmp::Gt => Cmp::Lt, + _ => self, + } + } + + /// Get the sign for this comparison operator. + /// + /// The following signs are returned: + /// + /// * `Eq` -> `==` + /// * `Ne` -> `!=` + /// * `Lt` -> `< ` + /// * `Le` -> `<=` + /// * `Ge` -> `>=` + /// * `Gt` -> `> ` + /// + /// Note: Some comparison operators also support other signs, + /// such as `=` for `Eq` and `!` for `Ne`, + /// these are never returned by this method however as the table above is used. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Cmp; + /// + /// assert_eq!(Cmp::Eq.sign(), "=="); + /// assert_eq!(Cmp::Lt.sign(), "<"); + /// assert_eq!(Cmp::Ge.flip().sign(), "<="); + /// ``` + pub fn sign(self) -> &'static str { + match self { + Cmp::Eq => "==", + Cmp::Ne => "!=", + Cmp::Lt => "<", + Cmp::Le => "<=", + Cmp::Ge => ">=", + Cmp::Gt => ">", + } + } + + /// Get a factor (number) for this comparison operator. + /// These factors can be useful for quick calculations. + /// + /// The following factor numbers are returned: + /// + /// * `Eq` _or_ `Ne` -> ` 0` + /// * `Lt` _or_ `Le` -> `-1` + /// * `Gt` _or_ `Ge` -> ` 1` + /// + /// # Examples + /// + /// ``` + /// use version_compare::Version; + /// + /// let a = Version::from("1.2.3").unwrap(); + /// let b = Version::from("1.3").unwrap(); + /// + /// assert_eq!(a.compare(&b).factor(), -1); + /// assert_eq!(10 * b.compare(a).factor(), 10); + /// ``` + pub fn factor(self) -> i8 { + match self { + Cmp::Eq | Cmp::Ne => 0, + Cmp::Lt | Cmp::Le => -1, + Cmp::Gt | Cmp::Ge => 1, + } + } + + /// Get Rust's ordering for this comparison operator. + /// + /// The following comparison operators are supported: + /// + /// * `Eq` -> `Ordering::Equal` + /// * `Lt` -> `Ordering::Less` + /// * `Gt` -> `Ordering::Greater` + /// + /// For other comparison operators `None` is returned. + /// + /// # Examples + /// + /// ``` + /// use std::cmp::Ordering; + /// use version_compare::Version; + /// + /// let a = Version::from("1.2.3").unwrap(); + /// let b = Version::from("1.3").unwrap(); + /// + /// assert_eq!(a.compare(b).ord().unwrap(), Ordering::Less); + /// ``` + pub fn ord(self) -> Option { + match self { + Cmp::Eq => Some(Ordering::Equal), + Cmp::Lt => Some(Ordering::Less), + Cmp::Gt => Some(Ordering::Greater), + _ => None, + } + } +} + +#[cfg_attr(tarpaulin, skip)] +#[cfg(test)] +mod tests { + use std::cmp::Ordering; + + use super::Cmp; + + #[test] + fn from_sign() { + // Normal signs + assert_eq!(Cmp::from_sign("==").unwrap(), Cmp::Eq); + assert_eq!(Cmp::from_sign("=").unwrap(), Cmp::Eq); + assert_eq!(Cmp::from_sign("!=").unwrap(), Cmp::Ne); + assert_eq!(Cmp::from_sign("!").unwrap(), Cmp::Ne); + assert_eq!(Cmp::from_sign("<>").unwrap(), Cmp::Ne); + assert_eq!(Cmp::from_sign("<").unwrap(), Cmp::Lt); + assert_eq!(Cmp::from_sign("<=").unwrap(), Cmp::Le); + assert_eq!(Cmp::from_sign(">=").unwrap(), Cmp::Ge); + assert_eq!(Cmp::from_sign(">").unwrap(), Cmp::Gt); + + // Exceptional cases + assert_eq!(Cmp::from_sign(" <= ").unwrap(), Cmp::Le); + assert_eq!(Cmp::from_sign("*"), Err(())); + } + + #[test] + fn from_name() { + // Normal names + assert_eq!(Cmp::from_name("eq").unwrap(), Cmp::Eq); + assert_eq!(Cmp::from_name("ne").unwrap(), Cmp::Ne); + assert_eq!(Cmp::from_name("lt").unwrap(), Cmp::Lt); + assert_eq!(Cmp::from_name("le").unwrap(), Cmp::Le); + assert_eq!(Cmp::from_name("ge").unwrap(), Cmp::Ge); + assert_eq!(Cmp::from_name("gt").unwrap(), Cmp::Gt); + + // Exceptional cases + assert_eq!(Cmp::from_name(" Le ").unwrap(), Cmp::Le); + assert_eq!(Cmp::from_name("abc"), Err(())); + } + + #[test] + fn from_ord() { + assert_eq!(Cmp::from_ord(Ordering::Less), Cmp::Lt); + assert_eq!(Cmp::from_ord(Ordering::Equal), Cmp::Eq); + assert_eq!(Cmp::from_ord(Ordering::Greater), Cmp::Gt); + } + + #[test] + fn name() { + assert_eq!(Cmp::Eq.name(), "eq"); + assert_eq!(Cmp::Ne.name(), "ne"); + assert_eq!(Cmp::Lt.name(), "lt"); + assert_eq!(Cmp::Le.name(), "le"); + assert_eq!(Cmp::Ge.name(), "ge"); + assert_eq!(Cmp::Gt.name(), "gt"); + } + + #[test] + fn invert() { + assert_eq!(Cmp::Ne.invert(), Cmp::Eq); + assert_eq!(Cmp::Eq.invert(), Cmp::Ne); + assert_eq!(Cmp::Ge.invert(), Cmp::Lt); + assert_eq!(Cmp::Gt.invert(), Cmp::Le); + assert_eq!(Cmp::Lt.invert(), Cmp::Ge); + assert_eq!(Cmp::Le.invert(), Cmp::Gt); + } + + #[test] + fn opposite() { + assert_eq!(Cmp::Eq.opposite(), Cmp::Ne); + assert_eq!(Cmp::Ne.opposite(), Cmp::Eq); + assert_eq!(Cmp::Lt.opposite(), Cmp::Gt); + assert_eq!(Cmp::Le.opposite(), Cmp::Ge); + assert_eq!(Cmp::Ge.opposite(), Cmp::Le); + assert_eq!(Cmp::Gt.opposite(), Cmp::Lt); + } + + #[test] + fn flip() { + assert_eq!(Cmp::Eq.flip(), Cmp::Eq); + assert_eq!(Cmp::Ne.flip(), Cmp::Ne); + assert_eq!(Cmp::Lt.flip(), Cmp::Gt); + assert_eq!(Cmp::Le.flip(), Cmp::Ge); + assert_eq!(Cmp::Ge.flip(), Cmp::Le); + assert_eq!(Cmp::Gt.flip(), Cmp::Lt); + } + + #[test] + fn sign() { + assert_eq!(Cmp::Eq.sign(), "=="); + assert_eq!(Cmp::Ne.sign(), "!="); + assert_eq!(Cmp::Lt.sign(), "<"); + assert_eq!(Cmp::Le.sign(), "<="); + assert_eq!(Cmp::Ge.sign(), ">="); + assert_eq!(Cmp::Gt.sign(), ">"); + } + + #[test] + fn factor() { + assert_eq!(Cmp::Eq.factor(), 0); + assert_eq!(Cmp::Ne.factor(), 0); + assert_eq!(Cmp::Lt.factor(), -1); + assert_eq!(Cmp::Le.factor(), -1); + assert_eq!(Cmp::Ge.factor(), 1); + assert_eq!(Cmp::Gt.factor(), 1); + } + + #[test] + fn ord() { + assert_eq!(Cmp::Eq.ord(), Some(Ordering::Equal)); + assert_eq!(Cmp::Ne.ord(), None); + assert_eq!(Cmp::Lt.ord(), Some(Ordering::Less)); + assert_eq!(Cmp::Le.ord(), None); + assert_eq!(Cmp::Ge.ord(), None); + assert_eq!(Cmp::Gt.ord(), Some(Ordering::Greater)); + } +} diff --git a/external/vendor/version-compare/src/compare.rs b/external/vendor/version-compare/src/compare.rs new file mode 100644 index 0000000000..e42ab92e0e --- /dev/null +++ b/external/vendor/version-compare/src/compare.rs @@ -0,0 +1,122 @@ +//! Version compare module, with useful static comparison methods. + +use crate::version::Version; +use crate::Cmp; + +/// Compare two version number strings to each other. +/// +/// This compares version `a` to version `b`, and returns whether version `a` is greater, less +/// or equal to version `b`. +/// +/// If either version number string is invalid an error is returned. +/// +/// One of the following operators is returned: +/// +/// * `Cmp::Eq` +/// * `Cmp::Lt` +/// * `Cmp::Gt` +/// +/// # Examples +/// +/// ``` +/// use version_compare::{Cmp, compare}; +/// +/// assert_eq!(compare("1.2.3", "1.2.3"), Ok(Cmp::Eq)); +/// assert_eq!(compare("1.2.3", "1.2.4"), Ok(Cmp::Lt)); +/// assert_eq!(compare("1", "0.1"), Ok(Cmp::Gt)); +/// ``` +#[allow(clippy::result_map_unit_fn)] +pub fn compare(a: A, b: B) -> Result +where + A: AsRef, + B: AsRef, +{ + let a = Version::from(a.as_ref()).ok_or(())?; + let b = Version::from(b.as_ref()).ok_or(())?; + Ok(a.compare(b)) +} + +/// Compare two version number strings to each other and test against the given comparison +/// `operator`. +/// +/// If either version number string is invalid an error is returned. +/// +/// # Examples +/// +/// ``` +/// use version_compare::{Cmp, compare_to}; +/// +/// assert!(compare_to("1.2.3", "1.2.3", Cmp::Eq).unwrap()); +/// assert!(compare_to("1.2.3", "1.2.3", Cmp::Le).unwrap()); +/// assert!(compare_to("1.2.3", "1.2.4", Cmp::Lt).unwrap()); +/// assert!(compare_to("1", "0.1", Cmp::Gt).unwrap()); +/// assert!(compare_to("1", "0.1", Cmp::Ge).unwrap()); +/// ``` +#[allow(clippy::result_map_unit_fn)] +pub fn compare_to(a: A, b: B, operator: Cmp) -> Result +where + A: AsRef, + B: AsRef, +{ + let a = Version::from(a.as_ref()).ok_or(())?; + let b = Version::from(b.as_ref()).ok_or(())?; + Ok(a.compare_to(b, operator)) +} + +#[cfg_attr(tarpaulin, skip)] +#[cfg(test)] +mod tests { + use crate::test::{COMBIS, COMBIS_ERROR}; + use crate::Cmp; + + #[test] + fn compare() { + // Compare each version in the version set + for entry in COMBIS { + assert_eq!( + super::compare(entry.0, entry.1), + Ok(entry.2), + "Testing that {} is {} {}", + entry.0, + entry.2.sign(), + entry.1, + ); + } + + // Compare each error version in the version set + for entry in COMBIS_ERROR { + let result = super::compare(entry.0, entry.1); + + if result.is_ok() { + assert!(result != Ok(entry.2)); + } + } + } + + #[test] + fn compare_to() { + // Compare each version in the version set + for entry in COMBIS { + // Test + assert!(super::compare_to(entry.0, entry.1, entry.2).unwrap()); + + // Make sure the inverse operator is not correct + assert_eq!( + super::compare_to(entry.0, entry.1, entry.2.invert()).unwrap(), + false, + ); + } + + // Compare each error version in the version set + for entry in COMBIS_ERROR { + let result = super::compare_to(entry.0, entry.1, entry.2); + + if result.is_ok() { + assert!(!result.unwrap()) + } + } + + // Assert an exceptional case, compare to not equal + assert!(super::compare_to("1.2.3", "1.2", Cmp::Ne).unwrap()); + } +} diff --git a/external/vendor/version-compare/src/lib.rs b/external/vendor/version-compare/src/lib.rs new file mode 100644 index 0000000000..c7d3596172 --- /dev/null +++ b/external/vendor/version-compare/src/lib.rs @@ -0,0 +1,103 @@ +//! Rust library to easily compare version numbers with no specific format, and test against various comparison operators. +//! +//! Comparing version numbers is hard, especially with weird version number formats. +//! +//! This library helps you to easily compare any kind of version number with no +//! specific format using a best-effort approach. +//! Two version numbers can be compared to each other to get a comparison operator +//! (`<`, `==`, `>`), or test them against a comparison operator. +//! +//! Along with version comparison, the library provides various other tools for +//! working with version numbers. +//! +//! Inspired by PHPs [version_compare()](http://php.net/manual/en/function.version-compare.php). +//! +//! ### Formats +//! +//! Version numbers that would parse successfully include: +//! `1`, `3.10.4.1`, `1.2.alpha`, `1.2.dev.4`, ` `, ` . -32 . 1`, `MyApp 3.2.0 / build 0932` ... +//! +//! See a list of how version numbers compare [here](https://github.com/timvisee/version-compare/blob/411ed7135741ed7cf2fcf4919012fb5412dc122b/src/test.rs#L50-L103). +//! +//! ## Examples +//! +//! [example.rs](examples/example.rs): +//! ```rust +//! use version_compare::{compare, compare_to, Cmp, Version}; +//! +//! let a = "1.2"; +//! let b = "1.5.1"; +//! +//! // The following comparison operators are used: +//! // - Cmp::Eq -> Equal +//! // - Cmp::Ne -> Not equal +//! // - Cmp::Lt -> Less than +//! // - Cmp::Le -> Less than or equal +//! // - Cmp::Ge -> Greater than or equal +//! // - Cmp::Gt -> Greater than +//! +//! // Easily compare version strings +//! assert_eq!(compare(a, b), Ok(Cmp::Lt)); +//! assert_eq!(compare_to(a, b, Cmp::Le), Ok(true)); +//! assert_eq!(compare_to(a, b, Cmp::Gt), Ok(false)); +//! +//! // Parse and wrap version strings as a Version +//! let a = Version::from(a).unwrap(); +//! let b = Version::from(b).unwrap(); +//! +//! // The Version can easily be compared with +//! assert_eq!(a < b, true); +//! assert_eq!(a <= b, true); +//! assert_eq!(a > b, false); +//! assert_eq!(a != b, true); +//! assert_eq!(a.compare(&b), Cmp::Lt); +//! assert_eq!(a.compare_to(&b, Cmp::Lt), true); +//! +//! // Or match the comparison operators +//! match a.compare(b) { +//! Cmp::Lt => println!("Version a is less than b"), +//! Cmp::Eq => println!("Version a is equal to b"), +//! Cmp::Gt => println!("Version a is greater than b"), +//! _ => unreachable!(), +//! } +//! ``` +//! +//! See the [`examples`](https://github.com/timvisee/version-compare/tree/master/examples) directory for more. +//! +//! ## Features +//! +//! * Compare version numbers, get: `<`, `==`, `>` +//! * Compare against a comparison operator +//! (`<`, `<=`, `==`, `!=`, `>=`, `>`) +//! * Parse complex and unspecified formats +//! * Static, standalone methods to easily compare version strings in a single line +//! of code +//! +//! ### Semver +//! +//! Version numbers using the [semver](http://semver.org/) format are compared +//! correctly with no additional configuration. +//! +//! If your version number strings follow this exact format you may be better off +//! using the [`semver`](https://crates.io/crates/semver) crate for more format +//! specific features. +//! +//! If that isn't certain however, `version-compare` makes comparing a breeze. +//! +//! _[View complete README](https://github.com/timvisee/version-compare/blob/master/README.md)_ + +mod cmp; +mod compare; +mod manifest; +mod part; +mod version; + +#[cfg(test)] +mod test; + +// Re-exports +pub use crate::cmp::Cmp; +pub use crate::compare::{compare, compare_to}; +pub use crate::manifest::Manifest; +pub use crate::part::Part; +pub use crate::version::Version; diff --git a/external/vendor/version-compare/src/manifest.rs b/external/vendor/version-compare/src/manifest.rs new file mode 100644 index 0000000000..2dc347dbd3 --- /dev/null +++ b/external/vendor/version-compare/src/manifest.rs @@ -0,0 +1,76 @@ +//! Module for the version manifest. +//! +//! A version manifest can be used to configure and specify how versions are parsed and compared. +//! For example, you can configure the maximum depth of a version number, and set whether text +//! parts are ignored in a version string. + +/// Version manifest (configuration). +/// +/// A manifest (configuration) that is used respectively when parsing and comparing version strings. +/// +/// # Examples +/// +/// ```rust +/// use version_compare::{Manifest, Version}; +/// +/// // Create manifest with max depth of 2 +/// let mut manifest = Manifest::default(); +/// manifest.max_depth = Some(2); +/// +/// // Version strings equal with manifest because we compare up-to 2 parts deep +/// let a = Version::from_manifest("1.0.1", &manifest).unwrap(); +/// let b = Version::from_manifest("1.0.2", &manifest).unwrap(); +/// assert!(a == b); +/// ``` + +#[derive(Debug, Clone, PartialEq, Eq, Default)] +pub struct Manifest { + /// The maximum depth of a version number. + /// + /// This specifies the maximum number of parts. There is no limit if `None` is set. + pub max_depth: Option, + + /// Whether to ignore text parts in version strings. + pub ignore_text: bool, +} + +/// Version manifest implementation. +impl Manifest { + /// Check whether there's a maximum configured depth. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Manifest; + /// + /// let mut manifest = Manifest::default(); + /// + /// assert!(!manifest.has_max_depth()); + /// + /// manifest.max_depth = Some(3); + /// assert!(manifest.has_max_depth()); + /// ``` + pub fn has_max_depth(&self) -> bool { + self.max_depth.is_some() && self.max_depth.unwrap() > 0 + } +} + +#[cfg_attr(tarpaulin, skip)] +#[cfg(test)] +mod tests { + use super::Manifest; + + #[test] + fn has_max_depth() { + let mut manifest = Manifest::default(); + + manifest.max_depth = Some(1); + assert!(manifest.has_max_depth()); + + manifest.max_depth = Some(3); + assert!(manifest.has_max_depth()); + + manifest.max_depth = None; + assert!(!manifest.has_max_depth()); + } +} diff --git a/external/vendor/version-compare/src/part.rs b/external/vendor/version-compare/src/part.rs new file mode 100644 index 0000000000..ecfac32d02 --- /dev/null +++ b/external/vendor/version-compare/src/part.rs @@ -0,0 +1,44 @@ +//! Version part module. +//! +//! A module that provides the `Part` enum, with the specification of all available version +//! parts. Each version string is broken down into these version parts when being parsed to a +//! `Version`. + +use std::fmt; + +/// Version string part enum. +/// +/// Each version string is broken down into these version parts when being parsed to a `Version`. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Part<'a> { + /// Numeric part, most common in version strings. + /// + /// Holds the numerical value. + Number(i32), + + /// A text part. + /// + /// These parts usually hold text with an yet unknown definition. Holds the string slice. + Text(&'a str), +} + +impl<'a> fmt::Display for Part<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + Part::Number(n) => write!(f, "{}", n), + Part::Text(t) => write!(f, "{}", t), + } + } +} + +#[cfg_attr(tarpaulin, skip)] +#[cfg(test)] +mod tests { + use super::Part; + + #[test] + fn display() { + assert_eq!(format!("{}", Part::Number(123)), "123"); + assert_eq!(format!("{}", Part::Text("123")), "123"); + } +} diff --git a/external/vendor/version-compare/src/test.rs b/external/vendor/version-compare/src/test.rs new file mode 100644 index 0000000000..ff4ac32238 --- /dev/null +++ b/external/vendor/version-compare/src/test.rs @@ -0,0 +1,116 @@ +use crate::Cmp; + +/// Struct containing a version number with some meta data. +/// Such a set can be used for testing. +/// +/// # Arguments +/// +/// - `0`: The version string. +/// - `1`: Number of version parts. +pub struct Version(pub &'static str, pub usize); + +/// List of version numbers with metadata for dynamic tests +pub const VERSIONS: &'static [Version] = &[ + Version("1", 1), + Version("1.2", 2), + Version("1.2.3.4", 4), + Version("1.2.3.4.5.6.7.8", 8), + Version("0", 1), + Version("0.0.0", 3), + Version("1.0.0", 3), + Version("0.0.1", 3), + Version("", 0), + Version(".", 0), + Version("...", 0), + Version("1.2.dev", 3), + Version("1.2-dev", 3), + Version("1.2.alpha.4", 4), + Version("1.2-alpha-4", 4), + Version("snapshot.1.2", 3), + Version("snapshot-1.2", 3), + // Issue: https://github.com/timvisee/version-compare/issues/26 + Version("0.0.1-test.0222426166a", 6), + Version("0.0.1-test.0222426166565421816516584651684351354", 5), + Version("0.0.1-test.02224261665a", 5), + Version("0.0.1-test.02224261665d7b1b689816d12f6bcacb", 5), +]; + +/// List of version numbers that contain errors with metadata for dynamic tests +pub const VERSIONS_ERROR: &'static [Version] = &[ + Version("abc", 1), + Version("alpha.dev.snapshot", 3), + Version("test. .snapshot", 3), +]; + +/// Struct containing two version numbers, and the comparison operator. +/// Such a set can be used for testing. +/// +/// # Arguments +/// +/// - `0`: The main version. +/// - `1`: The other version. +/// - `2`: The comparison operator. +pub struct VersionCombi(pub &'static str, pub &'static str, pub Cmp); + +/// List of version combinations for dynamic tests +pub const COMBIS: &'static [VersionCombi] = &[ + VersionCombi("1", "1", Cmp::Eq), + VersionCombi("1.0.0.0", "1", Cmp::Eq), + VersionCombi("1", "1.0.0.0", Cmp::Eq), + VersionCombi("0", "0", Cmp::Eq), + VersionCombi("0.0.0", "0", Cmp::Eq), + VersionCombi("0", "0.0.0", Cmp::Eq), + VersionCombi("", "", Cmp::Eq), + VersionCombi("", "0.0", Cmp::Eq), + VersionCombi("0.0", "", Cmp::Eq), + VersionCombi("", "0.1", Cmp::Lt), + VersionCombi("0.1", "", Cmp::Gt), + VersionCombi("1.2.3", "1.2.3", Cmp::Eq), + VersionCombi("1.2.3", "1.2.4", Cmp::Lt), + VersionCombi("1.0.0.1", "1.0.0.0", Cmp::Gt), + VersionCombi("1.0.0.0", "1.0.0.1", Cmp::Lt), + VersionCombi("1.2.3.4", "1.2", Cmp::Gt), + VersionCombi("1.2", "1.2.3.4", Cmp::Lt), + VersionCombi("1.2.3.4", "2", Cmp::Lt), + VersionCombi("2", "1.2.3.4", Cmp::Gt), + VersionCombi("123", "123", Cmp::Eq), + VersionCombi("123", "1.2.3", Cmp::Gt), + VersionCombi("1.2.3", "123", Cmp::Lt), + VersionCombi("1.1.2", "1.1.30-dev", Cmp::Lt), + VersionCombi("1.2.3", "1.2.3.alpha", Cmp::Gt), + VersionCombi("1.2.3", "1.2.3-dev", Cmp::Gt), + VersionCombi("1.2.3 RC0", "1.2.3 rc1", Cmp::Lt), + VersionCombi("1.2.3 rc2", "1.2.3 RC99", Cmp::Lt), + VersionCombi("1.2.3 RC3", "1.2.3 RC1", Cmp::Gt), + VersionCombi("1.2.3a", "1.2.3b", Cmp::Lt), + VersionCombi("1.2.3b", "1.2.3a", Cmp::Gt), + VersionCombi("1.2.3.dev", "1.2.3.alpha", Cmp::Gt), + VersionCombi("1.2.3-dev", "1.2.3-alpha", Cmp::Gt), + VersionCombi("1.2.3.dev.1", "1.2.3.alpha", Cmp::Gt), + VersionCombi("1.2.3-dev-1", "1.2.3-alpha", Cmp::Gt), + VersionCombi("version-compare 3.2.0 / build 0932", "3.2.5", Cmp::Lt), + VersionCombi("version-compare 3.2.0 / build 0932", "3.1.1", Cmp::Gt), + VersionCombi( + "version-compare 1.4.1 / build 0043", + "version-compare 1.4.1 / build 0043", + Cmp::Eq, + ), + VersionCombi( + "version-compare 1.4.1 / build 0042", + "version-compare 1.4.1 / build 0043", + Cmp::Lt, + ), + // Issue: https://github.com/timvisee/version-compare/issues/24 + VersionCombi("7.2p1", "7.1", Cmp::Gt), + // TODO: inspect these cases + VersionCombi("snapshot.1.2.3", "1.2.3.alpha", Cmp::Lt), + VersionCombi("snapshot-1.2.3", "1.2.3-alpha", Cmp::Lt), +]; + +/// List of invalid version combinations for dynamic tests +pub const COMBIS_ERROR: &'static [VersionCombi] = &[ + VersionCombi("1.2.3", "1.2.3", Cmp::Lt), + VersionCombi("1.2", "1.2.0.0", Cmp::Ne), + VersionCombi("1.2.3.dev", "dev", Cmp::Eq), + VersionCombi("snapshot", "1", Cmp::Lt), +]; diff --git a/external/vendor/version-compare/src/version.rs b/external/vendor/version-compare/src/version.rs new file mode 100644 index 0000000000..2dcb27cdac --- /dev/null +++ b/external/vendor/version-compare/src/version.rs @@ -0,0 +1,755 @@ +//! Version module, which provides the `Version` struct as parsed version representation. +//! +//! Version numbers in the form of a string are parsed to a `Version` first, before any comparison +//! is made. This struct provides many methods and features for easy comparison, probing and other +//! things. + +use std::borrow::Borrow; +use std::cmp::Ordering; +use std::fmt; +use std::iter::Peekable; +use std::slice::Iter; + +use crate::{Cmp, Manifest, Part}; + +/// Version struct, wrapping a string, providing useful comparison functions. +/// +/// A version in string format can be parsed using methods like `Version::from("1.2.3");`, +/// returning a `Result` with the parse result. +/// +/// The original version string can be accessed using `version.as_str()`. A `Version` that isn't +/// derrived from a version string returns a generated string. +/// +/// The struct provides many methods for easy comparison and probing. +/// +/// # Examples +/// +/// ``` +/// use version_compare::{Version}; +/// +/// let ver = Version::from("1.2.3").unwrap(); +/// ``` +#[derive(Clone, Eq)] +pub struct Version<'a> { + version: &'a str, + parts: Vec>, + manifest: Option<&'a Manifest>, +} + +impl<'a> Version<'a> { + /// Create a `Version` instance from a version string. + /// + /// The version string should be passed to the `version` parameter. + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Cmp, Version}; + /// + /// let a = Version::from("1.2.3").unwrap(); + /// let b = Version::from("1.3.0").unwrap(); + /// + /// assert_eq!(a.compare(b), Cmp::Lt); + /// ``` + pub fn from(version: &'a str) -> Option { + Some(Version { + version, + parts: split_version_str(version, None)?, + manifest: None, + }) + } + + /// Create a `Version` instance from already existing parts + /// + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Cmp, Version, Part}; + /// + /// let ver = Version::from_parts("1.0", vec![Part::Number(1), Part::Number(0)]); + /// ``` + pub fn from_parts(version: &'a str, parts: Vec>) -> Self { + Version { + version, + parts, + manifest: None, + } + } + + /// Create a `Version` instance from a version string with the given `manifest`. + /// + /// The version string should be passed to the `version` parameter. + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Cmp, Version, Manifest}; + /// + /// let manifest = Manifest::default(); + /// let ver = Version::from_manifest("1.2.3", &manifest).unwrap(); + /// + /// assert_eq!(ver.compare(Version::from("1.2.3").unwrap()), Cmp::Eq); + /// ``` + pub fn from_manifest(version: &'a str, manifest: &'a Manifest) -> Option { + Some(Version { + version, + parts: split_version_str(version, Some(manifest))?, + manifest: Some(manifest), + }) + } + + /// Get the version manifest, if available. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Version; + /// + /// let version = Version::from("1.2.3").unwrap(); + /// + /// if version.has_manifest() { + /// println!( + /// "Maximum version part depth is {} for this version", + /// version.manifest().unwrap().max_depth.unwrap_or(0), + /// ); + /// } else { + /// println!("Version has no manifest"); + /// } + /// ``` + pub fn manifest(&self) -> Option<&Manifest> { + self.manifest + } + + /// Check whether this version has a manifest. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Version; + /// + /// let version = Version::from("1.2.3").unwrap(); + /// + /// if version.has_manifest() { + /// println!("This version does have a manifest"); + /// } else { + /// println!("This version does not have a manifest"); + /// } + /// ``` + pub fn has_manifest(&self) -> bool { + self.manifest().is_some() + } + + /// Set the version manifest. + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Version, Manifest}; + /// + /// let manifest = Manifest::default(); + /// let mut version = Version::from("1.2.3").unwrap(); + /// + /// version.set_manifest(Some(&manifest)); + /// ``` + pub fn set_manifest(&mut self, manifest: Option<&'a Manifest>) { + self.manifest = manifest; + + // TODO: Re-parse the version string, because the manifest might have changed. + } + + /// Get the original version string. + /// + /// # Examples + /// + /// ``` + /// use version_compare::Version; + /// + /// let ver = Version::from("1.2.3").unwrap(); + /// + /// assert_eq!(ver.as_str(), "1.2.3"); + /// ``` + pub fn as_str(&self) -> &str { + self.version + } + + /// Get a specific version part by it's `index`. + /// An error is returned if the given index is out of bound. + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Version, Part}; + /// + /// let ver = Version::from("1.2.3").unwrap(); + /// + /// assert_eq!(ver.part(0), Ok(Part::Number(1))); + /// assert_eq!(ver.part(1), Ok(Part::Number(2))); + /// assert_eq!(ver.part(2), Ok(Part::Number(3))); + /// ``` + #[allow(clippy::result_map_unit_fn)] + pub fn part(&self, index: usize) -> Result, ()> { + // Make sure the index is in-bound + if index >= self.parts.len() { + return Err(()); + } + + Ok(self.parts[index]) + } + + /// Get a vector of all version parts. + /// + /// # Examples + /// + /// ``` + /// use version_compare::{Version, Part}; + /// + /// let ver = Version::from("1.2.3").unwrap(); + /// + /// assert_eq!(ver.parts(), [ + /// Part::Number(1), + /// Part::Number(2), + /// Part::Number(3) + /// ]); + /// ``` + pub fn parts(&self) -> &[Part<'a>] { + self.parts.as_slice() + } + + /// Compare this version to the given `other` version. + /// + /// This method returns one of the following comparison operators: + /// + /// * `Lt` + /// * `Eq` + /// * `Gt` + /// + /// Other comparison operators can be used when comparing, but aren't returned by this method. + /// + /// # Examples: + /// + /// ``` + /// use version_compare::{Cmp, Version}; + /// + /// let a = Version::from("1.2").unwrap(); + /// let b = Version::from("1.3.2").unwrap(); + /// + /// assert_eq!(a.compare(&b), Cmp::Lt); + /// assert_eq!(b.compare(&a), Cmp::Gt); + /// assert_eq!(a.compare(&a), Cmp::Eq); + /// ``` + pub fn compare(&self, other: V) -> Cmp + where + V: Borrow>, + { + compare_iter( + self.parts.iter().peekable(), + other.borrow().parts.iter().peekable(), + ) + } + + /// Compare this version to the given `other` version, + /// and check whether the given comparison operator is valid. + /// + /// All comparison operators can be used. + /// + /// # Examples: + /// + /// ``` + /// use version_compare::{Cmp, Version}; + /// + /// let a = Version::from("1.2").unwrap(); + /// let b = Version::from("1.3.2").unwrap(); + /// + /// assert!(a.compare_to(&b, Cmp::Lt)); + /// assert!(a.compare_to(&b, Cmp::Le)); + /// assert!(a.compare_to(&a, Cmp::Eq)); + /// assert!(a.compare_to(&a, Cmp::Le)); + /// ``` + pub fn compare_to(&self, other: V, operator: Cmp) -> bool + where + V: Borrow>, + { + match self.compare(other) { + Cmp::Eq => matches!(operator, Cmp::Eq | Cmp::Le | Cmp::Ge), + Cmp::Lt => matches!(operator, Cmp::Ne | Cmp::Lt | Cmp::Le), + Cmp::Gt => matches!(operator, Cmp::Ne | Cmp::Gt | Cmp::Ge), + _ => unreachable!(), + } + } +} + +impl<'a> fmt::Display for Version<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + write!(f, "{}", self.version) + } +} + +// Show just the version component parts as debug output +impl<'a> fmt::Debug for Version<'a> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + if f.alternate() { + write!(f, "{:#?}", self.parts) + } else { + write!(f, "{:?}", self.parts) + } + } +} + +/// Implement the partial ordering trait for the version struct, to easily allow version comparison. +impl<'a> PartialOrd for Version<'a> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.compare(other).ord().unwrap()) + } +} + +/// Implement the partial equality trait for the version struct, to easily allow version comparison. +impl<'a> PartialEq for Version<'a> { + fn eq(&self, other: &Self) -> bool { + self.compare_to(other, Cmp::Eq) + } +} + +/// Split the given version string, in it's version parts. +fn split_version_str<'a>( + version: &'a str, + manifest: Option<&'a Manifest>, +) -> Option>> { + // Split the version string, and create a vector to put the parts in + let split = version.split(|c| !char::is_alphanumeric(c)); + let mut parts = Vec::new(); + + // Get the manifest to follow + let mut used_manifest = &Manifest::default(); + if let Some(m) = manifest { + used_manifest = m; + } + + // Loop over the parts, and parse them + for part in split { + // We may not go over the maximum depth + if used_manifest.max_depth.is_some() && parts.len() >= used_manifest.max_depth.unwrap_or(0) + { + break; + } + + // Skip empty parts + if part.is_empty() { + continue; + } + + // Try to parse the value as an number + match part.parse::() { + Ok(number) => { + // Push the number part to the vector + parts.push(Part::Number(number)); + } + Err(_) => { + // Ignore text parts if specified + if used_manifest.ignore_text { + continue; + } + + // Numbers suffixed by text should be split into a number and text as well, + // if the number overflows, handle it as text + let split_at = part + .char_indices() + .take(part.len() - 1) + .take_while(|(_, c)| c.is_ascii_digit()) + .map(|(i, c)| (i, c, part.chars().nth(i + 1).unwrap())) + .filter(|(_, _, b)| b.is_alphabetic()) + .map(|(i, _, _)| i) + .next(); + if let Some(at) = split_at { + if let Ok(n) = part[..=at].parse() { + parts.push(Part::Number(n)); + parts.push(Part::Text(&part[at + 1..])); + } else { + parts.push(Part::Text(part)); + } + continue; + } + + // Push the text part to the vector + parts.push(Part::Text(part)) + } + } + } + + // The version must contain a number part if any part was parsed + if !parts.is_empty() && !parts.iter().any(|p| matches!(p, Part::Number(_))) { + return None; + } + + // Return the list of parts + Some(parts) +} + +/// Compare two version numbers based on the iterators of their version parts. +/// +/// This method returns one of the following comparison operators: +/// +/// * `Lt` +/// * `Eq` +/// * `Gt` +/// +/// Other comparison operators can be used when comparing, but aren't returned by this method. +fn compare_iter<'a>( + mut iter: Peekable>>, + mut other_iter: Peekable>>, +) -> Cmp { + // Iterate through the parts of this version + let mut other_part: Option<&Part>; + + // Iterate over the iterator, without consuming it + for part in &mut iter { + // Get the part for the other version + other_part = other_iter.next(); + + // If there are no parts left in the other version, try to determine the result + if other_part.is_none() { + // In the main version: if the current part is zero, continue to the next one + match part { + Part::Number(num) => { + if *num == 0 { + continue; + } + } + Part::Text(_) => return Cmp::Lt, + } + + // The main version is greater + return Cmp::Gt; + } + + // Match both parts as numbers to destruct their numerical values + if let Part::Number(num) = part { + if let Part::Number(other) = other_part.unwrap() { + // Compare the numbers + match num { + n if n < other => return Cmp::Lt, + n if n > other => return Cmp::Gt, + _ => continue, + } + } + } + // Match both parts as strings + else if let Part::Text(val) = part { + if let Part::Text(other_val) = other_part.unwrap() { + // normalize case + let (val_lwr, other_val_lwr) = (val.to_lowercase(), other_val.to_lowercase()); + // compare text: for instance, "RC1" will be less than "RC2", so this works out. + #[allow(clippy::comparison_chain)] + if val_lwr < other_val_lwr { + return Cmp::Lt; + } else if val_lwr > other_val_lwr { + return Cmp::Gt; + } + } + } + } + + // Check whether we should iterate over the other iterator, if it has any items left + match other_iter.peek() { + // Compare based on the other iterator + Some(_) => compare_iter(other_iter, iter).flip(), + + // Nothing more to iterate over, the versions should be equal + None => Cmp::Eq, + } +} + +#[cfg_attr(tarpaulin, skip)] +#[cfg(test)] +mod tests { + use std::cmp; + + use crate::test::{COMBIS, VERSIONS, VERSIONS_ERROR}; + use crate::{Cmp, Manifest, Part}; + + use super::Version; + + #[test] + // TODO: This doesn't really test whether this method fully works + fn from() { + // Test whether parsing works for each test version + for version in VERSIONS { + assert!(Version::from(version.0).is_some()); + } + + // Test whether parsing works for each test invalid version + for version in VERSIONS_ERROR { + assert!(Version::from(version.0).is_none()); + } + } + + #[test] + // TODO: This doesn't really test whether this method fully works + fn from_manifest() { + // Create a manifest + let manifest = Manifest::default(); + + // Test whether parsing works for each test version + for version in VERSIONS { + assert_eq!( + Version::from_manifest(version.0, &manifest) + .unwrap() + .manifest, + Some(&manifest) + ); + } + + // Test whether parsing works for each test invalid version + for version in VERSIONS_ERROR { + assert!(Version::from_manifest(version.0, &manifest).is_none()); + } + } + + #[test] + fn manifest() { + let manifest = Manifest::default(); + let mut version = Version::from("1.2.3").unwrap(); + + version.manifest = Some(&manifest); + assert_eq!(version.manifest(), Some(&manifest)); + + version.manifest = None; + assert_eq!(version.manifest(), None); + } + + #[test] + fn has_manifest() { + let manifest = Manifest::default(); + let mut version = Version::from("1.2.3").unwrap(); + + version.manifest = Some(&manifest); + assert!(version.has_manifest()); + + version.manifest = None; + assert!(!version.has_manifest()); + } + + #[test] + fn set_manifest() { + let manifest = Manifest::default(); + let mut version = Version::from("1.2.3").unwrap(); + + version.set_manifest(Some(&manifest)); + assert_eq!(version.manifest, Some(&manifest)); + + version.set_manifest(None); + assert_eq!(version.manifest, None); + } + + #[test] + fn as_str() { + // Test for each test version + for version in VERSIONS { + // The input version string must be the same as the returned string + assert_eq!(Version::from(version.0).unwrap().as_str(), version.0); + } + } + + #[test] + fn part() { + // Test for each test version + for version in VERSIONS { + // Create a version object + let ver = Version::from(version.0).unwrap(); + + // Loop through each part + for i in 0..version.1 { + assert_eq!(ver.part(i), Ok(ver.parts[i])); + } + + // A value outside the range must return an error + assert!(ver.part(version.1).is_err()); + } + } + + #[test] + fn parts() { + // Test for each test version + for version in VERSIONS { + // The number of parts must match + assert_eq!(Version::from(version.0).unwrap().parts().len(), version.1); + } + } + + #[test] + fn parts_max_depth() { + // Create a manifest + let mut manifest = Manifest::default(); + + // Loop through a range of numbers + for depth in 0..5 { + // Set the maximum depth + manifest.max_depth = if depth > 0 { Some(depth) } else { None }; + + // Test for each test version with the manifest + for version in VERSIONS { + // Create a version object, and count it's parts + let ver = Version::from_manifest(&version.0, &manifest); + + // Some versions might be none, because not all of the start with a number when the + // maximum depth is 1. A version string with only text isn't allowed, + // resulting in none. + if ver.is_none() { + continue; + } + + // Get the part count + let count = ver.unwrap().parts().len(); + + // The number of parts must match + if depth == 0 { + assert_eq!(count, version.1); + } else { + assert_eq!(count, cmp::min(version.1, depth)); + } + } + } + } + + #[test] + fn parts_ignore_text() { + // Create a manifest + let mut manifest = Manifest::default(); + + // Try this for true and false + for ignore in vec![true, false] { + // Set to ignore text + manifest.ignore_text = ignore; + + // Keep track whether any version passed with text + let mut had_text = false; + + // Test each test version + for version in VERSIONS { + // Create a version instance, and get it's parts + let ver = Version::from_manifest(&version.0, &manifest).unwrap(); + + // Loop through all version parts + for part in ver.parts() { + match part { + Part::Text(_) => { + // Set the flag + had_text = true; + + // Break the loop if we already reached text when not ignored + if !ignore { + break; + } + } + _ => {} + } + } + } + + // Assert had text + assert_eq!(had_text, !ignore); + } + } + + #[test] + fn compare() { + // Compare each version in the version set + for entry in COMBIS { + // Get both versions + let a = Version::from(entry.0).unwrap(); + let b = Version::from(entry.1).unwrap(); + + // Compare them + assert_eq!( + a.compare(b), + entry.2.clone(), + "Testing that {} is {} {}", + entry.0, + entry.2.sign(), + entry.1, + ); + } + } + + #[test] + fn compare_to() { + // Compare each version in the version set + for entry in COMBIS { + // Get both versions + let a = Version::from(entry.0).unwrap(); + let b = Version::from(entry.1).unwrap(); + + // Test normally and inverse + assert!(a.compare_to(&b, entry.2)); + assert!(!a.compare_to(b, entry.2.invert())); + } + + // Assert an exceptional case, compare to not equal + assert!(Version::from("1.2") + .unwrap() + .compare_to(Version::from("1.2.3").unwrap(), Cmp::Ne,)); + } + + #[test] + fn display() { + assert_eq!(format!("{}", Version::from("1.2.3").unwrap()), "1.2.3"); + } + + #[test] + fn debug() { + assert_eq!( + format!("{:?}", Version::from("1.2.3").unwrap()), + "[Number(1), Number(2), Number(3)]", + ); + assert_eq!( + format!("{:#?}", Version::from("1.2.3").unwrap()), + "[\n Number(\n 1,\n ),\n Number(\n 2,\n ),\n Number(\n 3,\n ),\n]", + ); + } + + #[test] + fn partial_cmp() { + // Compare each version in the version set + for entry in COMBIS { + // Get both versions + let a = Version::from(entry.0).unwrap(); + let b = Version::from(entry.1).unwrap(); + + // Compare and assert + match entry.2 { + Cmp::Eq => assert!(a == b), + Cmp::Lt => assert!(a < b), + Cmp::Gt => assert!(a > b), + _ => {} + } + } + } + + #[test] + fn partial_eq() { + // Compare each version in the version set + for entry in COMBIS { + // Skip entries that are less or equal, or greater or equal + match entry.2 { + Cmp::Le | Cmp::Ge => continue, + _ => {} + } + + // Get both versions + let a = Version::from(entry.0).unwrap(); + let b = Version::from(entry.1).unwrap(); + + // Determine what the result should be + let result = match entry.2 { + Cmp::Eq => true, + _ => false, + }; + + // Test + assert_eq!(a == b, result); + } + + // Assert an exceptional case, compare to not equal + assert!(Version::from("1.2").unwrap() != Version::from("1.2.3").unwrap()); + } +} diff --git a/src/rust/README.md b/src/rust/README.md index 2bec49f9d4..ca6fa4a49b 100644 --- a/src/rust/README.md +++ b/src/rust/README.md @@ -38,5 +38,18 @@ We generate one header file `rust.h` and ever product specific function is `#ifd # Vendoring -Run the vendoring script `vendor.sh` to vendor dependencies from crates.io. The -script will ensure that also rust std libs dependencies are vendored. +Run the vendoring script `vendor-rust.sh` to vendor dependencies from +crates.io. The script will ensure that also rust std libs dependencies are +vendored. + +If dependencies are updated, remember to also update in `test/simulator-ng`. You can use + +``` +cargo update --precise +``` + +to specify specific versions to up/downgrade to. + +When the toolchain (and standard libraries) are updated they usually depend on +newer versions of crates. Update our lockfile to the same versions to avoid +vendoringing duplicate versions. diff --git a/src/rust/bitbox02-rust-c/Cargo.toml b/src/rust/bitbox02-rust-c/Cargo.toml index 62ecab4a03..6ff57b4be6 100644 --- a/src/rust/bitbox02-rust-c/Cargo.toml +++ b/src/rust/bitbox02-rust-c/Cargo.toml @@ -68,6 +68,15 @@ target-c-unit-tests = [ "firmware", "c-unit-testing", ] +target-simulator-ng = [ + "dep:bitcoin", # for rust_base58_encode_check() + "app-bitcoin", + "app-litecoin", + "app-ethereum", + "app-cardano", + "app-u2f", + "firmware", +] platform-bitbox02 = [] platform-bitbox02plus = ["util/sha2", "bitbox02-noise", "bitbox02-rust"] diff --git a/src/rust/bitbox02-rust/src/general/screen.rs b/src/rust/bitbox02-rust/src/general/screen.rs index 1aedafb50c..0fe778a676 100644 --- a/src/rust/bitbox02-rust/src/general/screen.rs +++ b/src/rust/bitbox02-rust/src/general/screen.rs @@ -14,10 +14,10 @@ use core::time::Duration; -use bitbox02::{delay, ug_clear_buffer, ug_font_select_9x9, ug_put_string, ug_send_buffer}; +use bitbox02::{delay, screen_clear, ug_font_select_9x9, ug_put_string, ug_send_buffer}; pub fn print_debug_internal(duration: Duration, msg: &str) { - ug_clear_buffer(); + screen_clear(); ug_font_select_9x9(); ug_put_string(0, 0, msg, false); ug_send_buffer(); diff --git a/src/rust/bitbox02-sys/build.rs b/src/rust/bitbox02-sys/build.rs index 94fdb9a68d..659e896d07 100644 --- a/src/rust/bitbox02-sys/build.rs +++ b/src/rust/bitbox02-sys/build.rs @@ -22,54 +22,62 @@ const ALLOWLIST_VARS: &[&str] = &[ "BIP32_SERIALIZED_LEN", "BIP39_WORDLIST_LEN", "EC_PUBLIC_KEY_LEN", + "font_font_a_11X10", + "font_font_a_9X9", + "font_monogram_5X9", + "font_password_11X12", "INPUT_STRING_MAX_SIZE", "KEYSTORE_MAX_SEED_LENGTH", "MAX_LABEL_SIZE", "MAX_PK_SCRIPT_SIZE", + "MAX_UNLOCK_ATTEMPTS", "MAX_VARINT_SIZE", "MEMORY_DEVICE_NAME_MAX_LEN", "MEMORY_MULTISIG_NAME_MAX_LEN", - "SD_MAX_FILE_SIZE", - "XPUB_ENCODED_LEN", - "font_font_a_11X10", - "font_font_a_9X9", - "font_monogram_5X9", - "font_password_11X12", - "MEMORY_SPI_BLE_FIRMWARE_MAX_SIZE", - "MEMORY_SPI_BLE_FIRMWARE_1_ADDR", - "MEMORY_SPI_BLE_FIRMWARE_2_ADDR", - "MEMORY_PLATFORM_BITBOX02", "MEMORY_PLATFORM_BITBOX02_PLUS", + "MEMORY_PLATFORM_BITBOX02", "MEMORY_SECURECHIP_TYPE_ATECC", "MEMORY_SECURECHIP_TYPE_OPTIGA", - "MAX_UNLOCK_ATTEMPTS", + "MEMORY_SPI_BLE_FIRMWARE_1_ADDR", + "MEMORY_SPI_BLE_FIRMWARE_2_ADDR", + "MEMORY_SPI_BLE_FIRMWARE_MAX_SIZE", + "SCREEN_HEIGHT", + "SCREEN_WIDTH", + "SD_MAX_FILE_SIZE", + "SLIDER_POSITION_TWO_THIRD", + "XPUB_ENCODED_LEN", ]; const ALLOWLIST_TYPES: &[&str] = &[ "buffer_t", "component_t", "confirm_params_t", + "event_types", + "gestures_slider_data_t", "trinary_input_string_params_t", + "UG_COLOR", ]; const ALLOWLIST_FNS: &[&str] = &[ - "UG_ClearBuffer", - "UG_FontSelect", - "UG_PutString", - "UG_SendBuffer", "bip32_derive_xpub", - "bitbox02_smarteeprom_init", "bitbox_secp256k1_dleq_prove", "bitbox_secp256k1_dleq_verify", + "bitbox02_smarteeprom_init", + "communication_mode_ble_enabled", "confirm_create", "confirm_transaction_address_create", "confirm_transaction_fee_create", "delay_ms", "delay_us", + "emit_event", "empty_create", + "fake_memory_factoryreset", + "fake_securechip_event_counter_reset", + "fake_securechip_event_counter", + "hww_setup", "keystore_bip39_mnemonic_to_seed", - "keystore_copy_seed", "keystore_copy_bip39_seed", + "keystore_copy_seed", "keystore_create_and_store_seed", "keystore_encrypt_and_store_seed", "keystore_get_bip39_word", @@ -78,58 +86,60 @@ const ALLOWLIST_FNS: &[&str] = &[ "keystore_mock_unlocked", "keystore_secp256k1_nonce_commit", "keystore_secp256k1_sign", - "keystore_unlock", - "keystore_unlock_bip39", - "keystore_test_get_retained_seed_encrypted", "keystore_test_get_retained_bip39_seed_encrypted", + "keystore_test_get_retained_seed_encrypted", + "keystore_unlock_bip39", + "keystore_unlock", "label_create", "localtime", "lock_animation_start", "lock_animation_stop", - "memory_set_salt_root", "memory_add_noise_remote_static_pubkey", + "memory_ble_enable", + "memory_ble_enabled", "memory_bootloader_hash", "memory_check_noise_remote_static_pubkey", "memory_get_attestation_bootloader_hash", "memory_get_attestation_pubkey_and_certificate", - "memory_get_encrypted_seed_and_hmac", + "memory_get_ble_metadata", "memory_get_device_name", + "memory_get_encrypted_seed_and_hmac", "memory_get_noise_static_private_key", + "memory_get_platform", + "memory_get_securechip_type", "memory_get_seed_birthdate", "memory_is_initialized", "memory_is_mnemonic_passphrase_enabled", "memory_is_seeded", "memory_multisig_get_by_hash", "memory_multisig_set_by_hash", + "memory_set_ble_metadata", "memory_set_device_name", "memory_set_initialized", "memory_set_mnemonic_passphrase_enabled", + "memory_set_salt_root", "memory_set_seed_birthdate", "memory_setup", - "memory_ble_enabled", - "memory_ble_enable", - "memory_get_ble_metadata", - "memory_set_ble_metadata", - "memory_get_platform", - "memory_get_securechip_type", "memory_spi_get_active_ble_firmware_version", - "spi_mem_protected_area_write", "menu_create", - "fake_memory_factoryreset", - "spi_mem_full_erase", "printf", "progress_create", "progress_set", + "queue_hww_queue", + "queue_pull", "random_32_bytes_mcu", "random_32_bytes", "random_fake_reset", "reboot_to_bootloader", - "reset_reset", "reset_ble", + "reset_reset", + "screen_clear", + "screen_init", "screen_print_debug", "screen_process", "screen_saver_disable", "screen_saver_enable", + "screen_splash", "sd_card_inserted", "sd_erase_file_in_subdir", "sd_format", @@ -143,23 +153,31 @@ const ALLOWLIST_FNS: &[&str] = &[ "securechip_model", "securechip_monotonic_increments_remaining", "securechip_u2f_counter_set", - "fake_securechip_event_counter", - "fake_securechip_event_counter_reset", - "smarteeprom_is_enabled", - "smarteeprom_disable", "smarteeprom_bb02_config", + "smarteeprom_disable", + "smarteeprom_is_enabled", + "spi_mem_full_erase", + "spi_mem_protected_area_write", "status_create", "trinary_choice_create", "trinary_input_string_create", "trinary_input_string_set_input", - "ui_screen_stack_pop", + "UG_ClearBuffer", + "UG_FontSelect", + "UG_PutString", + "UG_SendBuffer", "ui_screen_stack_pop_all", + "ui_screen_stack_pop", "ui_screen_stack_push", + "usb_packet_process", + "usb_processing_hww", + "usb_processing_init", + "usb_processing_process", "util_format_datetime", - "communication_mode_ble_enabled", ]; const RUSTIFIED_ENUMS: &[&str] = &[ + "event_types", "keystore_error_t", "keystore_secp256k1_pubkey_format", "memory_result_t", diff --git a/src/rust/bitbox02-sys/wrapper.h b/src/rust/bitbox02-sys/wrapper.h index ada97b3899..83d0573aa5 100644 --- a/src/rust/bitbox02-sys/wrapper.h +++ b/src/rust/bitbox02-sys/wrapper.h @@ -53,6 +53,12 @@ #if defined(TESTING) #include +#include +#include +#include +#include +#include +#include #endif #if !defined(TESTING) diff --git a/src/rust/bitbox02/Cargo.toml b/src/rust/bitbox02/Cargo.toml index e0c8b383ac..163f3422d7 100644 --- a/src/rust/bitbox02/Cargo.toml +++ b/src/rust/bitbox02/Cargo.toml @@ -46,3 +46,6 @@ app-ethereum = [] app-bitcoin = [] app-litecoin = [] app-u2f = [] + +# Expose raw C bindings as bitbox02::bindings module +bindings = [] diff --git a/src/rust/bitbox02/src/lib.rs b/src/rust/bitbox02/src/lib.rs index 4e93f4732b..7a0f7b91ba 100644 --- a/src/rust/bitbox02/src/lib.rs +++ b/src/rust/bitbox02/src/lib.rs @@ -30,6 +30,9 @@ extern crate alloc; use alloc::string::String; +#[cfg(feature = "bindings")] +pub use bitbox02_sys as bindings; + #[cfg(feature = "testing")] pub mod testing; @@ -62,8 +65,8 @@ pub fn ug_put_string(x: i16, y: i16, input: &str, inverted: bool) { } } -pub fn ug_clear_buffer() { - unsafe { bitbox02_sys::UG_ClearBuffer() } +pub fn screen_clear() { + unsafe { bitbox02_sys::screen_clear() } } pub fn ug_send_buffer() { diff --git a/src/ui/components/status.c b/src/ui/components/status.c index 42fbba10ef..378528370a 100644 --- a/src/ui/components/status.c +++ b/src/ui/components/status.c @@ -21,7 +21,11 @@ #include #include +#if defined(TESTING) +#define STATUS_DEFAULT_DELAY 100 // counts +#else #define STATUS_DEFAULT_DELAY 500 // counts +#endif typedef struct { bool status; diff --git a/src/ui/event.h b/src/ui/event.h index c3afab61d9..c4741e8cbf 100644 --- a/src/ui/event.h +++ b/src/ui/event.h @@ -17,7 +17,7 @@ #include -enum { +enum event_types { EVENT_CONFIRM, EVENT_FORWARD, EVENT_BACKWARD, diff --git a/src/ui/screen_process.h b/src/ui/screen_process.h index 0f26ed9b52..4378b519b6 100644 --- a/src/ui/screen_process.h +++ b/src/ui/screen_process.h @@ -39,6 +39,10 @@ void screen_process(void); * Period of screen updates. * The screen is refreshed every SCREEN_FRAME_RATE event loops cycles. */ +#if defined(TESTING) +#define SCREEN_FRAME_RATE 1 +#else #define SCREEN_FRAME_RATE 30 +#endif #endif diff --git a/test/simulator-ng/.gitignore b/test/simulator-ng/.gitignore new file mode 100644 index 0000000000..ea8c4bf7f3 --- /dev/null +++ b/test/simulator-ng/.gitignore @@ -0,0 +1 @@ +/target diff --git a/test/simulator-ng/CMakeLists.txt b/test/simulator-ng/CMakeLists.txt new file mode 100644 index 0000000000..a229a7d430 --- /dev/null +++ b/test/simulator-ng/CMakeLists.txt @@ -0,0 +1,65 @@ +# Copyright 2024 Shift Cryptosecurity AG +# +# 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. + +#----------------------------------------------------------------------------- +# Simulator Next Generation +# + +set(RUST_BINARY_DIR ${CMAKE_BINARY_DIR}/src/rust) + +set(RUSTFLAGS "-L${CMAKE_ARCHIVE_OUTPUT_DIRECTORY} -lstatic=fatfs -lstatic=secp256k1 --cfg=rust_secp_no_symbol_renaming") + +if(SANITIZE_ADDRESS OR SANITIZE_UNDEFINED) + string(APPEND RUSTFLAGS " -Zexternal-clangrt -Cdefault-linker-libraries=y") + # When building with address sanitizer it is important that llvm/clang is + # the same version as rustcs llvm. On macos this can be achieved by + # installing llvm from brew and then prepend the path to its binary dir to + # PATH. By default rust uses `cc` as linker, but this will pick the system llvm. + if(${CMAKE_SYSTEM_NAME} MATCHES "Darwin") + string(APPEND RUSTFLAGS " -Clinker=clang") + endif() +endif() +if(SANITIZE_ADDRESS) + string(APPEND RUSTFLAGS " -Clink-arg=-fsanitize=address -Zsanitizer=address") + set(CFLAGS "-fsanitize=address") +endif() +if(SANITIZE_UNDEFINED) + string(APPEND RUSTFLAGS " -Clink-arg=-fsanitize=undefined") + string(APPEND CFLAGS " -fsanitize=undefined") +endif() + +execute_process(COMMAND rustc --print host-tuple OUTPUT_VARIABLE LLVM_HOST_TUPLE OUTPUT_STRIP_TRAILING_WHITESPACE) + +# Supplying llvm host tuple is necessary for address sanitization and doesn't +# hurt during regular builds. +add_custom_command( + OUTPUT dummy ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/simulator-ng + COMMAND + ${CMAKE_COMMAND} -E env + MACOSX_DEPLOYMENT_TARGET=${CMAKE_OSX_DEPLOYMENT_TARGET} + RUSTFLAGS=${RUSTFLAGS} + CFLAGS=${CFLAGS} + RUSTC_BOOTSTRAP=1 + cargo build --manifest-path ${CMAKE_CURRENT_SOURCE_DIR}/Cargo.toml --target-dir ${RUST_BINARY_DIR} --target=${LLVM_HOST_TUPLE} + COMMAND + ${CMAKE_COMMAND} -E copy + ${RUST_BINARY_DIR}/${LLVM_HOST_TUPLE}/debug/simulator-ng + ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/simulator-ng + DEPENDS rust-cbindgen secp256k1 fatfs + WORKING_DIRECTORY ${RUST_BINARY_DIR} +) + +add_custom_target(simulator-ng + DEPENDS ${CMAKE_RUNTIME_OUTPUT_DIRECTORY}/simulator-ng +) diff --git a/test/simulator-ng/Cargo.lock b/test/simulator-ng/Cargo.lock new file mode 100644 index 0000000000..d6ddfe115e --- /dev/null +++ b/test/simulator-ng/Cargo.lock @@ -0,0 +1,981 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "aead" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d122413f284cf2d62fb1b7db97e02edb8cda96d769b16e443a4f6195e35662b0" +dependencies = [ + "crypto-common", + "generic-array", +] + +[[package]] +name = "anyhow" +version = "1.0.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bb70cc08ec97ca5450e6eba421deeea5f172c0fc61f78b5357b2a8e8be195f" + +[[package]] +name = "arrayvec" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96d30a06541fbafbc7f82ed10c06164cfbd2c401138f6addd8404629c4b16711" + +[[package]] +name = "autocfg" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb031dd78e28731d87d56cc8ffef4a8f36ca26c38fe2de700543e627f8a464a" + +[[package]] +name = "base16ct" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c7f02d4ea65f2c1853089ffd8d2787bdbc63de2f0d29dedbcf8ccdfa0ccd4cf" + +[[package]] +name = "base58ck" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2c8d66485a3a2ea485c1913c4572ce0256067a5377ac8c75c4960e1cda98605f" +dependencies = [ + "bitcoin-internals", + "bitcoin_hashes", +] + +[[package]] +name = "bech32" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d965446196e3b7decd44aa7ee49e31d630118f90ef12f97900f262eb915c951d" + +[[package]] +name = "binascii" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "383d29d513d8764dcdc42ea295d979eb99c3c9f00607b3692cf68a431f7dca72" + +[[package]] +name = "bip32-ed25519" +version = "0.2.1" +source = "git+https://github.com/BitBoxSwiss/rust-bip32-ed25519?tag=v0.2.1#385d8a907f694aab7ca3f61ad603804c72ac520a" +dependencies = [ + "curve25519-dalek", + "digest", + "hmac", + "zeroize", +] + +[[package]] +name = "bip39" +version = "2.2.0" +source = "git+https://github.com/benma/rust-bip39.git?branch=bb02#5f2b6514274d7e89fb7d5c5d08cfaf0b63f0915c" +dependencies = [ + "bitcoin_hashes", + "zeroize", +] + +[[package]] +name = "bitbox-aes" +version = "0.1.0" +dependencies = [ + "bitcoin", + "ctaes", + "util", + "zeroize", +] + +[[package]] +name = "bitbox02" +version = "0.1.0" +dependencies = [ + "bip39", + "bitbox02-sys", + "bitcoin", + "hex", + "util", + "zeroize", +] + +[[package]] +name = "bitbox02-noise" +version = "0.1.0" +dependencies = [ + "noise-protocol", + "noise-rust-crypto", + "x25519-dalek", +] + +[[package]] +name = "bitbox02-rust" +version = "0.1.0" +dependencies = [ + "binascii", + "bip32-ed25519", + "bip39", + "bitbox02", + "bitbox02-noise", + "bitcoin", + "bitcoin_hashes", + "blake2", + "crc", + "digest", + "ed25519-dalek", + "erc20_params", + "hex", + "hmac", + "keccak", + "minicbor", + "miniscript", + "num-bigint", + "num-traits", + "prost", + "sha2", + "sha3", + "streaming-silent-payments", + "util", + "zeroize", +] + +[[package]] +name = "bitbox02-rust-c" +version = "0.1.0" +dependencies = [ + "bip39", + "bitbox-aes", + "bitbox02", + "bitbox02-noise", + "bitbox02-rust", + "bitcoin", + "der", + "hex", + "util", + "zeroize", +] + +[[package]] +name = "bitbox02-sys" +version = "0.1.0" +dependencies = [ + "cc", + "util", +] + +[[package]] +name = "bitcoin" +version = "0.32.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda569d741b895131a88ee5589a467e73e9c4718e958ac9308e4f7dc44b6945" +dependencies = [ + "base58ck", + "bech32", + "bitcoin-internals", + "bitcoin-io", + "bitcoin-units", + "bitcoin_hashes", + "hex-conservative", + "hex_lit", + "secp256k1", +] + +[[package]] +name = "bitcoin-internals" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "30bdbe14aa07b06e6cfeffc529a1f099e5fbe249524f8125358604df99a4bed2" + +[[package]] +name = "bitcoin-io" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "340e09e8399c7bd8912f495af6aa58bea0c9214773417ffaa8f6460f93aaee56" + +[[package]] +name = "bitcoin-units" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb54da0b28892f3c52203a7191534033e051b6f4b52bc15480681b57b7e036f5" +dependencies = [ + "bitcoin-internals", +] + +[[package]] +name = "bitcoin_hashes" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb18c03d0db0247e147a21a6faafd5a7eb851c743db062de72018b6b7e8e4d16" +dependencies = [ + "bitcoin-io", + "hex-conservative", +] + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "blake2" +version = "0.10.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "46502ad458c9a52b69d4d4d32775c788b7a1b85e8bc9d482d92250fc0e3f8efe" +dependencies = [ + "digest", +] + +[[package]] +name = "block-buffer" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cce20737498f97b993470a6e536b8523f0af7892a4f928cceb1ac5e52ebe7e" +dependencies = [ + "generic-array", +] + +[[package]] +name = "bytes" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad1f8e949d755f9d79112b5bb46938e0ef9d3804a0b16dfab13aafcaa5f0fa72" + +[[package]] +name = "cc" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1aeb932158bd710538c73702db6945cb68a8fb08c519e6e12706b94263b36db8" +dependencies = [ + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cfg-if" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd" + +[[package]] +name = "chacha20" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3613f74bd2eac03dad61bd53dbe620703d4371614fe0bc3b9f04dd36fe4e818" +dependencies = [ + "cfg-if", + "cipher", + "cpufeatures", +] + +[[package]] +name = "chacha20poly1305" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10cd79432192d1c0f4e1a0fef9527696cc039165d729fb41b3f4f4f354c2dc35" +dependencies = [ + "aead", + "chacha20", + "cipher", + "poly1305", + "zeroize", +] + +[[package]] +name = "cipher" +version = "0.4.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" +dependencies = [ + "crypto-common", + "inout", + "zeroize", +] + +[[package]] +name = "const-oid" +version = "0.9.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2459377285ad874054d797f3ccebf984978aa39129f6eafde5cdc8315b612f8" + +[[package]] +name = "cpufeatures" +version = "0.2.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a17b76ff3a4162b0b27f354a0c87015ddad39d35f9c0c36607a3bdd175dde1f1" +dependencies = [ + "libc", +] + +[[package]] +name = "crc" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "86ec7a15cbe22e59248fc7eadb1907dab5ba09372595da4d73dd805ed4417dfe" +dependencies = [ + "crc-catalog", +] + +[[package]] +name = "crc-catalog" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cace84e55f07e7301bae1c519df89cdad8cc3cd868413d3fdbdeca9ff3db484" + +[[package]] +name = "crypto-bigint" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0dc92fb57ca44df6db8059111ab3af99a63d5d0f8375d9972e319a379c6bab76" +dependencies = [ + "generic-array", + "rand_core", + "subtle", + "zeroize", +] + +[[package]] +name = "crypto-common" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bfb12502f3fc46cca1bb51ac28df9d618d813cdc3d2f25b9fe775a34af26bb3" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "ctaes" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4cbca3712c15d1e2dcc77f4eea8c838fb98f54ffe272d13a72516d488b098ce" +dependencies = [ + "cc", +] + +[[package]] +name = "curve25519-dalek" +version = "4.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97fb8b7c4503de7d6ae7b42ab72a5a59857b4c937ec27a3d4539dba95b5ab2be" +dependencies = [ + "cfg-if", + "cpufeatures", + "curve25519-dalek-derive", + "digest", + "fiat-crypto", + "rustc_version", + "subtle", +] + +[[package]] +name = "curve25519-dalek-derive" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f46882e17999c6cc590af592290432be3bce0428cb0d5f8b6715e4dc7b383eb3" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "der" +version = "0.7.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f55bf8e7b65898637379c1b74eb1551107c8294ed26d855ceb9fd1a09cfc9bc0" +dependencies = [ + "const-oid", + "zeroize", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", + "subtle", +] + +[[package]] +name = "ecdsa" +version = "0.16.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee27f32b5c5292967d2d4a9d7f1e0b0aed2c15daded5a60300e4abb9d8020bca" +dependencies = [ + "der", + "digest", + "elliptic-curve", + "rfc6979", + "signature", +] + +[[package]] +name = "ed25519" +version = "2.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "115531babc129696a58c64a4fef0a8bf9e9698629fb97e9e40767d235cfbcd53" +dependencies = [ + "signature", +] + +[[package]] +name = "ed25519-dalek" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a3daa8e81a3963a60642bcc1f90a670680bd4a77535faa384e9d1c79d620871" +dependencies = [ + "curve25519-dalek", + "ed25519", + "sha2", + "signature", + "subtle", +] + +[[package]] +name = "either" +version = "1.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb1f6b1ce1c140482ea30ddd3335fc0024ac7ee112895426e0a629a6c20adfe3" + +[[package]] +name = "elliptic-curve" +version = "0.13.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b5e6043086bf7973472e0c7dff2142ea0b680d30e18d9cc40f267efbf222bd47" +dependencies = [ + "base16ct", + "crypto-bigint", + "digest", + "ff", + "generic-array", + "group", + "rand_core", + "sec1", + "subtle", + "zeroize", +] + +[[package]] +name = "erc20_params" +version = "0.1.0" +dependencies = [ + "hex", +] + +[[package]] +name = "ff" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ded41244b729663b1e574f1b4fb731469f69f79c17667b5d776b16cda0479449" +dependencies = [ + "rand_core", + "subtle", +] + +[[package]] +name = "fiat-crypto" +version = "0.2.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f69037fe1b785e84986b4f2cbcf647381876a00671d25ceef715d7812dd7e1dd" + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", + "zeroize", +] + +[[package]] +name = "group" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0f9ef7462f7c099f518d754361858f86d8a07af53ba9af0fe635bbccb151a63" +dependencies = [ + "ff", + "rand_core", + "subtle", +] + +[[package]] +name = "hex" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70" + +[[package]] +name = "hex-conservative" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5313b072ce3c597065a808dbf612c4c8e8590bdbf8b579508bf7a762c5eae6cd" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "hex_lit" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3011d1213f159867b13cfd6ac92d2cd5f1345762c63be3554e84092d85a50bbd" + +[[package]] +name = "hmac" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" +dependencies = [ + "digest", +] + +[[package]] +name = "inout" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a0c10553d664a4d0bcff9f4215d0aac67a639cc68ef660840afe309b807bc9f5" +dependencies = [ + "generic-array", +] + +[[package]] +name = "itertools" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9a9d19fa1e79b6215ff29b9d6880b706147f16e9b1dbb1e4e5947b5b02bc5e3" +dependencies = [ + "either", +] + +[[package]] +name = "jobserver" +version = "0.1.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48d1dbcbbeb6a7fec7e059840aa538bd62aaccf972c7346c4d9d2059312853d0" +dependencies = [ + "libc", +] + +[[package]] +name = "keccak" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6d5ed8676d904364de097082f4e7d240b571b67989ced0240f08b7f966f940" +dependencies = [ + "cpufeatures", +] + +[[package]] +name = "lazy_static" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbd2bcb4c963f2ddae06a2efc7e9f3591312473c50c6685e1f298068316e66fe" + +[[package]] +name = "libc" +version = "0.2.171" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c19937216e9d3aa9956d9bb8dfc0b0c8beb6058fc4f7a4dc4d850edf86a237d6" + +[[package]] +name = "minicbor" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a1359d4b3ec786cdc1e44382c8c0e10965d95a173059590f62314c73be72969" +dependencies = [ + "minicbor-derive", +] + +[[package]] +name = "minicbor-derive" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6bdc119b1a405df86a8cde673295114179dbd0ebe18877c26ba89fb080365c2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "miniscript" +version = "12.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "add2d4aee30e4291ce5cffa3a322e441ff4d4bc57b38c8d9bf0e94faa50ab626" +dependencies = [ + "bech32", + "bitcoin", +] + +[[package]] +name = "noise-protocol" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2473d39689a839f5a363aaef7d99f76d5611bf352286682b25a6644fec18b1d3" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "noise-rust-crypto" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4c6159f60beb3bbbcdc266bc789bfc6c37fdad7d7ca7152d3e049ef5af633f0" +dependencies = [ + "chacha20poly1305", + "noise-protocol", + "sha2", + "zeroize", +] + +[[package]] +name = "num-bigint" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e44f723f1133c9deac646763579fdb3ac745e418f2a7af9cd0c431da1f20b9" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-integer" +version = "0.1.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7969661fd2958a5cb096e56c8e1ad0444ac2bbcd0061bd28660485a44879858f" +dependencies = [ + "num-traits", +] + +[[package]] +name = "num-traits" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841" +dependencies = [ + "autocfg", +] + +[[package]] +name = "opaque-debug" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "624a8340c38c1b80fd549087862da4ba43e08858af025b236e509b6649fc13d5" + +[[package]] +name = "p256" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9863ad85fa8f4460f9c48cb909d38a0d689dba1f6f6988a5e3e0d31071bcd4b" +dependencies = [ + "ecdsa", + "elliptic-curve", + "primeorder", + "sha2", +] + +[[package]] +name = "pkg-config" +version = "0.3.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7edddbd0b52d732b21ad9a5fab5c704c14cd949e5e9a1ec5929a24fded1b904c" + +[[package]] +name = "poly1305" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8159bd90725d2df49889a078b54f4f79e87f1f8a8444194cdca81d38f5393abf" +dependencies = [ + "cpufeatures", + "opaque-debug", + "universal-hash", +] + +[[package]] +name = "primeorder" +version = "0.13.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "353e1ca18966c16d9deb1c69278edbc5f194139612772bd9537af60ac231e1e6" +dependencies = [ + "elliptic-curve", +] + +[[package]] +name = "proc-macro2" +version = "1.0.93" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60946a68e5f9d28b0dc1c21bb8a97ee7d018a8b322fa57838ba31cc878e22d99" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "prost" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e13db3d3fde688c61e2446b4d843bc27a7e8af269a69440c0308021dc92333cc" +dependencies = [ + "bytes", + "prost-derive", +] + +[[package]] +name = "prost-derive" +version = "0.13.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "18bec9b0adc4eba778b33684b7ba3e7137789434769ee3ce3930463ef904cfca" +dependencies = [ + "anyhow", + "itertools", + "proc-macro2", + "quote", + "syn", +] + +[[package]] +name = "quote" +version = "1.0.38" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e4dccaaaf89514f546c693ddc140f729f958c247918a13380cccc6078391acc" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" + +[[package]] +name = "rfc6979" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dd2a808d456c4a54e300a23e9f5a67e122c3024119acbfd73e3bf664491cb2" +dependencies = [ + "hmac", + "subtle", +] + +[[package]] +name = "rustc_version" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bfa0f585226d2e68097d4f95d113b15b83a82e819ab25717ec0590d9584ef366" +dependencies = [ + "semver", +] + +[[package]] +name = "sdl2" +version = "0.38.0" +dependencies = [ + "bitflags", + "lazy_static", + "libc", + "sdl2-sys", +] + +[[package]] +name = "sdl2-sys" +version = "0.38.0" +dependencies = [ + "cfg-if", + "libc", + "pkg-config", + "version-compare", +] + +[[package]] +name = "sec1" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3e97a565f76233a6003f9f5c54be1d9c5bdfa3eccfb189469f11ec4901c47dc" +dependencies = [ + "base16ct", + "der", + "generic-array", + "subtle", + "zeroize", +] + +[[package]] +name = "secp256k1" +version = "0.29.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e0cc0f1cf93f4969faf3ea1c7d8a9faed25918d96affa959720823dfe86d4f3" +dependencies = [ + "bitcoin_hashes", + "secp256k1-sys", +] + +[[package]] +name = "secp256k1-sys" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1433bd67156263443f14d603720b082dd3121779323fce20cba2aa07b874bc1b" +dependencies = [ + "cc", +] + +[[package]] +name = "semver" +version = "1.0.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "836fa6a3e1e547f9a2c4040802ec865b5d85f4014efe00555d7090a3dcaa1090" + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + +[[package]] +name = "sha3" +version = "0.10.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75872d278a8f37ef87fa0ddbda7802605cb18344497949862c0d4dcb291eba60" +dependencies = [ + "digest", + "keccak", +] + +[[package]] +name = "shlex" +version = "1.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fda2ff0d084019ba4d7c6f371c95d8fd75ce3524c3cb8fb653a3023f6323e64" + +[[package]] +name = "signature" +version = "2.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "77549399552de45a898a580c1b41d445bf730df867cc44e6c0233bbc4b8329de" +dependencies = [ + "digest", + "rand_core", +] + +[[package]] +name = "simulator-ng" +version = "0.1.0" +dependencies = [ + "bitbox-aes", + "bitbox02", + "bitbox02-rust", + "bitbox02-rust-c", + "sdl2", +] + +[[package]] +name = "streaming-silent-payments" +version = "0.1.0" +dependencies = [ + "bitbox02", + "bitcoin", +] + +[[package]] +name = "subtle" +version = "2.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6bdef32e8150c2a081110b42772ffe7d7c9032b606bc226c8260fd97e0976601" + +[[package]] +name = "syn" +version = "2.0.98" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "36147f1a48ae0ec2b5b3bc5b537d267457555a10dc06f3dbc8cb11ba3006d3b1" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[package]] +name = "typenum" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "497961ef93d974e23eb6f433eb5fe1b7930b659f06d12dec6fc44a8f554c0bba" + +[[package]] +name = "unicode-ident" +version = "1.0.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a210d160f08b701c8721ba1c726c11662f877ea6b7094007e1ca9a1041945034" + +[[package]] +name = "universal-hash" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc1de2c688dc15305988b563c3854064043356019f97a4b46276fe734c4f07ea" +dependencies = [ + "crypto-common", + "subtle", +] + +[[package]] +name = "util" +version = "0.1.0" +dependencies = [ + "bitcoin", + "hex", + "num-bigint", + "p256", + "sha2", +] + +[[package]] +name = "version-compare" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "579a42fc0b8e0c63b76519a339be31bed574929511fa53c1a3acae26eb258f29" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "x25519-dalek" +version = "2.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb66477291e7e8d2b0ff1bcb900bf29489a9692816d79874bea351e7a8b6de96" +dependencies = [ + "curve25519-dalek", + "rand_core", +] + +[[package]] +name = "zeroize" +version = "1.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525b4ec142c6b68a2d10f01f7bbf6755599ca3f81ea53b8431b7dd348f5fdb2d" +dependencies = [ + "zeroize_derive", +] + +[[package]] +name = "zeroize_derive" +version = "1.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce36e65b0d2999d2aafac989fb249189a141aee1f53c612c1f37d72631959f69" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] diff --git a/test/simulator-ng/Cargo.toml b/test/simulator-ng/Cargo.toml new file mode 100644 index 0000000000..20f4ff0845 --- /dev/null +++ b/test/simulator-ng/Cargo.toml @@ -0,0 +1,13 @@ +[package] +name = "simulator-ng" +version = "0.1.0" +edition = "2024" + +[dependencies] +# SDL2 "bundled" feature doesn't work with "SDL2_image" +# SDL2 "static-link" feature doesn't work if the library is placed in a "system dir" +sdl2 = { path="../../external/rust-sdl2", default-features=false, features=["static-link", "use-pkgconfig", "image", "ttf"] } +bitbox02-rust = { path="../../src/rust/bitbox02-rust" } +bitbox02-rust-c = { path="../../src/rust/bitbox02-rust-c", features=["target-simulator-ng", "testing"] } +bitbox02 = { path="../../src/rust/bitbox02", features=["bindings"] } +bitbox-aes = { path="../../src/rust/bitbox-aes"} diff --git a/test/simulator-ng/bg.png b/test/simulator-ng/bg.png new file mode 100644 index 0000000000..905f5fc626 Binary files /dev/null and b/test/simulator-ng/bg.png differ diff --git a/test/simulator-ng/src/main.rs b/test/simulator-ng/src/main.rs new file mode 100644 index 0000000000..daa1e0b7bf --- /dev/null +++ b/test/simulator-ng/src/main.rs @@ -0,0 +1,451 @@ +use sdl2::event::{Event, EventSender}; +use sdl2::image::LoadTexture; +use sdl2::keyboard::Keycode; +use sdl2::pixels::{Color, PixelFormatEnum}; +use sdl2::rect::Rect; +use sdl2::render::BlendMode; +use std::fmt::Write as fmtWrite; +use std::io::{Read, Write}; +use std::net::{TcpListener, TcpStream}; +use std::sync::{ + Arc, + atomic::{AtomicBool, AtomicU32, Ordering}, + mpsc, +}; +use std::thread; +use std::time::{Duration, Instant}; + +// "use" these dependencies to link in functions +extern crate bitbox02_rust_c; +extern crate bitbox_aes; + +// Only send `Copy` things in SDL events. it doesn't handle objects very safely. +// https://github.com/Rust-SDL2/rust-sdl2/issues/487 +/// New data from client, to be forwarded to HWW +#[derive(Debug, Clone, Copy)] +struct HWWDataEvent {} + +/// When reading thread detects an end of stream, send disconnect event to kill writer thread +#[derive(Debug)] +struct DisconnectEvent {} + +static BG: &[u8; 325362] = include_bytes!("../bg.png"); +static FONT: &[u8; 10304] = include_bytes!("../../../src/ui/fonts/monogram.ttf"); + +use bitbox02::bindings::{SCREEN_HEIGHT, SCREEN_WIDTH, UG_COLOR}; + +const MARGIN: u32 = 20; +const PADDING_TOP_BOTTOM: u32 = 22; +const PADDING_LEFT: u32 = 60; +const PADDING_RIGHT: u32 = 35; + +pub fn handle_stream_reader( + mut stream: TcpStream, + sender: mpsc::Sender<[u8; 64]>, + es: EventSender, + counter: Arc, +) { + let mut buf = [0; 1024]; + while let Ok(len) = stream.read(&mut buf) { + if len == 0 { + // Client disconnected + break; + } + for i in 0..len / 64 { + let mut data: [u8; 64] = [0; 64]; + data.copy_from_slice(&buf[64 * i..64 * (i + 1)]); + sender.send(data).unwrap(); + } + } + es.push_custom_event(DisconnectEvent {}).unwrap(); + println!("Reader: Disconnected"); + counter.fetch_sub(1, Ordering::SeqCst); +} + +pub fn handle_stream_writer( + mut stream: TcpStream, + counter: Arc, + outbound: mpsc::Receiver<[u8; 64]>, +) { + for item in outbound.iter() { + if stream.write_all(&item[..]).is_err() { + // Client disconnected while writing + break; + } + } + println!("Writer: Disconnected"); + counter.fetch_sub(1, Ordering::SeqCst); +} + +pub fn network_task( + new_connection_flag: Arc, + evs: mpsc::Receiver<(EventSender, mpsc::Receiver<[u8; 64]>)>, + hww_sender: mpsc::Sender<[u8; 64]>, +) { + let listener = TcpListener::bind("0.0.0.0:15423").unwrap(); + + // Use this counter to ensure that we only connect to a single client. + let counter = Arc::new(AtomicU32::new(0)); + for stream in listener.incoming() { + if counter.fetch_add(2, Ordering::SeqCst) == 0 { + new_connection_flag.store(true, Ordering::SeqCst); + let stream = stream.unwrap(); + let (es, receiver) = evs.recv().unwrap(); + thread::spawn({ + let stream = stream.try_clone().unwrap(); + let counter = counter.clone(); + let hww_sender = hww_sender.clone(); + move || handle_stream_reader(stream, hww_sender, es, counter) + }); + thread::spawn({ + let counter = counter.clone(); + move || handle_stream_writer(stream, counter, receiver) + }); + } else { + println!("Busy, won't accept new clients"); + counter.fetch_sub(2, Ordering::SeqCst); + } + } +} + +static mut DISPLAY_BUF: [u32; (SCREEN_WIDTH * SCREEN_HEIGHT) as usize] = + [0; (SCREEN_WIDTH * SCREEN_HEIGHT) as usize]; + +// Unsafe, do not use this while you are mutating DISPLAY_BUF... +unsafe fn display_buf_as_u8_slice() -> &'static [u8] { + let ptr: *const u32 = unsafe { &raw const DISPLAY_BUF[0] }; + let len = SCREEN_WIDTH as usize * SCREEN_HEIGHT as usize * size_of::(); + unsafe { std::slice::from_raw_parts(ptr as *const u8, len) } +} + +unsafe extern "C" fn pixel_fn(x: i16, y: i16, c: UG_COLOR) { + if x < 0 || x >= SCREEN_WIDTH as i16 { + return; + } + if y < 0 || y >= SCREEN_HEIGHT as i16 { + return; + } + let ptr: *mut _ = unsafe { &raw mut DISPLAY_BUF[0] }; + let c = c as u32; + let offset = ((y * SCREEN_WIDTH as i16) + x) as usize; + + // White pixels are OPAQUE, Black pixels are completely transparent. + if c != 0 { + unsafe { *ptr.add(offset) = (c << 8) | (c << 16) | (c << 24) | 0xff } + } else { + unsafe { *ptr.add(offset) = 0 } + } +} + +unsafe extern "C" fn clear_fn() { + let mut ptr: *mut _ = unsafe { &raw mut DISPLAY_BUF[0] }; + for _ in 0..(SCREEN_WIDTH * SCREEN_HEIGHT) { + unsafe { *ptr = 0 } + ptr = unsafe { ptr.add(1) }; + } +} + +unsafe extern "C" fn mirror_fn(_: bool) {} + +fn init_hww() -> bool { + unsafe { bitbox02::bindings::screen_init(Some(pixel_fn), Some(mirror_fn), Some(clear_fn)) }; + unsafe { bitbox02::bindings::screen_splash() }; + + // BitBox02 simulation initialization + unsafe { bitbox02::bindings::usb_processing_init() }; + println!("USB setup success"); + + unsafe { bitbox02::bindings::hww_setup() }; + println!("HWW setup success"); + + let sd_success = unsafe { bitbox02::bindings::sd_format() }; + if !sd_success { + eprintln!("ERROR, sd card setup failed"); + return false; + } + + println!("Sd card setup: success"); + + bitbox02::testing::mock_memory(); + println!("Memory setup: success"); + + unsafe { bitbox02::bindings::smarteeprom_bb02_config() }; + unsafe { bitbox02::bindings::bitbox02_smarteeprom_init() }; + true +} + +unsafe extern "C" { + fn rust_workflow_spin(); + fn rust_async_usb_spin(); +} + +struct Slider { + active: bool, + position: u16, + pinch: bool, +} + +impl Default for Slider { + fn default() -> Self { + Slider { + active: false, + position: 0, + pinch: false, + } + } +} + +pub fn handle_mouse_motion(sliders: &mut (Slider, Slider), x: i32, y: i32, xrel: i32) { + let slider_top = &mut sliders.0; + let slider_bottom = &mut sliders.1; + + let slider_pos = (x - ((MARGIN + PADDING_LEFT) as i32)) * 255 / SCREEN_WIDTH as i32; + if slider_pos >= 0 && slider_pos <= 255 { + let slider_data = bitbox02::bindings::gestures_slider_data_t { + diff: xrel as i16, + position: slider_pos as u16, + velocity: 0, + }; + if y < MARGIN as i32 / 2 { + if slider_top.active { + println!("top tap {:?}", slider_data); + slider_top.active = false; + let event = bitbox02::bindings::event_t { + data: &slider_data as *const _ as *const _, + id: bitbox02::bindings::event_types::EVENT_TOP_SHORT_TAP as u8, + }; + unsafe { bitbox02::bindings::emit_event(&event) }; + } + } else if y < MARGIN as i32 { + slider_top.active = true; + } else if y > (MARGIN + 2 * PADDING_TOP_BOTTOM + 64 + MARGIN / 2) as i32 { + if slider_bottom.active { + println!("bottom tap {:?}", slider_data); + slider_bottom.active = false; + let event = bitbox02::bindings::event_t { + data: &slider_data as *const _ as *const _, + id: bitbox02::bindings::event_types::EVENT_BOTTOM_SHORT_TAP as u8, + }; + unsafe { bitbox02::bindings::emit_event(&event) }; + } + } else if y > (MARGIN + 2 * PADDING_TOP_BOTTOM + 64) as i32 { + slider_bottom.active = true; + } + } + if x > (MARGIN + PADDING_LEFT + SCREEN_WIDTH + PADDING_RIGHT) as i32 + && x < (MARGIN + PADDING_LEFT + SCREEN_WIDTH + PADDING_RIGHT + MARGIN / 2) as i32 + && y > (MARGIN + PADDING_TOP_BOTTOM + SCREEN_HEIGHT / 3) as i32 + && y < (MARGIN + PADDING_TOP_BOTTOM + SCREEN_HEIGHT * 2 / 3) as i32 + { + if !slider_top.pinch { + slider_top.pinch = true; + } + } else if (slider_top.pinch) { + slider_top.pinch = false; + } +} + +pub fn main() -> Result<(), i32> { + let sdl_context = sdl2::init().unwrap(); + let sdl_ttf = sdl2::ttf::init().unwrap(); + let font_rwops = sdl2::rwops::RWops::from_bytes(FONT).unwrap(); + let font = sdl_ttf.load_font_from_rwops(font_rwops, 16).unwrap(); + + if !init_hww() { + return Err(1); + } + + let ev = sdl_context.event().unwrap(); + let (evs_sender, evs_receiver) = mpsc::channel(); + let (hww_sender, hww_receiver) = mpsc::channel(); + ev.register_custom_event::().unwrap(); + ev.register_custom_event::().unwrap(); + let es = ev.event_sender(); + let new_connection_flag = Arc::new(AtomicBool::new(false)); + thread::spawn({ + let new_connection_flag = Arc::clone(&new_connection_flag); + || network_task(new_connection_flag, evs_receiver, hww_sender) + }); + + let video_subsystem = sdl_context.video().unwrap(); + + let window = video_subsystem + .window( + "BitBox02 simulator", + SCREEN_WIDTH + 2 * MARGIN + PADDING_LEFT + PADDING_RIGHT, + SCREEN_HEIGHT + 2 * MARGIN + 2 * PADDING_TOP_BOTTOM, + ) + .position_centered() + .build() + .unwrap(); + + let mut canvas = window.into_canvas().build().unwrap(); + + let tc = canvas.texture_creator(); + let bg = tc.load_texture_bytes(BG).unwrap(); + let mut screen_content = tc + .create_texture_static(Some(PixelFormatEnum::RGBA8888), SCREEN_WIDTH, SCREEN_HEIGHT) + .unwrap(); + screen_content.set_blend_mode(BlendMode::Blend); + + let content_area = Rect::new( + (MARGIN + PADDING_LEFT) as i32, + (MARGIN + PADDING_TOP_BOTTOM) as i32, + SCREEN_WIDTH, + SCREEN_HEIGHT, + ); + let bg_area = Rect::new( + MARGIN as i32, + MARGIN as i32, + SCREEN_WIDTH + PADDING_LEFT + PADDING_RIGHT, + SCREEN_HEIGHT + 2 * PADDING_TOP_BOTTOM, + ); + let slider_top_bg = Rect::new( + (MARGIN + PADDING_LEFT) as i32, + (MARGIN / 2) as i32, + SCREEN_WIDTH, + MARGIN / 2, + ); + let slider_bottom_bg = Rect::new( + (MARGIN + PADDING_LEFT) as i32, + (MARGIN + 2 * PADDING_TOP_BOTTOM + SCREEN_HEIGHT) as i32, + SCREEN_WIDTH, + MARGIN / 2, + ); + let pinch_bg = Rect::new( + (MARGIN + PADDING_LEFT + 128 + PADDING_RIGHT) as i32, + (MARGIN + PADDING_TOP_BOTTOM + SCREEN_HEIGHT / 3) as i32, + MARGIN / 2, + SCREEN_HEIGHT / 3, + ); + + canvas.set_draw_color(Color::RGB(0, 255, 255)); + canvas.clear(); + canvas.present(); + let mut event_pump = sdl_context.event_pump().unwrap(); + let mut last_blit = Instant::now(); + let mut current_client_outbound = None; + let mut sliders = (Slider::default(), Slider::default()); + let mut fps_formatted = String::new(); + 'running: loop { + if new_connection_flag.swap(false, Ordering::SeqCst) { + println!("new connection"); + let (sender, receiver) = mpsc::channel(); + current_client_outbound = Some(sender); + evs_sender.send((ev.event_sender(), receiver)).unwrap(); + } + for event in event_pump.poll_iter() { + match event { + Event::Quit { .. } + | Event::KeyDown { + keycode: Some(Keycode::Escape), + .. + } => break 'running, + Event::MouseMotion { x, y, xrel, .. } => { + handle_mouse_motion(&mut sliders, x, y, xrel); + } + Event::User { .. } => { + if let Some(_) = event.as_user_event_type::() { + current_client_outbound = None; + } + } + _ => { + //println!("unhandled event") + } + } + } + + // Check if there is data + while let Ok(data) = hww_receiver.try_recv() { + unsafe { + bitbox02::bindings::usb_packet_process( + data.as_ptr() as *const bitbox02::bindings::USB_FRAME + ) + }; + } + + // Send data from HWW to TCP Client + loop { + let hww_data = + unsafe { bitbox02::bindings::queue_pull(bitbox02::bindings::queue_hww_queue()) }; + if hww_data != std::ptr::null() { + if let Some(sender) = ¤t_client_outbound { + let mut data: [u8; 64] = [0; 64]; + let slice: &[u8] = unsafe { std::slice::from_raw_parts(hww_data, 64) }; + data.copy_from_slice(&slice[..]); + if sender.send(data).is_err() { + println!("writer thread died and closed channel"); + current_client_outbound = None; + } + } + } else { + break; + } + } + + unsafe { rust_workflow_spin() } + bitbox02_rust::async_usb::spin(); + unsafe { rust_async_usb_spin() } + unsafe { + bitbox02::bindings::usb_processing_process(bitbox02::bindings::usb_processing_hww()) + } + + // Draw with 60hz + let now = Instant::now(); + if now.duration_since(last_blit) > Duration::from_micros(16667) { + // Special handling of pinch. Emit one event per frame + if sliders.0.pinch { + let slider_data = bitbox02::bindings::gestures_slider_data_t { + diff: 0, + position: bitbox02::bindings::SLIDER_POSITION_TWO_THIRD as u16 + 1, + velocity: 0, + }; + let mut event = bitbox02::bindings::event_t { + data: &slider_data as *const _ as *const _, + id: bitbox02::bindings::event_types::EVENT_TOP_CONTINUOUS_TAP as u8, + }; + unsafe { bitbox02::bindings::emit_event(&event) }; + event.id = bitbox02::bindings::event_types::EVENT_BOTTOM_CONTINUOUS_TAP as u8; + unsafe { bitbox02::bindings::emit_event(&event) }; + } + + unsafe { bitbox02::bindings::screen_process() } + canvas.set_draw_color(Color::RGB(255, 255, 255)); + canvas.clear(); + canvas.set_draw_color(Color::RGB(0, 150, 150)); + let fps = 1000.0 / ((now - last_blit).as_millis() as f32); + fps_formatted.clear(); + write!(fps_formatted, "{fps:.2}").unwrap(); + last_blit = now; + + let text_surf = font + .render(&fps_formatted) + .solid(Color::RGB(0, 0, 0)) + .unwrap(); + let text = text_surf.as_texture(&tc).unwrap(); + let fps_box = Rect::new(10, 5, text_surf.width(), text_surf.height()); + canvas + .copy(&text, None, fps_box) + .expect("failed to copy text to canvas"); + + canvas + .copy(&bg, None, bg_area) + .expect("Couldn't copy to canvas"); + canvas + .fill_rects(&[slider_top_bg, slider_bottom_bg, pinch_bg]) + .unwrap(); + + screen_content + .update( + None, + unsafe { display_buf_as_u8_slice() }, + SCREEN_WIDTH as usize * size_of::(), + ) + .unwrap(); + canvas.copy(&screen_content, None, content_area).unwrap(); + + canvas.present(); + } + } + Ok(()) +}