diff options
author | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
---|---|---|
committer | Daniel Baumann <daniel.baumann@progress-linux.org> | 2024-04-28 14:29:10 +0000 |
commit | 2aa4a82499d4becd2284cdb482213d541b8804dd (patch) | |
tree | b80bf8bf13c3766139fbacc530efd0dd9d54394c /third_party/rust/rental | |
parent | Initial commit. (diff) | |
download | firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.tar.xz firefox-2aa4a82499d4becd2284cdb482213d541b8804dd.zip |
Adding upstream version 86.0.1.upstream/86.0.1upstream
Signed-off-by: Daniel Baumann <daniel.baumann@progress-linux.org>
Diffstat (limited to 'third_party/rust/rental')
23 files changed, 1925 insertions, 0 deletions
diff --git a/third_party/rust/rental/.cargo-checksum.json b/third_party/rust/rental/.cargo-checksum.json new file mode 100644 index 0000000000..24a3467710 --- /dev/null +++ b/third_party/rust/rental/.cargo-checksum.json @@ -0,0 +1 @@ +{"files":{"Cargo.toml":"99e1c578dbb4b110ee59a7ba54e0812067bda50b2e39954a86c95db0cbcbc460","LICENSE-APACHE":"a60eea817514531668d7e00765731449fe14d059d3249e0bc93b36de45f759f2","LICENSE-MIT":"0caa93d2b69a83cfb0c2d4db6b782a5dba5ecc4f9fa1f54b04b268af739bf868","README.md":"f45eef4d1177d0b66657e49fbda9dfc963b2a0110e5825e9c9b19d9d9a26dd3d","src/lib.rs":"2cfcf8833642107e34dab2a4457a9c9be144b21dd6d37090444f055067fd551b","tests/clone.rs":"0bf3267771ef8b3bf3c0d0ab98b7e99597c808f50596e0b6c12dfd5598eaf820","tests/complex.rs":"7c7f685e7ae7435698e34f8c29bd5bd8b89143ea43c3381a4627d366902b1285","tests/complex_mut.rs":"374d4a0782b00a5679b55d73b112c424977c0dba525072fadf0fc96ed00f632a","tests/covariant.rs":"fc5697208f44b96047e6423f8b9621a379e29cc5709dcf91f860f1424ef2a0d1","tests/debug.rs":"38e345ca450effc80898a267a1214a72d615441fa31697410ed1465638b85813","tests/drop_order.rs":"8c98fef9f0ea4eac8cebbd384be8c8e8db6d5aaffe42b83a6390e74d91dfd1ac","tests/generic.rs":"2f9d7aa9cc3dd3887b7270835cad8d914150b9809fb41430dc317b14788d3fa5","tests/lt_params.rs":"4f3e9252a35836c4a3a76a68b4fe4eeedb002169b278a0cbc82705716b2a3e6a","tests/map.rs":"314c5cd5163e6bef174fd7a4e37d9b8b9248d4e71f3387f5d6aa29ee784332b7","tests/simple_mut.rs":"beaabd34ed1c06c2f60d05c19c103c32588f52621e7a953e1bf3e2a0759cb09d","tests/simple_ref.rs":"aa64fa94f08926957293129cd26c128c6be21934f026bd052aa9b49a2e8987c7","tests/string.rs":"4e12df6b4e67991c8d912422935f75f2b0016dfa2d26a3305532fc98facc7c67","tests/subrental.rs":"dad1f751c9c8ef3b76e1be6513ae7419ddd16032e5fd71d8baa445d3d3f9e044","tests/target_ty_hack.rs":"d13301dbfb36646eb461928edbb088fe4ed5b01934c12fa1c2b3cd486f7bfb8d","tests/trait.rs":"b3697d80b7b61238401d133f53d058d2e3ad17e6925cc45ed8b8718bcf755e1a","tests/unused.rs":"e420e6d13bcd8b8e3def4a77e8de6502fdf5fd55d44ccad611f16e57c2d67704","tests/vec_slice.rs":"bd2826caeba5ae64268c0e2aed870afacc6d8ba3da850a309b19c7f0b17428eb"},"package":"8545debe98b2b139fb04cad8618b530e9b07c152d99a5de83c860b877d67847f"}
\ No newline at end of file diff --git a/third_party/rust/rental/Cargo.toml b/third_party/rust/rental/Cargo.toml new file mode 100644 index 0000000000..2634b4881d --- /dev/null +++ b/third_party/rust/rental/Cargo.toml @@ -0,0 +1,33 @@ +# 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] +name = "rental" +version = "0.5.5" +authors = ["Jameson Ernst <jameson@jpernst.com>"] +description = "A macro to generate safe self-referential structs, plus premade types for common use cases." +documentation = "https://docs.rs/rental" +readme = "README.md" +keywords = ["lifetime", "ownership", "borrowing", "self", "reference"] +categories = ["rust-patterns", "no-std"] +license = "MIT/Apache-2.0" +repository = "https://github.com/jpernst/rental" +[dependencies.rental-impl] +version = "=0.5.5" + +[dependencies.stable_deref_trait] +version = "1.0.0" +default-features = false + +[features] +default = ["std"] +std = ["stable_deref_trait/std"] diff --git a/third_party/rust/rental/LICENSE-APACHE b/third_party/rust/rental/LICENSE-APACHE new file mode 100644 index 0000000000..16fe87b06e --- /dev/null +++ b/third_party/rust/rental/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/third_party/rust/rental/LICENSE-MIT b/third_party/rust/rental/LICENSE-MIT new file mode 100644 index 0000000000..3e0417e5c0 --- /dev/null +++ b/third_party/rust/rental/LICENSE-MIT @@ -0,0 +1,25 @@ +Copyright (c) 2016 Jameson Ernst + +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/third_party/rust/rental/README.md b/third_party/rust/rental/README.md new file mode 100644 index 0000000000..4124f178cf --- /dev/null +++ b/third_party/rust/rental/README.md @@ -0,0 +1,47 @@ +# Rental - A macro to generate safe self-referential structs, plus premade types for common use cases. + +[Documentation](http://docs.rs/rental) + +# Overview +It can sometimes occur in the course of designing an API that it would be convenient, or even necessary, to allow fields within a struct to hold references to other fields within that same struct. Rust's concept of ownership and borrowing is powerful, but can't express such a scenario yet. +//! +Creating such a struct manually would require unsafe code to erase lifetime parameters from the field types. Accessing the fields directly would be completely unsafe as a result. This library addresses that issue by allowing access to the internal fields only under carefully controlled circumstances, through closures that are bounded by generic lifetimes to prevent infiltration or exfiltration of any data with an incorrect lifetime. In short, while the struct internally uses unsafe code to store the fields, the interface exposed to the consumer of the struct is completely safe. The implementation of this interface is subtle and verbose, hence the macro to automate the process. + +The API of this crate consists of the `rental` macro that generates safe self-referential structs, a few example instantiations to demonstrate the API provided by such structs (see `examples`), and a module of premade instantiations to cover common use cases (see `common`). + +# Example +One instance where this crate is useful is when working with `libloading`. That crate provides a `Library` struct that defines methods to borrow `Symbol`s from it. These symbols are bounded by the lifetime of the library, and are thus considered a borrow. Under normal circumstances, one would be unable to store both the library and the symbols within a single struct, but the macro defined in this crate allows you to define a struct that is capable of storing both simultaneously, like so: + +```rust,ignore +rental! { + pub mod rent_libloading { + use libloading; + + #[rental(deref_suffix)] // This struct will deref to the Deref::Target of Symbol. + pub struct RentSymbol<S: 'static> { + lib: Box<libloading::Library>, // Library is boxed for StableDeref. + sym: libloading::Symbol<'lib, S>, // The 'lib lifetime borrows lib. + } + } +} + +fn main() { + let lib = libloading::Library::new("my_lib.so").unwrap(); // Open our dylib. + if let Ok(rs) = rent_libloading::RentSymbol::try_new( + Box::new(lib), + |lib| unsafe { lib.get::<extern "C" fn()>(b"my_symbol") }) // Loading symbols is unsafe. + { + (*rs)(); // Call our function + }; +} +``` + +In this way we can store both the `Library` and the `Symbol` that borrows it in a single struct. We can even tell our struct to deref to the function pointer itself so we can easily call it. This is legal because the function pointer does not contain any of the special lifetimes introduced by the rental struct in its type signature, which means reborrowing will not expose them to the outside world. As an aside, the `unsafe` block for loading the symbol is necessary because the act of loading a symbol from a dylib is unsafe, and is unrelated to rental. + +# Limitations +There are a few limitations with the current implementation due to bugs or pending features in rust itself. These will be lifted once the underlying language allows it. + +* Currently, the rental struct itself can only take lifetime parameters under certain conditions. These conditions are difficult to fully describe, but in general, a lifetime param of the rental struct itself must appear "outside" of any special rental lifetimes in the type signatures of the struct fields. To put it another way, replacing the rental lifetimes with `'static` must still produce legal types, otherwise it will not compile. In most situations this is fine, since most of the use cases for this library involve erasing all of the lifetimes anyway, but there's no reason why the head element of a rental struct shouldn't be able to take arbitrary lifetime params. This is currently impossible to fully support due to lack of an `'unsafe` lifetime or equivalent feature. +* Prefix fields, and the head field if it IS a subrental, must be of the form `Foo<T>` where `Foo` is some `StableDeref` container, or rental will not be able to correctly guess the `Deref::Target` of the type. If you are using a custom type that does not fit this pattern, you can use the `target_ty` attribute on the field to manually specify the target type. If the head field is NOT a subrental, then it may have any form as long as it is `StableDeref`. +* Rental structs can only have a maximum of 32 rental lifetimes, including transitive rental lifetimes from subrentals. This limitation is the result of needing to implement a new trait for each rental arity. This limit can be easily increased if necessary. +* The references received in the constructor closures don't currently have their lifetime relationship to eachother expressed in bounds, since HRTB lifetimes do not currently support bounds. This is not a soundness hole, but it does prevent some otherwise valid uses from compiling. diff --git a/third_party/rust/rental/src/lib.rs b/third_party/rust/rental/src/lib.rs new file mode 100644 index 0000000000..d7c9f8aaaf --- /dev/null +++ b/third_party/rust/rental/src/lib.rs @@ -0,0 +1,487 @@ +//! A macro to generate safe self-referntial structs, plus premade types for common use cases. +//! +//! # Overview +//! It can sometimes occur in the course of designing an API that it would be convenient, or even necessary, to allow fields within a struct to hold references to other fields within that same struct. Rust's concept of ownership and borrowing is powerful, but can't express such a scenario yet. +//! +//! Creating such a struct manually would require unsafe code to erase lifetime parameters from the field types. Accessing the fields directly would be completely unsafe as a result. This library addresses that issue by allowing access to the internal fields only under carefully controlled circumstances, through closures that are bounded by generic lifetimes to prevent infiltration or exfiltration of any data with an incorrect lifetime. In short, while the struct internally uses unsafe code to store the fields, the interface exposed to the consumer of the struct is completely safe. The implementation of this interface is subtle and verbose, hence the macro to automate the process. +//! +//! The API of this crate consists of the [`rental`](macro.rental.html) macro that generates safe self-referential structs, a few example instantiations to demonstrate the API provided by such structs (see [`examples`](examples/index.html)), and a module of premade instantiations to cover common use cases (see [`common`](common/index.html)). +//! +//! # Example +//! One instance where this crate is useful is when working with `libloading`. That crate provides a `Library` struct that defines methods to borrow `Symbol`s from it. These symbols are bounded by the lifetime of the library, and are thus considered a borrow. Under normal circumstances, one would be unable to store both the library and the symbols within a single struct, but the macro defined in this crate allows you to define a struct that is capable of storing both simultaneously, like so: +//! +//! ```rust,ignore +//! rental! { +//! pub mod rent_libloading { +//! use libloading; +//! +//! #[rental(deref_suffix)] // This struct will deref to the Deref::Target of Symbol. +//! pub struct RentSymbol<S: 'static> { +//! lib: Box<libloading::Library>, // Library is boxed for StableDeref. +//! sym: libloading::Symbol<'lib, S>, // The 'lib lifetime borrows lib. +//! } +//! } +//! } +//! +//! fn main() { +//! let lib = libloading::Library::new("my_lib.so").unwrap(); // Open our dylib. +//! if let Ok(rs) = rent_libloading::RentSymbol::try_new( +//! Box::new(lib), +//! |lib| unsafe { lib.get::<extern "C" fn()>(b"my_symbol") }) // Loading symbols is unsafe. +//! { +//! (*rs)(); // Call our function +//! }; +//! } +//! ``` +//! +//! In this way we can store both the `Library` and the `Symbol` that borrows it in a single struct. We can even tell our struct to deref to the function pointer itself so we can easily call it. This is legal because the function pointer does not contain any of the special lifetimes introduced by the rental struct in its type signature, which means reborrowing will not expose them to the outside world. As an aside, the `unsafe` block for loading the symbol is necessary because the act of loading a symbol from a dylib is unsafe, and is unrelated to rental. +//! +//! **NOTE for Rust 2018:** Relying on implicit crate imports may cause compile errors in code generated by this macro. To avoid this, import the crate manually like so: +//! ```rust,ignore +//! #[macro_use] +//! extern crate rental; +//! ``` +//! +//! # Limitations +//! There are a few limitations with the current implementation due to bugs or pending features in rust itself. These will be lifted once the underlying language allows it. +//! +//! * Currently, the rental struct itself can only take lifetime parameters under certain conditions. These conditions are difficult to fully describe, but in general, a lifetime param of the rental struct itself must appear "outside" of any special rental lifetimes in the type signatures of the struct fields. To put it another way, replacing the rental lifetimes with `'static` must still produce legal types, otherwise it will not compile. In most situations this is fine, since most of the use cases for this library involve erasing all of the lifetimes anyway, but there's no reason why the head element of a rental struct shouldn't be able to take arbitrary lifetime params. This is currently impossible to fully support due to lack of an `'unsafe` lifetime or equivalent feature. +//! * Prefix fields, and the head field if it IS a subrental, must be of the form `Foo<T>` where `Foo` is some `StableDeref` container, or rental will not be able to correctly guess the `Deref::Target` of the type. If you are using a custom type that does not fit this pattern, you can use the `target_ty` attribute on the field to manually specify the target type. If the head field is NOT a subrental, then it may have any form as long as it is `StableDeref`. +//! * Rental structs can only have a maximum of 32 rental lifetimes, including transitive rental lifetimes from subrentals. This limitation is the result of needing to implement a new trait for each rental arity. This limit can be easily increased if necessary. +//! * The references received in the constructor closures don't currently have their lifetime relationship to eachother expressed in bounds, since HRTB lifetimes do not currently support bounds. This is not a soundness hole, but it does prevent some otherwise valid uses from compiling. + + +#![cfg_attr(not(feature = "std"), no_std)] + +#[cfg(feature = "std")] +extern crate core; +#[macro_use] +extern crate rental_impl; +extern crate stable_deref_trait; + +#[doc(hidden)] +pub use rental_impl::*; + + +/// This trait converts any `*_Borrow` or `*_BorrowMut` structs generated by the [`rental`](macro.rental.html) macro into their suffix (most dependent) field. +/// +/// When you own a borrow struct, such as in the body of the closure provided to the `rent_all` or `ref_rent_all` methods of a rental struct, you can call `into_suffix()` to discard the borrow struct and obtain the suffix field if you don't need any of the other fields. +pub trait IntoSuffix { + /// Type of the transitive suffix of the borrow struct. + /// + /// If the suffix field of the borrow struct is itself a borrow struct of a subrental, then this type is the suffix of that nested borrow struct, recursively. + type Suffix; + + /// Discard the borrow struct and return the transitive suffix field. + /// + /// If the suffix field of the borrow struct is itself a borrow struct of a subrental, then this function will return the nested suffix of that borrow struct, recursively. + fn into_suffix(self) -> <Self as IntoSuffix>::Suffix; +} + + +/// An error wrapper returned by the `try_new` method of a rental struct. +/// +/// This will contain the first error returned by the closure chain, as well as the original head value you passed in so you can do something else with it. +pub struct RentalError<E, H> (pub E, pub H); + +pub type RentalResult<T, E, H> = Result<T, RentalError<E, H>>; + + +macro_rules! define_rental_traits { + ($max_arity:expr) => { + #[allow(unused)] + #[derive(__rental_traits)] + enum ProceduralMasqueradeDummyType { + Input = (0, stringify!($max_arity)).0 + } + }; +} + + +#[doc(hidden)] +pub mod __rental_prelude { + pub use core::marker::PhantomData; + pub use core::clone::Clone; + pub use core::ops::{FnOnce, Deref, DerefMut, Drop}; + pub use core::convert::{AsRef, AsMut, Into}; + pub use core::borrow::{Borrow, BorrowMut}; + pub use core::mem::transmute; + pub use core::result::Result; + pub use core::option::Option; + pub use core::fmt; + pub use stable_deref_trait::{StableDeref, CloneStableDeref}; + + pub use super::{IntoSuffix, RentalError, RentalResult}; + + + define_rental_traits!(32); + + + #[inline(always)] + pub fn static_assert_stable_deref<T: StableDeref>() { } + #[inline(always)] + pub fn static_assert_mut_stable_deref<T: DerefMut + StableDeref>() { } +} + + +/// The bedrock of this crate, this macro will generate self-referential structs. +/// +/// This macro is invoked in item position. The body parses as valid rust and contains no special syntax. Only certain constructs are allowed, and a few special attributes and lifetimes are recognized. +/// +/// To start, the top level item of the macro invocation must be a single module. This module will contain all items that the macro generates and export them to you. Within the module, only three types of items are accepted: `use` statements, type aliases, and struct definitions. The `use` statements and type aliases are passed directly through with no special consideration; the primary concern is the struct definitions. +/// +/// First, all struct definitions must have a `#[rental]` or `#[rental_mut]` attribute to indicate that they are self-referential. The `mut` variant indicates that the struct mutably borrows itself, while the normal attribute assumes shared borrows. These attributes also accept certain flags to enable specific features, described below. +/// +/// Next, the structs must have named fields (no tuple structs) and they must have at least 2 fields, since a struct with 1 field can't meaningfully reference itself anyway. +/// +/// The order of the fields is significant, as they are declared in order of least to most dependent. The first field, also referred to as the "head" of the struct, contains no self-references, the second field may borrow the first, the third field may borrow the second or first, and so on. The chain of fields after the head is called the "tail". +/// +/// Because rental structs are self-referential, special care is taken to ensure that moving the struct will not invalidate any internal references. This is accomplished by requiring all fields but the last one, collectively known as the "prefix" of the struct, to implement [`StableDeref`](https://crates.io/crates/stable_deref_trait). This is not required for the final field of the struct, known as the "suffix", since nothing holds a reference to it. +/// +/// NOTE: Because of a workaround for a compiler bug, rental might not always correctly determine the `Deref::Target` type of your prefix fields. If you receive type errors when compiling, you can try using the `target_ty` attribute on the field of the struct. Set this attribute equal to a string that names the correct target type (e.g. `#[target_ty = "[u8]"]` for `Vec<u8>`. +/// +/// Each field that you declare creates a special lifetime of the same name that can be used by later fields to borrow it. This is how the referential relationships are established in the struct definition. +/// +/// This is a all a bit to chew on so far, so let's stop and take a look at an example: +/// +/// ```rust +/// # #[macro_use] extern crate rental; +/// pub struct Foo { i: i32 } +/// pub struct Bar<'a> { foo: &'a Foo } +/// pub struct Qux<'a: 'b, 'b> { bar: &'b Bar<'a> } +/// +/// rental! { +/// mod my_rentals { +/// use super::*; +/// +/// #[rental] +/// pub struct MyRental { +/// foo: Box<Foo>, +/// bar: Box<Bar<'foo>>, +/// qux: Qux<'foo, 'bar>, +/// } +/// } +/// } +/// # fn main () { } +/// ``` +/// +/// Here we see each field use the special lifetimes of the previous fields to establish the borrowing chain. +/// +/// In addition to the rental struct itself, two other structs are generated, with `_Borrow` and `_BorrowMut` appended to the original struct name (e.g. `MyRental_Borrow` and `MyRental_BorrowMut`). These structs contain the same fields as the original struct, but are borrows of the originals. These structs are passed into certain closures that you provide to the [`rent_all`](examples/struct.RentRef.html#method.rent_all) suite of methods to allow you access to the struct's fields. For mutable rentals, these structs will only contain a borrow of the suffix; the other fields will be erased with `PhantomData`. +/// +/// # Attribute Flags +/// +/// A `rental` or `rental_mut` attribute accepts various options that affect the code generated by the macro to add certain features if your type supports them. These flags are placed in parens after the attribute, similar to the `cfg` attribute, e.g. `#[rental(debug)]`. +/// +/// ## debug +/// If all the fields of your struct implement `Debug` then you can use the `debug` option on the rental attribute to gain a `Debug` impl on the struct itself. For mutable rental structs, only the suffix field needs to be `Debug`, as it is the only one that will be printed. The prefix fields are mutably borrowed so cannot be accessed while the suffix exists. +/// +/// ## clone +/// If the prefix fields of your struct impl `CloneStableDeref` (which means clones still deref to the same object), and the suffix field is `Clone`, then your rental struct can be `Clone` as well. +/// +/// ## deref_suffix / deref_mut_suffix +/// If the suffix field of the struct implements `Deref` or `DerefMut`, you can add a `deref_suffix` or `deref_mut_suffix` argument to the `rental` attribute on the struct. This will generate a `Deref` implementation for the rental struct itself that will deref through the suffix and return the borrow to you, for convenience. Note, however, that this will only be legal if none of the special rental lifetimes appear in the type signature of the deref target. If they do, exposing them to the outside world could result in unsafety, so this is not allowed and such a scenario will not compile. +/// +/// ## covariant +/// Since the true lifetime of a self-referential field is currently inexpressible in rust, the lifetimes the fields use internally are fake. This means that directly borrowing the fields of the struct would be quite unsafe. However, if we know that the type is covariant over its lifetime parameters, then we can reborrow away the fake rental lifetimes to something concrete and safe. This tag will provide methods that access the fields of the struct directly, while also ensuring that the covariance requirement is met, otherwise the struct will fail to compile. For an exmaple see [`SimpleRefCovariant`](examples/struct.SimpleRefCovariant.html). +/// +/// ## map_suffix = "T" +/// For rental structs that contain some kind of smart reference as their suffix field, such as a `Ref` or `MutexGuard`, it can be useful to be able to map the reference to another type. This option allows you to do so, given certain conditions. First, your rental struct must have a type parameter in the position that you want to map, such as `Ref<'head, T>` or `MutexGuard<'head, T>`. Second, this type param must ONLY be used in the suffix field. Specify the type parameter you wish to use with `map_suffix = "T"` where `T` is the name of the type param that satisfies these conditions. For an example of the methods this option provides, see [`SimpleRefMap`](examples/struct.SimpleRefMap.html). +/// +/// # Subrentals +/// +/// Finally, there is one other capability to discuss. If a rental struct has been defined elsewhere, either in our own crate or in a dependency, we'd like to be able to chain our own rental struct off of it. In this way, we can use another rental struct as a sort of pre-packaged prefix of our own. As a variation on the above example, it would look like this: +/// +/// ```rust +/// # #[macro_use] extern crate rental; +/// pub struct Foo { i: i32 } +/// pub struct Bar<'a> { foo: &'a Foo } +/// pub struct Qux<'a: 'b, 'b> { bar: &'b Bar<'a> } +/// +/// rental! { +/// mod my_rentals { +/// use super::*; +/// +/// #[rental] +/// pub struct OtherRental { +/// foo: Box<Foo>, +/// bar: Bar<'foo>, +/// } +/// +/// #[rental] +/// pub struct MyRental { +/// #[subrental = 2] +/// prefix: Box<OtherRental>, +/// qux: Qux<'prefix_0, 'prefix_1>, +/// } +/// } +/// } +/// # fn main () { } +/// ``` +/// +/// The first rental struct is fairly standard, so we'll focus on the second one. The head field is given a `subrental` attribute and set equal to an integer indicating the arity. The arity of a rental struct is the number of special lifetimes it creates. As can be seen above, the first struct has two fields, neither of which is itself a subrental, so it has an arity of 2. The arity of the second struct would be 3, since it includes the two fields of the first rental as well as one new one. In this way, arity is transitive. So if we used our new struct itself as a subrental of yet another struct, we'd need to declare the field with `subrental = 3`. The special lifetimes created by a subrental are the field name followed by a `_` and a zero-based index. Also note that the suffix field cannot itself be a subrental, only prefix fields. +/// +/// This covers the essential capabilities of the macro itself. For details on the API of the structs themselves, see the [`examples`](examples/index.html) module. +#[macro_export] +macro_rules! rental { + { + $(#[$attr:meta])* + mod $rental_mod:ident { + $($body:tt)* + } + } => { + $(#[$attr])* + mod $rental_mod { + #[allow(unused_imports)] + use $crate::__rental_prelude; + + #[allow(unused)] + #[derive(__rental_structs_and_impls)] + enum ProceduralMasqueradeDummyType { + Input = (0, stringify!($($body)*)).0 + } + } + }; + { + $(#[$attr:meta])* + pub mod $rental_mod:ident { + $($body:tt)* + } + } => { + $(#[$attr])* + pub mod $rental_mod { + #[allow(unused_imports)] + use $crate::__rental_prelude; + + #[allow(unused)] + #[derive(__rental_structs_and_impls)] + enum ProceduralMasqueradeDummyType { + Input = (0, stringify!($($body)*)).0 + } + } + }; + { + $(#[$attr:meta])* + pub($($vis:tt)*) mod $rental_mod:ident { + $($body:tt)* + } + } => { + $(#[$attr])* + pub($($vis)*) mod $rental_mod { + #[allow(unused_imports)] + use $crate::__rental_prelude; + + #[allow(unused)] + #[derive(__rental_structs_and_impls)] + enum ProceduralMasqueradeDummyType { + Input = (0, stringify!($($body)*)).0 + } + } + }; +} + + +#[cfg(feature = "std")] +rental! { + /// Example types that demonstrate the API generated by the rental macro. + pub mod examples { + use std::sync; + + /// The simplest shared rental. The head is a boxed integer, and the suffix is a ref to that integer. This struct demonstrates the basic API that all shared rental structs have. See [`SimpleMut`](struct.SimpleMut.html) for the mutable analog. + #[rental] + pub struct SimpleRef { + head: Box<i32>, + iref: &'head i32, + } + + /// The simplest mutable rental. Mutable rentals have a slightly different API; compare this struct to [`SimpleRef`](struct.SimpleRef.html) for the clearest picture of how they differ. + #[rental_mut] + pub struct SimpleMut { + head: Box<i32>, + iref: &'head mut i32, + } + + /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `debug` flag enabled. This will provide a `Debug` impl for the struct as long as all of the fields are `Debug`. + #[rental(debug)] + pub struct SimpleRefDebug { + head: Box<i32>, + iref: &'head i32, + } + + /// Similar to [`SimpleRef`](struct.SimpleRef.html), but with the `clone` flag enabled. This will provide a `Clone` impl for the struct as long as the prefix fields are `CloneStableDeref` and the suffix is `Clone` . Notice that the head is an `Arc`, since a clone of an `Arc` will deref to the same object as the original. + #[rental(clone)] + pub struct SimpleRefClone { + head: sync::Arc<i32>, + iref: &'head i32, + } + + /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `deref_suffix` flag enabled. This will provide a `Deref` impl for the struct, which will in turn deref the suffix. Notice that this flag also removes the `self` param from all methods, replacing it with an explicit param. This prevents any rental methods from blocking deref. + #[rental(deref_suffix)] + pub struct SimpleRefDeref { + head: Box<i32>, + iref: &'head i32, + } + + /// Identical to [`SimpleMut`](struct.SimpleMut.html), but with the `deref_mut_suffix` flag enabled. This will provide a `DerefMut` impl for the struct, which will in turn deref the suffix.Notice that this flag also removes the `self` param from all methods, replacing it with an explicit param. This prevents any rental methods from blocking deref. + #[rental_mut(deref_mut_suffix)] + pub struct SimpleMutDeref { + head: Box<i32>, + iref: &'head mut i32, + } + + /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `covariant` flag enabled. For rental structs where the field types have covariant lifetimes, this will allow you to directly borrow the fields, as they can be safely reborrowed to a shorter lifetime. See the [`all`](struct.SimpleRefCovariant.html#method.all) and [`suffix`](struct.SimpleRefCovariant.html#method.suffix) methods. + #[rental(covariant)] + pub struct SimpleRefCovariant { + head: Box<i32>, + iref: &'head i32, + } + + /// Identical to [`SimpleRef`](struct.SimpleRef.html), but with the `map_suffix` flag enabled. This will allow the type of the suffix to be changed by mapping it to another instantiation of the same struct with the different type param. See the [`map`](struct.SimpleRefMap.html#method.map), [`try_map`](struct.SimpleRefMap.html#method.try_map), and [`try_map_or_drop`](struct.SimpleRefMap.html#method.try_map_or_drop) methods. + #[rental(map_suffix = "T")] + pub struct SimpleRefMap<T: 'static> { + head: Box<i32>, + iref: &'head T, + } + } +} + + +#[cfg(feature = "std")] +rental! { + /// Premade types for the most common use cases. + pub mod common { + use std::ops::DerefMut; + use stable_deref_trait::StableDeref; + use std::cell; + use std::sync; + + /// Stores an owner and a shared reference in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentRef; + /// # fn main() { + /// let r = RentRef::new(Box::new(5), |i| &*i); + /// assert_eq!(*r, RentRef::rent(&r, |iref| **iref)); + /// # } + /// ``` + #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")] + pub struct RentRef<H: 'static + StableDeref, T: 'static> { + head: H, + suffix: &'head T, + } + + /// Stores an owner and a mutable reference in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentMut; + /// # fn main() { + /// let mut r = RentMut::new(Box::new(5), |i| &mut *i); + /// *r = 12; + /// assert_eq!(12, RentMut::rent(&mut r, |iref| **iref)); + /// # } + /// ``` + #[rental_mut(debug, deref_mut_suffix, covariant, map_suffix = "T")] + pub struct RentMut<H: 'static + StableDeref + DerefMut, T: 'static> { + head: H, + suffix: &'head mut T, + } + + /// Stores a `RefCell` and a `Ref` in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentRefCell; + /// # fn main() { + /// use std::cell; + /// + /// let r = RentRefCell::new(Box::new(cell::RefCell::new(5)), |c| c.borrow()); + /// assert_eq!(*r, RentRefCell::rent(&r, |c| **c)); + /// # } + /// ``` + #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")] + pub struct RentRefCell<H: 'static + StableDeref, T: 'static> { + head: H, + suffix: cell::Ref<'head, T>, + } + + /// Stores a `RefCell` and a `RefMut` in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentRefCellMut; + /// # fn main() { + /// use std::cell; + /// + /// let mut r = RentRefCellMut::new(Box::new(cell::RefCell::new(5)), |c| c.borrow_mut()); + /// *r = 12; + /// assert_eq!(12, RentRefCellMut::rent(&r, |c| **c)); + /// # } + /// ``` + #[rental_mut(debug, deref_mut_suffix, covariant, map_suffix = "T")] + pub struct RentRefCellMut<H: 'static + StableDeref + DerefMut, T: 'static> { + head: H, + suffix: cell::RefMut<'head, T>, + } + + + /// Stores a `Mutex` and a `MutexGuard` in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentMutex; + /// # fn main() { + /// use std::sync; + /// + /// let mut r = RentMutex::new(Box::new(sync::Mutex::new(5)), |c| c.lock().unwrap()); + /// *r = 12; + /// assert_eq!(12, RentMutex::rent(&r, |c| **c)); + /// # } + /// ``` + #[rental(debug, clone, deref_mut_suffix, covariant, map_suffix = "T")] + pub struct RentMutex<H: 'static + StableDeref + DerefMut, T: 'static> { + head: H, + suffix: sync::MutexGuard<'head, T>, + } + + /// Stores an `RwLock` and an `RwLockReadGuard` in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentRwLock; + /// # fn main() { + /// use std::sync; + /// + /// let r = RentRwLock::new(Box::new(sync::RwLock::new(5)), |c| c.read().unwrap()); + /// assert_eq!(*r, RentRwLock::rent(&r, |c| **c)); + /// # } + /// ``` + #[rental(debug, clone, deref_suffix, covariant, map_suffix = "T")] + pub struct RentRwLock<H: 'static + StableDeref, T: 'static> { + head: H, + suffix: sync::RwLockReadGuard<'head, T>, + } + + /// Stores an `RwLock` and an `RwLockWriteGuard` in the same struct. + /// + /// ```rust + /// # extern crate rental; + /// # use rental::common::RentRwLockMut; + /// # fn main() { + /// use std::sync; + /// + /// let mut r = RentRwLockMut::new(Box::new(sync::RwLock::new(5)), |c| c.write().unwrap()); + /// *r = 12; + /// assert_eq!(12, RentRwLockMut::rent(&r, |c| **c)); + /// # } + /// ``` + #[rental(debug, clone, deref_mut_suffix, covariant, map_suffix = "T")] + pub struct RentRwLockMut<H: 'static + StableDeref, T: 'static> { + head: H, + suffix: sync::RwLockWriteGuard<'head, T>, + } + } +} + + diff --git a/third_party/rust/rental/tests/clone.rs b/third_party/rust/rental/tests/clone.rs new file mode 100644 index 0000000000..043f84a895 --- /dev/null +++ b/third_party/rust/rental/tests/clone.rs @@ -0,0 +1,50 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + +pub struct Bar<'i> { + iref: &'i i32, + misc: i32, +} + +impl <'i> Clone for Bar<'i> { + fn clone (&self) -> Self { + Bar{ + iref: Clone::clone(&self.iref), + misc: Clone::clone(&self.misc), + } + } +} + + +rental! { + mod rentals { + use super::*; + use std::sync::Arc; + + #[rental(clone)] + pub struct FooClone { + foo: Arc<Foo>, + fr: Bar<'foo>, + } + } +} + + +#[test] +fn clone() { + use std::sync::Arc; + + let foo = Foo { i: 5 }; + let rf = rentals::FooClone::new(Arc::new(foo), |foo| Bar{ iref: &foo.i, misc: 12 }); + assert_eq!(5, rf.rent(|f| *f.iref)); + + let rfc = rf.clone(); + assert_eq!(5, rfc.rent(|f| *f.iref)); +} + + diff --git a/third_party/rust/rental/tests/complex.rs b/third_party/rust/rental/tests/complex.rs new file mode 100644 index 0000000000..187e976807 --- /dev/null +++ b/third_party/rust/rental/tests/complex.rs @@ -0,0 +1,115 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + +pub struct Bar<'a> { + foo: &'a Foo, +} + +pub struct Baz<'a: 'b, 'b> { + bar: &'b Bar<'a> +} + +pub struct Qux<'a: 'b, 'b: 'c, 'c> { + baz: &'c Baz<'a, 'b> +} + +pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> { + qux: &'d Qux<'a, 'b, 'c> +} + + +impl Foo { + pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self } } + pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) } + pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) } +} + +impl<'a> Bar<'a> { + pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self } } + pub fn try_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { bar: self }) } + pub fn fail_borrow<'b>(&'b self) -> Result<Baz<'a, 'b>, ()> { Err(()) } +} + +impl<'a: 'b, 'b> Baz<'a, 'b> { + pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self } } + pub fn try_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux { baz: self }) } + pub fn fail_borrow<'c>(&'c self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) } +} + +impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> { + pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self } } + pub fn try_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Ok(Xyzzy { qux: self }) } + pub fn fail_borrow<'d>(&'d self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Err(()) } +} + + +rental! { + mod rentals { + use super::*; + + #[rental] + pub struct ComplexRent { + foo: Box<Foo>, + bar: Box<Bar<'foo>>, + baz: Box<Baz<'foo, 'bar>>, + qux: Box<Qux<'foo, 'bar, 'baz>>, + xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>, + } + } +} + + +#[test] +fn new() { + let foo = Foo { i: 5 }; + let _ = rentals::ComplexRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow()), + |bar, _| Box::new(bar.borrow()), + |baz, _, _| Box::new(baz.borrow()), + |qux, _, _, _| qux.borrow() + ); + + let foo = Foo { i: 5 }; + let cr = rentals::ComplexRent::try_new( + Box::new(foo), + |foo| foo.try_borrow().map(|bar| Box::new(bar)), + |bar, _| bar.try_borrow().map(|baz| Box::new(baz)), + |baz, _, _| baz.try_borrow().map(|qux| Box::new(qux)), + |qux, _, _, _| qux.try_borrow() + ); + assert!(cr.is_ok()); + + let foo = Foo { i: 5 }; + let cr = rentals::ComplexRent::try_new( + Box::new(foo), + |foo| foo.try_borrow().map(|bar| Box::new(bar)), + |bar, _| bar.try_borrow().map(|baz| Box::new(baz)), + |baz, _, _| baz.try_borrow().map(|qux| Box::new(qux)), + |qux, _, _, _| qux.fail_borrow() + ); + assert!(cr.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { i: 5 }; + let cr = rentals::ComplexRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow()), + |bar, _| Box::new(bar.borrow()), + |baz, _, _| Box::new(baz.borrow()), + |qux, _, _, _| qux.borrow() + ); + let i = cr.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i); + assert_eq!(i, 5); + + let iref = cr.ref_rent(|xyzzy| &xyzzy.qux.baz.bar.foo.i); + assert_eq!(*iref, 5); +} diff --git a/third_party/rust/rental/tests/complex_mut.rs b/third_party/rust/rental/tests/complex_mut.rs new file mode 100644 index 0000000000..3ea44440ab --- /dev/null +++ b/third_party/rust/rental/tests/complex_mut.rs @@ -0,0 +1,136 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + +pub struct Bar<'a> { + foo: &'a mut Foo, +} + +pub struct Baz<'a: 'b, 'b> { + bar: &'b mut Bar<'a> +} + +pub struct Qux<'a: 'b, 'b: 'c, 'c> { + baz: &'c mut Baz<'a, 'b> +} + +pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> { + qux: &'d mut Qux<'a, 'b, 'c> +} + + +impl Foo { + pub fn borrow_mut<'a>(&'a mut self) -> Bar<'a> { Bar { foo: self } } + pub fn try_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) } + pub fn fail_borrow_mut<'a>(&'a mut self) -> Result<Bar<'a>, ()> { Err(()) } +} + +impl<'a> Bar<'a> { + pub fn borrow_mut<'b>(&'b mut self) -> Baz<'a, 'b> { Baz { bar: self } } + pub fn try_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Ok(Baz { bar: self }) } + pub fn fail_borrow_mut<'b>(&'b mut self) -> Result<Baz<'a, 'b>, ()> { Err(()) } +} + +impl<'a: 'b, 'b> Baz<'a, 'b> { + pub fn borrow_mut<'c>(&'c mut self) -> Qux<'a, 'b, 'c> { Qux { baz: self } } + pub fn try_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Ok(Qux { baz: self }) } + pub fn fail_borrow_mut<'c>(&'c mut self) -> Result<Qux<'a, 'b, 'c>, ()> { Err(()) } +} + +impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> { + pub fn borrow_mut<'d>(&'d mut self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self } } + pub fn try_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Ok(Xyzzy { qux: self }) } + pub fn fail_borrow_mut<'d>(&'d mut self) -> Result<Xyzzy<'a, 'b, 'c, 'd>, ()> { Err(()) } +} + + +rental! { + mod rentals { + use super::*; + + #[rental_mut] + pub struct ComplexRent { + foo: Box<Foo>, + bar: Box<Bar<'foo>>, + baz: Box<Baz<'foo, 'bar>>, + qux: Box<Qux<'foo, 'bar, 'baz>>, + xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>, + } + } +} + + +#[test] +fn new() { + let foo = Foo { i: 5 }; + let _ = rentals::ComplexRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow_mut()), + |bar| Box::new(bar.borrow_mut()), + |baz| Box::new(baz.borrow_mut()), + |qux| qux.borrow_mut() + ); + + let foo = Foo { i: 5 }; + let cm = rentals::ComplexRent::try_new( + Box::new(foo), + |foo| foo.try_borrow_mut().map(|bar| Box::new(bar)), + |bar| bar.try_borrow_mut().map(|baz| Box::new(baz)), + |baz| baz.try_borrow_mut().map(|qux| Box::new(qux)), + |qux| qux.try_borrow_mut() + ); + assert!(cm.is_ok()); + + let foo = Foo { i: 5 }; + let cm = rentals::ComplexRent::try_new( + Box::new(foo), + |foo| foo.try_borrow_mut().map(|bar| Box::new(bar)), + |bar| bar.try_borrow_mut().map(|baz| Box::new(baz)), + |baz| baz.try_borrow_mut().map(|qux| Box::new(qux)), + |qux| qux.fail_borrow_mut() + ); + assert!(cm.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { i: 5 }; + let cm = rentals::ComplexRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow_mut()), + |bar| Box::new(bar.borrow_mut()), + |baz| Box::new(baz.borrow_mut()), + |qux| qux.borrow_mut() + ); + let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i); + assert_eq!(i, 5); + + let iref = cm.ref_rent(|xyzzy| &xyzzy.qux.baz.bar.foo.i); + assert_eq!(*iref, 5); +} + + +#[test] +fn write() { + let foo = Foo { i: 5 }; + let mut cm = rentals::ComplexRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow_mut()), + |bar| Box::new(bar.borrow_mut()), + |baz| Box::new(baz.borrow_mut()), + |qux| qux.borrow_mut() + ); + + { + let iref: &mut i32 = cm.ref_rent_mut(|xyzzy| &mut xyzzy.qux.baz.bar.foo.i); + *iref = 12; + } + + let i = cm.rent(|xyzzy| xyzzy.qux.baz.bar.foo.i); + assert_eq!(i, 12); +} diff --git a/third_party/rust/rental/tests/covariant.rs b/third_party/rust/rental/tests/covariant.rs new file mode 100644 index 0000000000..545c2714ae --- /dev/null +++ b/third_party/rust/rental/tests/covariant.rs @@ -0,0 +1,52 @@ +#[macro_use] +extern crate rental; + + +//use std::marker::PhantomData; + + +pub struct Foo { + i: i32, +} + + +//pub struct Invariant<'a> { +// iref: &'a i32, +// inv: PhantomData<&'a mut &'a ()>, +//} + + +rental! { + mod rentals { + use super::*; + + #[rental(covariant)] + pub struct SimpleRef { + foo: Box<Foo>, + iref: &'foo i32, + } + + #[rental_mut(covariant)] + pub struct SimpleMut { + foo: Box<Foo>, + iref: &'foo mut i32, + } + +// #[rental(covariant)] +// pub struct ShouldBreak { +// foo: Box<Foo>, +// inv: Invariant<'foo>, +// } + } +} + + +#[test] +fn borrow() { + let foo = Foo { i: 5 }; + let fr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.i); + let b = fr.all(); + assert_eq!(**b.iref, 5); +} + + diff --git a/third_party/rust/rental/tests/debug.rs b/third_party/rust/rental/tests/debug.rs new file mode 100644 index 0000000000..59cf183b9b --- /dev/null +++ b/third_party/rust/rental/tests/debug.rs @@ -0,0 +1,39 @@ +#[macro_use] +extern crate rental; + + +#[derive(Debug)] +pub struct Foo { + i: i32, +} + + +rental! { + mod rentals { + use super::*; + + #[rental(debug, deref_suffix)] + pub struct SimpleRef { + foo: Box<Foo>, + iref: &'foo i32, + } + + #[rental_mut(debug, deref_suffix)] + pub struct SimpleMut { + foo: Box<Foo>, + iref: &'foo mut i32, + } + } +} + + +#[test] +fn print() { + let foo = Foo { i: 5 }; + let sr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.i); + println!("{:?}", sr); + + let foo = Foo { i: 5 }; + let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i); + println!("{:?}", sm); +} diff --git a/third_party/rust/rental/tests/drop_order.rs b/third_party/rust/rental/tests/drop_order.rs new file mode 100644 index 0000000000..642438b8d2 --- /dev/null +++ b/third_party/rust/rental/tests/drop_order.rs @@ -0,0 +1,129 @@ +#![allow(dead_code)] + +#[macro_use] +extern crate rental; + +use std::cell::RefCell; +use std::rc::Rc; + + +pub struct Foo { + i: i32, + d: Rc<RefCell<String>>, +} + +pub struct Bar<'a> { + foo: &'a Foo, + d: Rc<RefCell<String>>, +} + +pub struct Baz<'a: 'b, 'b> { + bar: &'b Bar<'a>, + d: Rc<RefCell<String>>, +} + +pub struct Qux<'a: 'b, 'b: 'c, 'c> { + baz: &'c Baz<'a, 'b>, + d: Rc<RefCell<String>>, +} + +pub struct Xyzzy<'a: 'b, 'b: 'c, 'c: 'd, 'd> { + qux: &'d Qux<'a, 'b, 'c>, + d: Rc<RefCell<String>>, +} + + +impl Foo { + pub fn borrow<'a>(&'a self) -> Bar<'a> { Bar { foo: self, d: self.d.clone() } } +} + +impl Drop for Foo { + fn drop(&mut self) { + self.d.borrow_mut().push_str("Foo"); + } +} + +impl<'a> Bar<'a> { + pub fn borrow<'b>(&'b self) -> Baz<'a, 'b> { Baz { bar: self, d: self.d.clone() } } +} + +impl<'a> Drop for Bar<'a> { + fn drop(&mut self) { + self.d.borrow_mut().push_str("Bar"); + } +} + +impl<'a: 'b, 'b> Baz<'a, 'b> { + pub fn borrow<'c>(&'c self) -> Qux<'a, 'b, 'c> { Qux { baz: self, d: self.d.clone() } } +} + +impl<'a: 'b, 'b> Drop for Baz<'a, 'b> { + fn drop(&mut self) { + self.d.borrow_mut().push_str("Baz"); + } +} + +impl<'a: 'b, 'b: 'c, 'c> Qux<'a, 'b, 'c> { + pub fn borrow<'d>(&'d self) -> Xyzzy<'a, 'b, 'c, 'd> { Xyzzy { qux: self, d: self.d.clone() } } +} + +impl<'a: 'b, 'b: 'c, 'c> Drop for Qux<'a, 'b, 'c> { + fn drop(&mut self) { + self.d.borrow_mut().push_str("Qux"); + } +} + +impl<'a: 'b, 'b: 'c, 'c: 'd, 'd> Drop for Xyzzy<'a, 'b, 'c, 'd> { + fn drop(&mut self) { + self.d.borrow_mut().push_str("Xyzzy"); + } +} + + +rental! { + pub mod rentals { + use super::*; + + #[rental] + pub struct DropTestRent { + foo: Box<Foo>, + bar: Box<Bar<'foo>>, + baz: Box<Baz<'foo, 'bar>>, + qux: Box<Qux<'foo, 'bar, 'baz>>, + xyzzy: Xyzzy<'foo, 'bar, 'baz, 'qux>, + } + } +} + + +#[test] +fn drop_order() { + let d = Rc::new(RefCell::new(String::new())); + { + let foo = Foo { i: 5, d: d.clone() }; + let _ = rentals::DropTestRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow()), + |bar, _| Box::new(bar.borrow()), + |baz, _, _| Box::new(baz.borrow()), + |qux, _, _, _| qux.borrow() + ); + } + assert_eq!(*d.borrow(), "XyzzyQuxBazBarFoo"); + + let d = Rc::new(RefCell::new(String::new())); + { + let foo = Foo { i: 5, d: d.clone() }; + let r = rentals::DropTestRent::new( + Box::new(foo), + |foo| Box::new(foo.borrow()), + |bar, _| Box::new(bar.borrow()), + |baz, _, _| Box::new(baz.borrow()), + |qux, _, _, _| qux.borrow() + ); + + let _head = r.into_head(); + } + assert_eq!(*d.borrow(), "XyzzyQuxBazBarFoo"); +} + diff --git a/third_party/rust/rental/tests/generic.rs b/third_party/rust/rental/tests/generic.rs new file mode 100644 index 0000000000..9043025d62 --- /dev/null +++ b/third_party/rust/rental/tests/generic.rs @@ -0,0 +1,53 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo<T: 'static> { + t: T, +} + +impl<T: 'static> Foo<T> { + fn try_borrow(&self) -> Result<&T, ()> { Ok(&self.t) } + fn fail_borrow(&self) -> Result<&T, ()> { Err(()) } +} + + +rental! { + mod rentals { + type FooAlias<T> = super::Foo<T>; + + #[rental] + pub struct SimpleRef<T: 'static> { + foo: Box<FooAlias<T>>, + tref: &'foo T, + } + } +} + + +#[test] +fn new() { + let foo = Foo { t: 5 }; + let _ = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.t); + + let foo = Foo { t: 5 }; + let sr = rentals::SimpleRef::try_new(Box::new(foo), |foo| foo.try_borrow()); + assert!(sr.is_ok()); + + let foo = Foo { t: 5 }; + let sr = rentals::SimpleRef::try_new(Box::new(foo), |foo| foo.fail_borrow()); + assert!(sr.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { t: 5 }; + + let sr = rentals::SimpleRef::new(Box::new(foo), |foo| &foo.t); + let t: i32 = sr.rent(|tref| **tref); + assert_eq!(t, 5); + + let tref: &i32 = sr.ref_rent(|tref| *tref); + assert_eq!(*tref, 5); +} diff --git a/third_party/rust/rental/tests/lt_params.rs b/third_party/rust/rental/tests/lt_params.rs new file mode 100644 index 0000000000..3ce6d3eee7 --- /dev/null +++ b/third_party/rust/rental/tests/lt_params.rs @@ -0,0 +1,65 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo<'a> { + i: &'a i32, +} + +impl<'a> Foo<'a> { + fn borrow(&self) -> &i32 { self.i } + fn try_borrow(&self) -> Result<&i32, ()> { Ok(self.i) } + fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) } +} + + +rental! { + mod rentals { + use super::*; + + #[rental] + pub struct LtParam<'a> { + foo: Box<Foo<'a>>, + iref: &'foo i32, + } + } +} + + +#[test] +fn new() { + let i = 5; + + let foo = Foo { i: &i }; + let _ = rentals::LtParam::new(Box::new(foo), |foo| foo.borrow()); + + let foo = Foo { i: &i }; + let sr = rentals::LtParam::try_new(Box::new(foo), |foo| foo.try_borrow()); + assert!(sr.is_ok()); + + let foo = Foo { i: &i }; + let sr = rentals::LtParam::try_new(Box::new(foo), |foo| foo.fail_borrow()); + assert!(sr.is_err()); +} + + +#[test] +fn read() { + let i = 5; + + let foo = Foo { i: &i }; + + let mut sr = rentals::LtParam::new(Box::new(foo), |foo| foo.borrow()); + + { + let i: i32 = sr.rent(|iref| **iref); + assert_eq!(i, 5); + } + + { + let iref: &i32 = sr.ref_rent(|iref| *iref); + assert_eq!(*iref, 5); + } + + assert_eq!(sr.rent_all_mut(|borrows| *borrows.foo.i), 5); +} diff --git a/third_party/rust/rental/tests/map.rs b/third_party/rust/rental/tests/map.rs new file mode 100644 index 0000000000..3ef3b94810 --- /dev/null +++ b/third_party/rust/rental/tests/map.rs @@ -0,0 +1,42 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + + +rental! { + mod rentals { + use super::*; + + #[rental(map_suffix = "T")] + pub struct SimpleRef<T: 'static> { + foo: Box<Foo>, + fr: &'foo T, + } + + #[rental_mut(map_suffix = "T")] + pub struct SimpleMut<T: 'static> { + foo: Box<Foo>, + fr: &'foo mut T, + } + } +} + + +#[test] +fn map() { + let foo = Foo { i: 5 }; + let sr = rentals::SimpleRef::new(Box::new(foo), |foo| foo); + let sr = sr.map(|fr| &fr.i); + assert_eq!(sr.rent(|ir| **ir), 5); + + let foo = Foo { i: 12 }; + let sm = rentals::SimpleMut::new(Box::new(foo), |foo| foo); + let sm = sm.map(|fr| &mut fr.i); + assert_eq!(sm.rent(|ir| **ir), 12); +} + + diff --git a/third_party/rust/rental/tests/simple_mut.rs b/third_party/rust/rental/tests/simple_mut.rs new file mode 100644 index 0000000000..c7af358998 --- /dev/null +++ b/third_party/rust/rental/tests/simple_mut.rs @@ -0,0 +1,67 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + +impl Foo { + fn try_borrow_mut(&mut self) -> Result<&mut i32, ()> { Ok(&mut self.i) } + fn fail_borrow_mut(&mut self) -> Result<&mut i32, ()> { Err(()) } +} + + +rental! { + mod rentals { + use super::*; + + #[rental_mut] + pub struct SimpleMut { + foo: Box<Foo>, + iref: &'foo mut i32, + } + } +} + + +#[test] +fn new() { + let foo = Foo { i: 5 }; + let _ = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i); + + let foo = Foo { i: 5 }; + let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.try_borrow_mut()); + assert!(sm.is_ok()); + + let foo = Foo { i: 5 }; + let sm = rentals::SimpleMut::try_new(Box::new(foo), |foo| foo.fail_borrow_mut()); + assert!(sm.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { i: 5 }; + + let sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i); + let i: i32 = sm.rent(|iref| **iref); + assert_eq!(i, 5); + + let iref: &i32 = sm.ref_rent(|iref| *iref); + assert_eq!(*iref, 5); +} + + +#[test] +fn write() { + let foo = Foo { i: 5 }; + + let mut sm = rentals::SimpleMut::new(Box::new(foo), |foo| &mut foo.i); + + { + let iref: &mut i32 = sm.ref_rent_mut(|iref| *iref); + *iref = 12; + assert_eq!(*iref, 12); + } +} diff --git a/third_party/rust/rental/tests/simple_ref.rs b/third_party/rust/rental/tests/simple_ref.rs new file mode 100644 index 0000000000..2cb7765578 --- /dev/null +++ b/third_party/rust/rental/tests/simple_ref.rs @@ -0,0 +1,103 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + i: i32, +} + +impl Foo { + fn try_borrow(&self) -> Result<&i32, ()> { Ok(&self.i) } + fn fail_borrow(&self) -> Result<&i32, ()> { Err(()) } +} + +pub struct FooRef<'i> { + iref: &'i i32, + misc: i32, +} + + +impl<'i> ::std::ops::Deref for FooRef<'i> { + type Target = i32; + + fn deref(&self) -> &i32 { self.iref } +} + + +rental! { + mod rentals { + use super::*; + + #[rental] + pub struct SimpleRef { + foo: Box<Foo>, + fr: FooRef<'foo>, + } + } +} + + +#[test] +fn new() { + let foo = Foo { i: 5 }; + let _ = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 }); + + let foo = Foo { i: 5 }; + let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.try_borrow()?, misc: 12 })); + assert!(sr.is_ok()); + + let foo = Foo { i: 5 }; + let sr: rental::RentalResult<rentals::SimpleRef, (), _> = rentals::SimpleRef::try_new(Box::new(foo), |foo| Ok(FooRef{ iref: foo.fail_borrow()?, misc: 12 })); + assert!(sr.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { i: 5 }; + + let mut sr = rentals::SimpleRef::new(Box::new(foo), |foo| FooRef{ iref: &foo.i, misc: 12 }); + + { + let i: i32 = sr.rent(|iref| **iref); + assert_eq!(i, 5); + } + + { + let iref: &i32 = sr.ref_rent(|fr| fr.iref); + assert_eq!(*iref, 5); + let iref: Option<&i32> = sr.maybe_ref_rent(|fr| Some(fr.iref)); + assert_eq!(iref, Some(&5)); + let iref: Result<&i32, ()> = sr.try_ref_rent(|fr| Ok(fr.iref)); + assert_eq!(iref, Ok(&5)); + } + + { + assert_eq!(sr.head().i, 5); + assert_eq!(sr.rent_all(|borrows| borrows.foo.i), 5); + assert_eq!(sr.rent_all_mut(|borrows| borrows.foo.i), 5); + } + + { + let iref: Option<&i32> = sr.maybe_ref_rent_all(|borrows| Some(borrows.fr.iref)); + assert_eq!(iref, Some(&5)); + let iref: Result<&i32, ()> = sr.try_ref_rent_all(|borrows| Ok(borrows.fr.iref)); + assert_eq!(iref, Ok(&5)); + } + + { + let iref: &mut i32 = sr.ref_rent_all_mut(|borrows| &mut borrows.fr.misc); + *iref = 57; + assert_eq!(*iref, 57); + } + + { + let iref: Option<&mut i32> = sr.maybe_ref_rent_all_mut(|borrows| Some(&mut borrows.fr.misc)); + assert_eq!(iref, Some(&mut 57)); + } + + { + let iref: Result<&mut i32, ()> = sr.try_ref_rent_all_mut(|borrows| Ok(&mut borrows.fr.misc)); + assert_eq!(iref, Ok(&mut 57)); + } +} diff --git a/third_party/rust/rental/tests/string.rs b/third_party/rust/rental/tests/string.rs new file mode 100644 index 0000000000..9f6c7ea9da --- /dev/null +++ b/third_party/rust/rental/tests/string.rs @@ -0,0 +1,30 @@ +#[macro_use] +extern crate rental; + + +rental! { + pub mod rent_string { + #[rental(deref_suffix)] + pub struct OwnedStr { + buffer: String, + slice: &'buffer str, + slice_2: &'slice str, + } + } +} + + +#[test] +fn new() { + let buf = "Hello, World!".to_string(); + let _ = rent_string::OwnedStr::new(buf, |slice| slice, |slice, _| slice); +} + + +#[test] +fn read() { + let buf = "Hello, World!".to_string(); + let rbuf = rent_string::OwnedStr::new(buf, |slice| slice, |slice, _| slice); + + assert_eq!(&*rbuf, "Hello, World!"); +} diff --git a/third_party/rust/rental/tests/subrental.rs b/third_party/rust/rental/tests/subrental.rs new file mode 100644 index 0000000000..f44a072aee --- /dev/null +++ b/third_party/rust/rental/tests/subrental.rs @@ -0,0 +1,88 @@ +#[macro_use] +extern crate rental; + + +pub struct Foo { + pub i: i32, +} + +pub struct Bar<'a> { + pub foo: &'a Foo, +} + +pub struct Qux<'a: 'b, 'b> { + pub bar: &'b Bar<'a>, +} + + +impl Foo { + pub fn borrow(&self) -> Bar { Bar { foo: self } } + pub fn try_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Ok(Bar { foo: self }) } + pub fn fail_borrow<'a>(&'a self) -> Result<Bar<'a>, ()> { Err(()) } +} + +impl<'a> Bar<'a> { + pub fn borrow<'b>(&'b self) -> Qux<'a, 'b> { Qux { bar: self } } + pub fn try_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Ok(Qux { bar: self }) } + pub fn fail_borrow<'b>(&'b self) -> Result<Qux<'a, 'b>, ()> { Err(()) } +} + + +rental! { + pub mod rentals { + use super::*; + + #[rental] + pub struct Sub { + foo: Box<Foo>, + bar: Bar<'foo>, + } + + #[rental] + pub struct Rent { + #[subrental = 2] + sub: Box<Sub>, + qux: Qux<'sub_0, 'sub_1>, + } + + #[rental] + pub struct BorrowSub<'f> { + foo: &'f Foo, + bar: Bar<'foo>, + } + + #[rental] + pub struct TailRent { + foo: Box<Foo>, + #[subrental = 2] + sub: Box<BorrowSub<'foo>>, + iref: &'sub_1 i32, + } + } +} + + +#[test] +fn new() { + let foo = Foo { i: 5 }; + let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow()); + let _ = rentals::Rent::new(Box::new(sub), |sub| sub.bar.borrow()); + + let foo = Foo { i: 5 }; + let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow()); + let rent = rentals::Rent::try_new(Box::new(sub), |sub| sub.bar.try_borrow()); + assert!(rent.is_ok()); + + let foo = Foo { i: 5 }; + let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow()); + let rent = rentals::Rent::try_new(Box::new(sub), |sub| sub.bar.fail_borrow()); + assert!(rent.is_err()); +} + + +#[test] +fn read() { + let foo = Foo { i: 5 }; + let sub = rentals::Sub::new(Box::new(foo), |foo| foo.borrow()); + let _ = rentals::Rent::new(Box::new(sub), |sub| sub.bar.borrow()); +} diff --git a/third_party/rust/rental/tests/target_ty_hack.rs b/third_party/rust/rental/tests/target_ty_hack.rs new file mode 100644 index 0000000000..d98bd0d7b5 --- /dev/null +++ b/third_party/rust/rental/tests/target_ty_hack.rs @@ -0,0 +1,54 @@ +#[macro_use] +extern crate rental; + + +type MyVec<T> = Vec<T>; + + +rental! { + pub mod rent_vec_slice { + use super::*; + + #[rental] + pub struct OwnedSlice { + #[target_ty = "[u8]"] + buffer: MyVec<u8>, + slice: &'buffer [u8], + } + + #[rental_mut] + pub struct OwnedMutSlice { + #[target_ty = "[u8]"] + buffer: MyVec<u8>, + slice: &'buffer mut [u8], + } + } +} + + +#[test] +fn new() { + let vec = vec![1, 2, 3]; + let _ = rent_vec_slice::OwnedSlice::new(vec, |slice| slice); +} + + +#[test] +fn read() { + let vec = vec![1, 2, 3]; + let rvec = rent_vec_slice::OwnedSlice::new(vec, |slice| slice); + + assert_eq!(rvec.rent(|slice| slice[1]), 2); + assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1])); +} + + +#[test] +fn write() { + let vec = vec![1, 2, 3]; + let mut rvec = rent_vec_slice::OwnedMutSlice::new(vec, |slice| slice); + + rvec.rent_mut(|slice| slice[1] = 4); + assert_eq!(rvec.rent(|slice| slice[1]), 4); + assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1])); +} diff --git a/third_party/rust/rental/tests/trait.rs b/third_party/rust/rental/tests/trait.rs new file mode 100644 index 0000000000..180e328ce1 --- /dev/null +++ b/third_party/rust/rental/tests/trait.rs @@ -0,0 +1,33 @@ +#[macro_use] +extern crate rental; + + +pub trait MyTrait { } + + +pub struct MyStruct { } + + +impl MyTrait for MyStruct { } + + +rental! { + pub mod rentals { + use ::MyTrait; + + #[rental] + pub struct RentTrait { + my_trait: Box<MyTrait + 'static>, + my_suffix: &'my_trait (MyTrait + 'static), + } + } +} + + +#[test] +fn new() { + let _tr = rentals::RentTrait::new( + Box::new(MyStruct{}), + |t| &*t, + ); +} diff --git a/third_party/rust/rental/tests/unused.rs b/third_party/rust/rental/tests/unused.rs new file mode 100644 index 0000000000..a8962a050c --- /dev/null +++ b/third_party/rust/rental/tests/unused.rs @@ -0,0 +1,28 @@ +use std::rc::Rc; + +#[macro_use] +extern crate rental; + +pub struct Sample { + field: i32, +} + +rental! { + mod sample_rental { + use super::*; + + #[rental] + pub struct SampleRental { + sample: Rc<Sample>, + sref: &'sample i32, + } + } +} +use self::sample_rental::SampleRental; + +#[test] +fn unused() { + let sample = Rc::new(Sample { field: 42 }); + let rental = SampleRental::new(sample, |sample_rc| &sample_rc.field); + rental.rent(|this| println!("{}", this)); +} diff --git a/third_party/rust/rental/tests/vec_slice.rs b/third_party/rust/rental/tests/vec_slice.rs new file mode 100644 index 0000000000..afc46edf7c --- /dev/null +++ b/third_party/rust/rental/tests/vec_slice.rs @@ -0,0 +1,47 @@ +#[macro_use] +extern crate rental; + + +rental! { + pub mod rent_vec_slice { + #[rental] + pub struct OwnedSlice { + buffer: Vec<u8>, + slice: &'buffer [u8], + } + + #[rental_mut] + pub struct OwnedMutSlice { + buffer: Vec<u8>, + slice: &'buffer mut [u8], + } + } +} + + +#[test] +fn new() { + let vec = vec![1, 2, 3]; + let _ = rent_vec_slice::OwnedSlice::new(vec, |slice| slice); +} + + +#[test] +fn read() { + let vec = vec![1, 2, 3]; + let rvec = rent_vec_slice::OwnedSlice::new(vec, |slice| slice); + + assert_eq!(rvec.rent(|slice| slice[1]), 2); + assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1])); +} + + +#[test] +fn write() { + let vec = vec![1, 2, 3]; + let mut rvec = rent_vec_slice::OwnedMutSlice::new(vec, |slice| slice); + + rvec.rent_mut(|slice| slice[1] = 4); + assert_eq!(rvec.rent(|slice| slice[1]), 4); + assert_eq!(rvec.rent(|slice| slice[1]), rvec.rent(|slice| slice[1])); +} |