inventory-0.3.2/.cargo_vcs_info.json0000644000000001360000000000100130730ustar { "git": { "sha1": "969a8994fc25519cabb698687d9289e1c8dd4a85" }, "path_in_vcs": "" }inventory-0.3.2/.clippy.toml000064400000000000000000000000201046102023000141260ustar 00000000000000msrv = "1.62.0" inventory-0.3.2/.github/workflows/ci.yml000064400000000000000000000024371046102023000164040ustar 00000000000000name: CI on: push: pull_request: schedule: [cron: "40 1 * * *"] permissions: contents: read env: RUSTFLAGS: -Dwarnings jobs: test: name: ${{matrix.name || format('Rust {0}', matrix.rust)}} runs-on: ${{matrix.os}}-latest strategy: fail-fast: false matrix: rust: [nightly, beta, stable, 1.62.0] os: [ubuntu] include: - name: macOS os: macos rust: nightly - name: Windows (gnu) os: windows rust: nightly-x86_64-pc-windows-gnu - name: Windows (msvc) os: windows rust: nightly-x86_64-pc-windows-msvc steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@master with: toolchain: ${{matrix.rust}} - run: cargo test clippy: name: Clippy runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v3 - uses: dtolnay/rust-toolchain@clippy - run: cargo clippy -- -Dclippy::all -Dclippy::pedantic outdated: name: Outdated runs-on: ubuntu-latest if: github.event_name != 'pull_request' steps: - uses: actions/checkout@v3 - uses: dtolnay/install@cargo-outdated - run: cargo outdated --exit-code 1 inventory-0.3.2/.gitignore000064400000000000000000000000361046102023000136520ustar 00000000000000/target **/*.rs.bk Cargo.lock inventory-0.3.2/Cargo.lock0000644000000114370000000000100110540ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "ctor" version = "0.1.23" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdffe87e1d521a10f9696f833fe502293ea446d7f256c06128293a4119bdf4cb" dependencies = [ "quote", "syn", ] [[package]] name = "ghost" version = "0.1.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eb19fe8de3ea0920d282f7b77dd4227aea6b8b999b42cdf0ca41b2472b14443a" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "glob" version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b919933a397b79c37e33b77bb2aa3dc8eb6e165ad809e58ff75bc7db2e34574" [[package]] name = "inventory" version = "0.3.2" dependencies = [ "ctor", "ghost", "rustversion", "trybuild", ] [[package]] name = "itoa" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c8af84674fe1f223a982c933a0ee1086ac4d4052aa0fb8060c12c6ad838e754" [[package]] name = "once_cell" version = "1.13.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "074864da206b4973b84eb91683020dbefd6a8c3f0f38e054d93954e891935e4e" [[package]] name = "proc-macro2" version = "1.0.43" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0a2ca2c61bc9f3d74d2886294ab7b9853abd9c1ad903a3ac7815c58989bb7bab" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bbe448f377a7d6961e30f5955f9b8d106c3f5e449d493ee1b125c1d43c2b5179" dependencies = [ "proc-macro2", ] [[package]] name = "rustversion" version = "1.0.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97477e48b4cf8603ad5f7aaf897467cf42ab4218a38ef76fb14c2d6773a6d6a8" [[package]] name = "ryu" version = "1.0.11" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4501abdff3ae82a1c1b477a17252eb69cee9e66eb915c1abaa4f44d873df9f09" [[package]] name = "serde" version = "1.0.143" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53e8e5d5b70924f74ff5c6d64d9a5acd91422117c60f48c4e07855238a254553" [[package]] name = "serde_derive" version = "1.0.143" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d3d8e8de557aee63c26b85b947f5e59b690d0454c753f3adeb5cd7835ab88391" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "serde_json" version = "1.0.83" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "38dd04e3c8279e75b31ef29dbdceebfe5ad89f4d0937213c53f7d49d01b3d5a7" dependencies = [ "itoa", "ryu", "serde", ] [[package]] name = "syn" version = "1.0.99" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "58dbef6ec655055e20b86b15a8cc6d439cca19b667537ac6a1369572d151ab13" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "termcolor" version = "1.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bab24d30b911b2376f3a13cc2cd443142f0c81dda04c118693e35b3835757755" dependencies = [ "winapi-util", ] [[package]] name = "toml" version = "0.5.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8d82e1a7758622a465f8cee077614c73484dac5b836c02ff6a40d5d1010324d7" dependencies = [ "serde", ] [[package]] name = "trybuild" version = "1.0.64" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e7f408301c7480f9e6294eb779cfc907f54bd901a9660ef24d7f233ed5376485" dependencies = [ "glob", "once_cell", "serde", "serde_derive", "serde_json", "termcolor", "toml", ] [[package]] name = "unicode-ident" version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c4f5b37a154999a8f3f98cc23a628d850e154479cd94decf3414696e12e31aaf" [[package]] name = "winapi" version = "0.3.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" dependencies = [ "winapi-i686-pc-windows-gnu", "winapi-x86_64-pc-windows-gnu", ] [[package]] name = "winapi-i686-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" [[package]] name = "winapi-util" version = "0.1.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "70ec6ce85bb158151cae5e5c87f95a8e97d2c0c4b001223f33a334e3ce5de178" dependencies = [ "winapi", ] [[package]] name = "winapi-x86_64-pc-windows-gnu" version = "0.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" inventory-0.3.2/Cargo.toml0000644000000022350000000000100110730ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.62" name = "inventory" version = "0.3.2" authors = ["David Tolnay "] description = "Typed distributed plugin registration" documentation = "https://docs.rs/inventory" readme = "README.md" keywords = ["linkage"] categories = [ "development-tools::build-utils", "development-tools::procedural-macro-helpers", "no-std", ] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/inventory" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] [dependencies.ctor] version = "0.1" [dependencies.ghost] version = "0.1.4" [dev-dependencies.rustversion] version = "1.0" [dev-dependencies.trybuild] version = "1.0" inventory-0.3.2/Cargo.toml.orig000064400000000000000000000012051046102023000145500ustar 00000000000000[package] name = "inventory" version = "0.3.2" # remember to update html_root_url authors = ["David Tolnay "] categories = ["development-tools::build-utils", "development-tools::procedural-macro-helpers", "no-std"] description = "Typed distributed plugin registration" documentation = "https://docs.rs/inventory" edition = "2021" keywords = ["linkage"] license = "MIT OR Apache-2.0" repository = "https://github.com/dtolnay/inventory" rust-version = "1.62" [dependencies] ctor = "0.1" ghost = "0.1.4" [dev-dependencies] rustversion = "1.0" trybuild = "1.0" [package.metadata.docs.rs] targets = ["x86_64-unknown-linux-gnu"] inventory-0.3.2/LICENSE-APACHE000064400000000000000000000251371046102023000136170ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. inventory-0.3.2/LICENSE-MIT000064400000000000000000000017771046102023000133330ustar 00000000000000Permission 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. inventory-0.3.2/README.md000064400000000000000000000110221046102023000131360ustar 00000000000000## Typed distributed plugin registration [github](https://github.com/dtolnay/inventory) [crates.io](https://crates.io/crates/inventory) [docs.rs](https://docs.rs/inventory) [build status](https://github.com/dtolnay/inventory/actions?query=branch%3Amaster) This crate provides a way to set up a plugin registry into which plugins can be registered from any source file linked into your application. There does not need to be a central list of all the plugins. ```toml [dependencies] inventory = "0.3" ``` *Supports rustc 1.62+*
# Examples Suppose we are writing a command line flags library and want to allow any source file in the application to register command line flags that are relevant to it. This is the flag registration style used by [gflags] and is better suited for large scale development than maintaining a single central list of flags, as the central list would become an endless source of merge conflicts in an application developed simultaneously by thousands of developers. [gflags]: https://gflags.github.io/gflags/ ### Instantiating the plugin registry Let's use a `struct Flag` as the plugin type, which will contain the short name of the flag like `-v`, the full name like `--verbose`, and maybe other information like argument type and help text. We instantiate a plugin registry with an invocation of `inventory::collect!`. ```rust pub struct Flag { short: char, name: &'static str, /* ... */ } impl Flag { pub const fn new(short: char, name: &'static str) -> Self { Flag { short, name } } } inventory::collect!(Flag); ``` This `collect!` call must be in the same crate that defines the plugin type. This macro does not "run" anything so place it outside of any function body. ### Registering plugins Now any crate with access to the `Flag` type can register flags as a plugin. Plugins can be registered by the same crate that declares the plugin type, or by any downstream crate. ```rust inventory::submit! { Flag::new('v', "verbose") } ``` The `submit!` macro does not "run" anything so place it outside of any function body. In particular, note that all `submit!` invocations across all source files linked into your application all take effect simultaneously. A `submit!` invocation is not a statement that needs to be called from `main` in order to execute. ### Iterating over plugins The value `inventory::iter::` is an iterator with element type `&'static T` that iterates over all plugins registered of type `T`. ```rust for flag in inventory::iter:: { println!("-{}, --{}", flag.short, flag.name); } ``` There is no guarantee about the order that plugins of the same type are visited by the iterator. They may be visited in any order.
## How it works Inventory is built on the [`ctor`] crate which provides module initialization functions for Rust similar to `__attribute__((constructor))` in C. Each call to `inventory::submit!` produces a shim that evaluates the given expression and registers it into a registry of its corresponding type. This registration happens dynamically as part of life-before-main for statically linked elements. Elements brought in by a dynamically loaded library are registered at the time that dlopen occurs. [`ctor`]: https://github.com/mmastrac/rust-ctor Platform support includes Linux, macOS, iOS, FreeBSD, Android, and Windows. Other platforms will simply find that no plugins have been registered. Support for other targets would need to be added in the `ctor` crate. For a different approach to plugin registration that *does not* involve life-before-main, see the [`linkme`] crate. [`linkme`]: https://github.com/dtolnay/linkme
#### License Licensed under either of Apache License, Version 2.0 or MIT license at your option.
Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this crate by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions. inventory-0.3.2/examples/flags.rs000064400000000000000000000005561046102023000151510ustar 00000000000000struct Flag { short: char, name: &'static str, } impl Flag { const fn new(short: char, name: &'static str) -> Self { Flag { short, name } } } inventory::submit! { Flag::new('v', "verbose") } inventory::collect!(Flag); fn main() { for flag in inventory::iter:: { println!("-{}, --{}", flag.short, flag.name); } } inventory-0.3.2/src/lib.rs000064400000000000000000000265461046102023000136030ustar 00000000000000//! [![github]](https://github.com/dtolnay/inventory) [![crates-io]](https://crates.io/crates/inventory) [![docs-rs]](https://docs.rs/inventory) //! //! [github]: https://img.shields.io/badge/github-8da0cb?style=for-the-badge&labelColor=555555&logo=github //! [crates-io]: https://img.shields.io/badge/crates.io-fc8d62?style=for-the-badge&labelColor=555555&logo=rust //! [docs-rs]: https://img.shields.io/badge/docs.rs-66c2a5?style=for-the-badge&labelColor=555555&logo=docs.rs //! //!
//! //! **Typed distributed plugin registration.** //! //! This crate provides a way to set up a plugin registry into which plugins //! can be registered from any source file linked into your application. There //! does not need to be a central list of all the plugins. //! //! # Examples //! //! Suppose we are writing a command line flags library and want to allow any //! source file in the application to register command line flags that are //! relevant to it. //! //! This is the flag registration style used by [gflags] and is better suited //! for large scale development than maintaining a single central list of flags, //! as the central list would become an endless source of merge conflicts in an //! application developed simultaneously by thousands of developers. //! //! [gflags]: https://gflags.github.io/gflags/ //! //! ## Instantiating the plugin registry //! //! Let's use a `struct Flag` as the plugin type, which will contain the short //! name of the flag like `-v`, the full name like `--verbose`, and maybe other //! information like argument type and help text. We instantiate a plugin //! registry with an invocation of `inventory::collect!`. //! //! ``` //! pub struct Flag { //! short: char, //! name: &'static str, //! /* ... */ //! } //! //! impl Flag { //! pub const fn new(short: char, name: &'static str) -> Self { //! Flag { short, name } //! } //! } //! //! inventory::collect!(Flag); //! ``` //! //! This `collect!` call must be in the same crate that defines the plugin type. //! This macro does not "run" anything so place it outside of any function body. //! //! ## Registering plugins //! //! Now any crate with access to the `Flag` type can register flags as a plugin. //! Plugins can be registered by the same crate that declares the plugin type, //! or by any downstream crate. //! //! ``` //! # struct Flag; //! # //! # impl Flag { //! # const fn new(short: char, name: &'static str) -> Self { //! # Flag //! # } //! # } //! # //! # inventory::collect!(Flag); //! # //! inventory::submit! { //! Flag::new('v', "verbose") //! } //! # //! # fn main() {} //! ``` //! //! The `submit!` macro does not "run" anything so place it outside of any //! function body. In particular, note that all `submit!` invocations across all //! source files linked into your application all take effect simultaneously. A //! `submit!` invocation is not a statement that needs to be called from `main` //! in order to execute. //! //! ## Iterating over plugins //! //! The value `inventory::iter::` is an iterator with element type `&'static //! T` that iterates over all plugins registered of type `T`. //! //! ``` //! # struct Flag { //! # short: char, //! # name: &'static str, //! # } //! # //! # inventory::collect!(Flag); //! # //! for flag in inventory::iter:: { //! println!("-{}, --{}", flag.short, flag.name); //! } //! ``` //! //! There is no guarantee about the order that plugins of the same type are //! visited by the iterator. They may be visited in any order. #![doc(html_root_url = "https://docs.rs/inventory/0.3.2")] #![no_std] #![allow( clippy::doc_markdown, clippy::empty_enum, clippy::expl_impl_clone_on_copy, clippy::let_unit_value, clippy::must_use_candidate, clippy::semicolon_if_nothing_returned, // https://github.com/rust-lang/rust-clippy/issues/7324 )] // Not public API. #[doc(hidden)] pub extern crate core; // Not public API. #[doc(hidden)] pub use ctor::ctor; use core::cell::UnsafeCell; use core::marker::PhantomData; use core::ops::Deref; use core::ptr; use core::sync::atomic::{AtomicPtr, Ordering}; use ghost::phantom; // Not public API. Used by generated code. #[doc(hidden)] pub struct Registry { head: AtomicPtr, } // Not public API. Used by generated code. #[doc(hidden)] pub struct Node { pub value: &'static dyn ErasedNode, pub next: UnsafeCell>, } // The `value` is Sync, and `next` is only mutated during submit, which is prior // to any reads. unsafe impl Sync for Node {} // Not public API. Used by generated code. #[doc(hidden)] pub trait ErasedNode: Sync { // SAFETY: requires *node.value is of type Self. unsafe fn submit(&self, node: &'static Node); } impl ErasedNode for T { unsafe fn submit(&self, node: &'static Node) { T::registry().submit(node); } } /// Trait bound corresponding to types that can be iterated by inventory::iter. /// /// This trait cannot be implemented manually. Instead use the [`collect`] macro /// which expands to an implementation of this trait for the given type. /// /// # Examples /// /// ``` /// use inventory::Collect; /// /// fn count_plugins() -> usize { /// inventory::iter::.into_iter().count() /// } /// ``` pub trait Collect: Sync + Sized + 'static { #[doc(hidden)] fn registry() -> &'static Registry; } impl Registry { // Not public API. Used by generated code. pub const fn new() -> Self { Registry { head: AtomicPtr::new(ptr::null_mut()), } } // SAFETY: requires type of *new.value matches the $ty surrounding the // declaration of this registry in inventory::collect macro. unsafe fn submit(&'static self, new: &'static Node) { let mut head = self.head.load(Ordering::Relaxed); loop { *new.next.get() = head.as_ref(); let new_ptr = new as *const Node as *mut Node; match self .head .compare_exchange(head, new_ptr, Ordering::Release, Ordering::Relaxed) { Ok(_) => return, Err(prev) => head = prev, } } } } /// An iterator over plugins registered of a given type. /// /// The value `inventory::iter::` is an iterator with element type `&'static /// T`. /// /// There is no guarantee about the order that plugins of the same type are /// visited by the iterator. They may be visited in any order. /// /// # Examples /// /// ``` /// # struct Flag { /// # short: char, /// # name: &'static str, /// # } /// # /// # inventory::collect!(Flag); /// # /// # const IGNORE: &str = stringify! { /// use my_flags::Flag; /// # }; /// /// fn main() { /// for flag in inventory::iter:: { /// println!("-{}, --{}", flag.short, flag.name); /// } /// } /// ``` /// /// Refer to the [crate level documentation](index.html) for a complete example /// of instantiating a plugin registry and submitting plugins. #[allow(non_camel_case_types)] #[phantom] pub struct iter; const ITER: () = { fn into_iter() -> Iter { let head = T::registry().head.load(Ordering::Acquire); Iter { // Head pointer is always null or valid &'static Node. node: unsafe { head.as_ref() }, marker: PhantomData, } } impl IntoIterator for iter { type Item = &'static T; type IntoIter = Iter; fn into_iter(self) -> Self::IntoIter { into_iter() } } #[doc(hidden)] impl Deref for iter { type Target = fn() -> Iter; fn deref(&self) -> &Self::Target { &(into_iter as fn() -> Iter) } } #[derive(Clone)] pub struct Iter { node: Option<&'static Node>, marker: PhantomData, } impl Iterator for Iter { type Item = &'static T; fn next(&mut self) -> Option { let node = self.node?; unsafe { let value_ptr = (node.value as *const dyn ErasedNode).cast::(); self.node = *node.next.get(); Some(&*value_ptr) } } } }; /// Associate a plugin registry with the specified type. /// /// This call must be in the same crate that defines the plugin type. This macro /// does not "run" anything so place it outside of any function body. /// /// # Examples /// /// Suppose we are writing a command line flags library and want to allow any /// source file in the application to register command line flags that are /// relevant to it. /// /// This is the flag registration style used by [gflags] and is better suited /// for large scale development than maintaining a single central list of flags, /// as the central list would become an endless source of merge conflicts. /// /// [gflags]: https://gflags.github.io/gflags/ /// /// ``` /// pub struct Flag { /// short: char, /// name: &'static str, /// /* ... */ /// } /// /// inventory::collect!(Flag); /// ``` /// /// Refer to the [crate level documentation](index.html) for a complete example /// of submitting plugins and iterating a plugin registry. #[macro_export] macro_rules! collect { ($ty:ty) => { impl $crate::Collect for $ty { #[inline] fn registry() -> &'static $crate::Registry { static REGISTRY: $crate::Registry = $crate::Registry::new(); ®ISTRY } } }; } /// Enter an element into the plugin registry corresponding to its type. /// /// This call may be in the same crate that defines the type, or downstream in /// any crate that depends on that crate. /// /// This macro does not "run" anything so place it outside of any function body. /// In particular, note that all `submit!` invocations across all source files /// linked into your application all take effect simultaneously. A `submit!` /// invocation is not a statement that needs to be called from `main` in order /// to execute. /// /// # Examples /// /// Put `submit!` invocations outside of any function body. /// /// ``` /// # struct Flag; /// # /// # impl Flag { /// # const fn new(short: char, name: &'static str) -> Self { /// # Flag /// # } /// # } /// # /// # inventory::collect!(Flag); /// # /// inventory::submit! { /// Flag::new('v', "verbose") /// } /// # /// # fn main() {} /// ``` /// /// Do not try to invoke `submit!` from inside of a function body as it does not /// do what you want. /// /// ```compile_fail /// // Do not do this. /// fn submit_flags(has_verbose_flag: bool) { /// if has_verbose_flag { /// inventory::submit! { /// Flag::new('v', "verbose") /// } /// } /// } /// ``` /// /// Refer to the [crate level documentation](index.html) for a complete example /// of instantiating and iterating a plugin registry. #[macro_export] macro_rules! submit { ($($value:tt)*) => { const _: () = { #[allow(non_upper_case_globals)] #[$crate::ctor] fn __init() { static __INVENTORY: $crate::Node = $crate::Node { value: &{ $($value)* }, next: $crate::core::cell::UnsafeCell::new($crate::core::option::Option::None), }; unsafe { $crate::ErasedNode::submit(__INVENTORY.value, &__INVENTORY) } } }; } } #[allow(dead_code)] fn unused() { _ = ITER; } inventory-0.3.2/tests/compiletest.rs000064400000000000000000000002141046102023000157200ustar 00000000000000#[rustversion::attr(not(nightly), ignore)] #[test] fn ui() { let t = trybuild::TestCases::new(); t.compile_fail("tests/ui/*.rs"); } inventory-0.3.2/tests/ui/collect-unsized.rs000064400000000000000000000001061046102023000171110ustar 00000000000000pub struct Unsized(str); inventory::collect!(Unsized); fn main() {} inventory-0.3.2/tests/ui/collect-unsized.stderr000064400000000000000000000014451046102023000177770ustar 00000000000000error[E0277]: the size for values of type `str` cannot be known at compilation time --> tests/ui/collect-unsized.rs:3:1 | 3 | inventory::collect!(Unsized); | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ doesn't have a size known at compile-time | = help: within `Unsized`, the trait `Sized` is not implemented for `str` note: required because it appears within the type `Unsized` --> tests/ui/collect-unsized.rs:1:12 | 1 | pub struct Unsized(str); | ^^^^^^^ note: required by a bound in `Collect` --> src/lib.rs | | pub trait Collect: Sync + Sized + 'static { | ^^^^^ required by this bound in `Collect` = note: this error originates in the macro `inventory::collect` (in Nightly builds, run with -Z macro-backtrace for more info) inventory-0.3.2/tests/ui/non-sync.rs000064400000000000000000000007171046102023000155610ustar 00000000000000use std::rc::Rc; use std::thread; struct Thing(Rc); inventory::collect!(Thing); fn clone_all() { for thing in inventory::iter:: { _ = Rc::clone(&thing.0); } } fn main() { // It would be bad if this were allowed. These threads would race on the // nonatomic reference counts. let thread1 = thread::spawn(clone_all); let thread2 = thread::spawn(clone_all); thread1.join().unwrap(); thread2.join().unwrap(); } inventory-0.3.2/tests/ui/non-sync.stderr000064400000000000000000000013651046102023000164400ustar 00000000000000error[E0277]: `Rc` cannot be shared between threads safely --> tests/ui/non-sync.rs:6:1 | 6 | inventory::collect!(Thing); | ^^^^^^^^^^^^^^^^^^^^^^^^^^ `Rc` cannot be shared between threads safely | = help: within `Thing`, the trait `Sync` is not implemented for `Rc` note: required because it appears within the type `Thing` --> tests/ui/non-sync.rs:4:8 | 4 | struct Thing(Rc); | ^^^^^ note: required by a bound in `Collect` --> src/lib.rs | | pub trait Collect: Sync + Sized + 'static { | ^^^^ required by this bound in `Collect` = note: this error originates in the macro `inventory::collect` (in Nightly builds, run with -Z macro-backtrace for more info) inventory-0.3.2/tests/ui/submit-nonconst.rs000064400000000000000000000002271046102023000171530ustar 00000000000000struct Thing; impl Thing { fn new() -> Self { Thing } } inventory::collect!(Thing); inventory::submit!(Thing::new()); fn main() {} inventory-0.3.2/tests/ui/submit-nonconst.stderr000064400000000000000000000006401046102023000200310ustar 00000000000000error[E0015]: cannot call non-const fn `Thing::new` in statics --> tests/ui/submit-nonconst.rs:11:20 | 11 | inventory::submit!(Thing::new()); | ^^^^^^^^^^^^ | = note: calls in statics are limited to constant functions, tuple structs and tuple variants = note: consider wrapping this expression in `Lazy::new(|| ...)` from the `once_cell` crate: https://crates.io/crates/once_cell inventory-0.3.2/tests/ui/submit-unrecognized.rs000064400000000000000000000000741046102023000200060ustar 00000000000000pub struct Thing; inventory::submit!(Thing); fn main() {} inventory-0.3.2/tests/ui/submit-unrecognized.stderr000064400000000000000000000007531046102023000206710ustar 00000000000000error[E0277]: the trait bound `Thing: Collect` is not satisfied --> tests/ui/submit-unrecognized.rs:3:1 | 3 | inventory::submit!(Thing); | ^^^^^^^^^^^^^^^^^^^^^^^^^ the trait `Collect` is not implemented for `Thing` | = note: required for `Thing` to implement `ErasedNode` = note: required for the cast from `Thing` to the object type `dyn ErasedNode` = note: this error originates in the macro `inventory::submit` (in Nightly builds, run with -Z macro-backtrace for more info)