diff options
Diffstat (limited to 'lazy-static')
-rw-r--r-- | lazy-static/.gitignore | 4 | ||||
-rw-r--r-- | lazy-static/.travis.yml | 34 | ||||
-rw-r--r-- | lazy-static/Cargo.toml | 34 | ||||
-rw-r--r-- | lazy-static/LICENSE-APACHE | 201 | ||||
-rw-r--r-- | lazy-static/LICENSE-MIT | 25 | ||||
-rw-r--r-- | lazy-static/README.md | 79 | ||||
-rw-r--r-- | lazy-static/appveyor.yml | 61 | ||||
-rw-r--r-- | lazy-static/compiletest/Cargo.toml | 11 | ||||
-rw-r--r-- | lazy-static/compiletest/src/lib.rs | 11 | ||||
-rw-r--r-- | lazy-static/compiletest/tests/compile-fail/README.md | 22 | ||||
-rw-r--r-- | lazy-static/compiletest/tests/compile-fail/incorrect_visibility_restriction.rs | 10 | ||||
-rw-r--r-- | lazy-static/compiletest/tests/compile-fail/static_is_private.rs | 14 | ||||
-rw-r--r-- | lazy-static/compiletest/tests/compile-fail/static_is_sized.rs | 11 | ||||
-rw-r--r-- | lazy-static/compiletest/tests/compile_tests.rs | 19 | ||||
-rw-r--r-- | lazy-static/src/core_lazy.rs | 31 | ||||
-rw-r--r-- | lazy-static/src/inline_lazy.rs | 65 | ||||
-rw-r--r-- | lazy-static/src/lib.rs | 212 | ||||
-rw-r--r-- | lazy-static/tests/no_std.rs | 20 | ||||
-rw-r--r-- | lazy-static/tests/test.rs | 162 |
19 files changed, 1026 insertions, 0 deletions
diff --git a/lazy-static/.gitignore b/lazy-static/.gitignore new file mode 100644 index 0000000..bde55ce --- /dev/null +++ b/lazy-static/.gitignore @@ -0,0 +1,4 @@ +target +doc +Cargo.lock +.cargo diff --git a/lazy-static/.travis.yml b/lazy-static/.travis.yml new file mode 100644 index 0000000..f4c3c74 --- /dev/null +++ b/lazy-static/.travis.yml @@ -0,0 +1,34 @@ +language: rust +matrix: + include: + - rust: 1.24.1 + - rust: stable + script: + - cargo test + - cargo test --features spin_no_std + - os: osx + - rust: beta + - rust: nightly + script: + - cargo test + - cargo bench + - cargo test --features spin_no_std + - cargo bench --features spin_no_std + - cd compiletest + - cargo clean + - cargo test + - cd ../ + + - rust: nightly + before_script: + - pip install 'travis-cargo<0.2' --user && export PATH=$HOME/.local/bin:$PATH + script: + - cargo doc --no-deps --all-features + after_success: + - travis-cargo --only nightly doc-upload +script: + - cargo test + +env: + global: + - secure: YXu24LptjeYirjWYjWGsMT2m3mB7LvQATE6TVo7VEUXv8GYoy2ORIHD83PeImxC93MmZ01QeUezRzuCW51ZcK92VnNSBttlF60SvIX18VsJrV92tsAhievFstqYQ+fB8DIuQ8noU0jPz7GpI+R9dlTRSImAqWOnVIghA+Wzz7Js= diff --git a/lazy-static/Cargo.toml b/lazy-static/Cargo.toml new file mode 100644 index 0000000..679f5cd --- /dev/null +++ b/lazy-static/Cargo.toml @@ -0,0 +1,34 @@ +[package] +name = "lazy_static" +# NB: When modifying, also modify html_root_url in lib.rs +version = "1.2.0" +authors = ["Marvin Löbel <loebel.marvin@gmail.com>"] +license = "MIT/Apache-2.0" + +description = "A macro for declaring lazily evaluated statics in Rust." +readme = "README.md" +documentation = "https://docs.rs/lazy_static" + +repository = "https://github.com/rust-lang-nursery/lazy-static.rs" +keywords = ["macro", "lazy", "static"] +categories = [ "no-std", "rust-patterns", "memory-management" ] +exclude = ["/.travis.yml", "/appveyor.yml"] + +[dependencies.spin] +version = "0.4.10" +optional = true +default-features = false +features = ["once"] + +[features] +nightly = [] +spin_no_std = ["spin"] + +[badges] +appveyor = { repository = "rust-lang-nursery/lazy-static.rs" } +travis-ci = { repository = "rust-lang-nursery/lazy-static.rs" } + +is-it-maintained-issue-resolution = { repository = "rust-lang-nursery/lazy-static.rs" } +is-it-maintained-open-issues = { repository = "rust-lang-nursery/lazy-static.rs" } + +maintenance = { status = "passively-maintained" } diff --git a/lazy-static/LICENSE-APACHE b/lazy-static/LICENSE-APACHE new file mode 100644 index 0000000..16fe87b --- /dev/null +++ b/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/lazy-static/LICENSE-MIT b/lazy-static/LICENSE-MIT new file mode 100644 index 0000000..25597d5 --- /dev/null +++ b/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/lazy-static/README.md b/lazy-static/README.md new file mode 100644 index 0000000..d96cdf8 --- /dev/null +++ b/lazy-static/README.md @@ -0,0 +1,79 @@ +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. + +[![Travis-CI Status](https://travis-ci.org/rust-lang-nursery/lazy-static.rs.svg?branch=master)](https://travis-ci.org/rust-lang-nursery/lazy-static.rs) +[![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.24.1+` + +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.2.0" +``` + +...and see the [docs](https://docs.rs/lazy_static) for how to use it. + +# Example + +```rust +#[macro_use] +extern crate lazy_static; + +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap<u32, &'static str> = { + 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 http://www.apache.org/licenses/LICENSE-2.0) + * MIT license ([LICENSE-MIT](LICENSE-MIT) or http://opensource.org/licenses/MIT) + +at your option. + +### Contribution + +Unless you explicitly state otherwise, any contribution intentionally submitted +for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any +additional terms or conditions. diff --git a/lazy-static/appveyor.yml b/lazy-static/appveyor.yml new file mode 100644 index 0000000..b138452 --- /dev/null +++ b/lazy-static/appveyor.yml @@ -0,0 +1,61 @@ +environment: + global: + PROJECT_NAME: lazy_static + # When this was added there were revocation check failures when using the + # libcurl backend as libcurl checks by default, but rustup doesn't provide the + # switch to turn this off. Switch to Hyper which looks to not check for + # revocation by default like libcurl does. + RUSTUP_USE_REQWEST: 1 + CARGO_HTTP_CHECK_REVOKE: false + matrix: + # Stable channel + - TARGET: i686-pc-windows-gnu + CHANNEL: stable + - TARGET: i686-pc-windows-msvc + CHANNEL: stable + - TARGET: x86_64-pc-windows-gnu + CHANNEL: stable + - TARGET: x86_64-pc-windows-msvc + CHANNEL: stable + # Beta channel + - TARGET: i686-pc-windows-gnu + CHANNEL: beta + - TARGET: i686-pc-windows-msvc + CHANNEL: beta + - TARGET: x86_64-pc-windows-gnu + CHANNEL: beta + - TARGET: x86_64-pc-windows-msvc + CHANNEL: beta + # Nightly channel + - TARGET: i686-pc-windows-gnu + CHANNEL: nightly + - TARGET: i686-pc-windows-msvc + CHANNEL: nightly + - TARGET: x86_64-pc-windows-gnu + CHANNEL: nightly + - TARGET: x86_64-pc-windows-msvc + CHANNEL: nightly + +# Install Rust and Cargo +# (Based on from https://github.com/rust-lang/libc/blob/master/appveyor.yml) +install: + - appveyor-retry appveyor DownloadFile https://win.rustup.rs/ -FileName rustup-init.exe + - rustup-init.exe -y --default-toolchain %CHANNEL% --default-host %TARGET% + - set PATH=%PATH%;C:\Users\appveyor\.cargo\bin + - if "%TARGET%" == "i686-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw32\bin + - if "%TARGET%" == "x86_64-pc-windows-gnu" set PATH=%PATH%;C:\msys64\mingw64\bin + - rustc -V + - cargo -V + +build: false + +test_script: + - cargo build --verbose + - cargo test + - if [%CHANNEL%]==[nightly] ( + cd compiletest && + cargo clean && + cargo build --verbose && + cargo test && + cd ../ + ) diff --git a/lazy-static/compiletest/Cargo.toml b/lazy-static/compiletest/Cargo.toml new file mode 100644 index 0000000..e25d5a7 --- /dev/null +++ b/lazy-static/compiletest/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "lazy_static_compiletest" +version = "0.0.1" +publish = false +authors = ["lazy_static contributors"] + +[dependencies.lazy_static] +path = "../" + +[dependencies.compiletest_rs] +version = "0.3" diff --git a/lazy-static/compiletest/src/lib.rs b/lazy-static/compiletest/src/lib.rs new file mode 100644 index 0000000..0452765 --- /dev/null +++ b/lazy-static/compiletest/src/lib.rs @@ -0,0 +1,11 @@ +/* +This library is a shim around `lazy_static` that disambiguates it with the `lazy_static` +that's shipped with the Rust toolchain. We re-export the entire public API of `lazy_static` +under a different crate name so that can be imported in the compile tests. + +This currently appears to use the right local build of `lazy_static`. +*/ + +extern crate lazy_static; + +pub use self::lazy_static::*; diff --git a/lazy-static/compiletest/tests/compile-fail/README.md b/lazy-static/compiletest/tests/compile-fail/README.md new file mode 100644 index 0000000..58dbc3b --- /dev/null +++ b/lazy-static/compiletest/tests/compile-fail/README.md @@ -0,0 +1,22 @@ +This directory contains snippets of code that should yield a +warning/note/help/error at compilation. Syntax of annotations is described in +[rust documentation](https://github.com/rust-lang/rust/blob/master/src/test/COMPILER_TESTS.md). +For more information check out [`compiletest` crate](https://github.com/laumann/compiletest-rs). + +To run compile tests issue `cargo +nightly --test`. + +## Notes on working with `compiletest` crate + +* Currently code that is inside macro should not be annotated, as `compiletest` + crate cannot deal with the fact that macro invocations effectively changes + line numbering. To prevent this add a `// error-pattern:<your error message here>` + on the top of the file and make sure that you set `deny` lint level + if you want to test compiler message different than error. +* `compiletest` crate by default sets `allow(dead_code)` lint level so make sure + that you change it to something suiting your needs even if the warning is + issued prior to any macro invocation. +* If you get a message `error: 0 unexpected errors found, 1 expected errors not found` + despite the fact that some error was bound to occur don't worry - it's a known + issue in the `compiletest` crate and your error was probably not registered - + make sure that your annotations are correct and that you are setting correct + lint levels. diff --git a/lazy-static/compiletest/tests/compile-fail/incorrect_visibility_restriction.rs b/lazy-static/compiletest/tests/compile-fail/incorrect_visibility_restriction.rs new file mode 100644 index 0000000..360e23d --- /dev/null +++ b/lazy-static/compiletest/tests/compile-fail/incorrect_visibility_restriction.rs @@ -0,0 +1,10 @@ +// incorrect visibility restriction +#[macro_use] +extern crate lazy_static_compiletest as lazy_static; + +lazy_static! { + pub(nonsense) static ref WRONG: () = (); + //~^ ERROR incorrect visibility restriction +} + +fn main() { } diff --git a/lazy-static/compiletest/tests/compile-fail/static_is_private.rs b/lazy-static/compiletest/tests/compile-fail/static_is_private.rs new file mode 100644 index 0000000..6ebc8f5 --- /dev/null +++ b/lazy-static/compiletest/tests/compile-fail/static_is_private.rs @@ -0,0 +1,14 @@ +#[macro_use] +extern crate lazy_static_compiletest as lazy_static; + +mod outer { + pub mod inner { + lazy_static! { + pub(in outer) static ref FOO: () = (); + } + } +} + +fn main() { + assert_eq!(*outer::inner::FOO, ()); //~ ERROR static `FOO` is private +} diff --git a/lazy-static/compiletest/tests/compile-fail/static_is_sized.rs b/lazy-static/compiletest/tests/compile-fail/static_is_sized.rs new file mode 100644 index 0000000..ac1cad4 --- /dev/null +++ b/lazy-static/compiletest/tests/compile-fail/static_is_sized.rs @@ -0,0 +1,11 @@ +// error-pattern:the size for values of type `str` cannot be known at compilation time +#[macro_use] +extern crate lazy_static_compiletest as lazy_static; + +lazy_static! { + pub static ref FOO: str = panic!(); +} + + +fn main() { +} diff --git a/lazy-static/compiletest/tests/compile_tests.rs b/lazy-static/compiletest/tests/compile_tests.rs new file mode 100644 index 0000000..d908077 --- /dev/null +++ b/lazy-static/compiletest/tests/compile_tests.rs @@ -0,0 +1,19 @@ +extern crate compiletest_rs as compiletest; + +fn run_mode(mode: &'static str) { + let mut config = compiletest::Config::default(); + config.mode = mode.parse().expect("Invalid mode"); + config.src_base = ["tests", mode].iter().collect(); + + config.verbose = true; + + config.target_rustcflags = Some("-L target/debug/ -L target/debug/deps/".to_owned()); + config.clean_rmeta(); + + compiletest::run_tests(&config); +} + +#[test] +fn compile_test() { + run_mode("compile-fail"); +} diff --git a/lazy-static/src/core_lazy.rs b/lazy-static/src/core_lazy.rs new file mode 100644 index 0000000..b66c3e0 --- /dev/null +++ b/lazy-static/src/core_lazy.rs @@ -0,0 +1,31 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate spin; + +use self::spin::Once; + +pub struct Lazy<T: Sync>(Once<T>); + +impl<T: Sync> Lazy<T> { + pub const INIT: Self = Lazy(Once::INIT); + + #[inline(always)] + pub fn get<F>(&'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/lazy-static/src/inline_lazy.rs b/lazy-static/src/inline_lazy.rs new file mode 100644 index 0000000..268dd45 --- /dev/null +++ b/lazy-static/src/inline_lazy.rs @@ -0,0 +1,65 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +extern crate core; +extern crate std; + +use self::std::prelude::v1::*; +use self::std::cell::Cell; +use self::std::sync::Once; +pub use self::std::sync::ONCE_INIT; + +// FIXME: Replace Option<T> with MaybeInitialized<T> +pub struct Lazy<T: Sync>(Cell<Option<T>>, Once); + +impl<T: Sync> Lazy<T> { + pub const INIT: Self = Lazy(Cell::new(None), ONCE_INIT); + + #[inline(always)] + pub fn get<F>(&'static self, f: F) -> &T + where + F: FnOnce() -> T, + { + self.1.call_once(|| { + self.0.set(Some(f())); + }); + + // `self.0` is guaranteed to be `Some` by this point + // The `Once` will catch and propegate panics + unsafe { + match *self.0.as_ptr() { + Some(ref x) => x, + None => { + debug_assert!(false, "attempted to derefence an uninitialized lazy static. This is a bug"); + + unreachable_unchecked() + }, + } + } + } +} + +unsafe impl<T: Sync> Sync for Lazy<T> {} + +#[macro_export] +#[doc(hidden)] +macro_rules! __lazy_static_create { + ($NAME:ident, $T:ty) => { + static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT; + }; +} + +/// Polyfill for std::hint::unreachable_unchecked. There currently exists a +/// [crate](https://docs.rs/unreachable) for an equivalent to std::hint::unreachable_unchecked, but +/// lazy_static currently doesn't include any runtime dependencies and we've chosen to include this +/// short polyfill rather than include a new crate in every consumer's build. +/// +/// This should be replaced by std's version when lazy_static starts to require at least Rust 1.27. +unsafe fn unreachable_unchecked() -> ! { + enum Void {} + match std::mem::uninitialized::<Void>() {} +} diff --git a/lazy-static/src/lib.rs b/lazy-static/src/lib.rs new file mode 100644 index 0000000..42dc405 --- /dev/null +++ b/lazy-static/src/lib.rs @@ -0,0 +1,212 @@ +// Copyright 2016 lazy-static.rs Developers +// +// Licensed under the Apache License, Version 2.0, <LICENSE-APACHE or +// http://apache.org/licenses/LICENSE-2.0> or the MIT license <LICENSE-MIT or +// http://opensource.org/licenses/MIT>, at your option. This file may not be +// copied, modified, or distributed except according to those terms. + +/*! +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 +# #[macro_use] +# extern crate 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<TYPE>` 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 +#[macro_use] +extern crate lazy_static; + +use std::collections::HashMap; + +lazy_static! { + static ref HASHMAP: HashMap<u32, &'static str> = { + 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 two cargo features: + +- `nightly`: This uses unstable language features only available on the nightly release channel for a more optimal implementation. In practice this currently means avoiding a heap allocation per static. This feature might get deprecated at a later point once all relevant optimizations are usable from stable. +- `spin_no_std` (implies `nightly`): This allows using this crate in a no-std environment, by depending on the standalone `spin` crate. + +Both features depend on unstable language features, which means +no guarantees can be made about them in regard to SemVer stability. + +*/ + +#![doc(html_root_url = "https://docs.rs/lazy_static/1.2.0")] +#![no_std] + +#[cfg(not(feature = "spin_no_std"))] +#[path="inline_lazy.rs"] +#[doc(hidden)] +pub mod lazy; + +#[cfg(feature = "spin_no_std")] +#[path="core_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)] + $($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 +/// #[macro_use] +/// extern crate lazy_static; +/// +/// lazy_static! { +/// static ref BUFFER: Vec<u8> = (0..65537).collect(); +/// } +/// +/// fn main() { +/// lazy_static::initialize(&BUFFER); +/// +/// // ... +/// work_with_initialized_data(&BUFFER); +/// } +/// # fn work_with_initialized_data(_: &[u8]) {} +/// ``` +pub fn initialize<T: LazyStatic>(lazy: &T) { + LazyStatic::initialize(lazy); +} diff --git a/lazy-static/tests/no_std.rs b/lazy-static/tests/no_std.rs new file mode 100644 index 0000000..f94a1aa --- /dev/null +++ b/lazy-static/tests/no_std.rs @@ -0,0 +1,20 @@ +#![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/lazy-static/tests/test.rs b/lazy-static/tests/test.rs new file mode 100644 index 0000000..654abc5 --- /dev/null +++ b/lazy-static/tests/test.rs @@ -0,0 +1,162 @@ +#[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<u32>; 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<u32, &'static str> = { + 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::<i32, u32>(-1) + }; +} + +lazy_static! { + static ref S1: &'static str = "a"; + static ref S2: &'static str = "b"; +} +lazy_static! { + static ref S3: String = [*S1, *S2].join(""); +} + +#[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<u32> = Box::new(0); + static ref BAR: Box<u32> = Box::new(98); + } + + pub mod inner { + lazy_static! { + pub(in visibility) static ref BAZ: Box<u32> = Box::new(42); + pub(crate) static ref BAG: Box<u32> = 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 { 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::ATOMIC_BOOL_INIT; +use std::sync::atomic::Ordering::SeqCst; + +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; +} |