diff options
author | Maurice Lam <yukl@google.com> | 2023-02-15 18:49:25 +0000 |
---|---|---|
committer | Maurice Lam <yukl@google.com> | 2023-02-15 18:58:59 +0000 |
commit | 7547b2c517884aba2d3bddcd5f6b396f8f0e4ce7 (patch) | |
tree | 1b3ca5b95ed6ead034f18c5d56d18fbc544a490f | |
parent | fc588a66f684bb03192632c7f56e23ae0eaf956d (diff) | |
download | ouroboros-7547b2c517884aba2d3bddcd5f6b396f8f0e4ce7.tar.gz |
Import ouroboros crate
Bug: 267375624
Test: None. No build files added yet
Change-Id: I3c4a94c36b791c2829b47aeb2597497e902496f4
-rw-r--r-- | .cargo_vcs_info.json | 6 | ||||
-rw-r--r-- | Cargo.toml | 31 | ||||
-rw-r--r-- | Cargo.toml.orig | 18 | ||||
l--------- | LICENSE | 1 | ||||
-rw-r--r-- | LICENSE_APACHE | 202 | ||||
-rw-r--r-- | LICENSE_MIT | 22 | ||||
-rw-r--r-- | METADATA | 19 | ||||
-rw-r--r-- | MODULE_LICENSE_APACHE2 | 0 | ||||
-rw-r--r-- | OWNERS | 1 | ||||
-rw-r--r-- | README.md | 77 | ||||
-rw-r--r-- | src/lib.rs | 407 |
11 files changed, 784 insertions, 0 deletions
diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json new file mode 100644 index 0000000..6f8191c --- /dev/null +++ b/.cargo_vcs_info.json @@ -0,0 +1,6 @@ +{ + "git": { + "sha1": "79bac55f29edbb44f7205246ab5c3f706cbc4647" + }, + "path_in_vcs": "ouroboros" +}
\ No newline at end of file diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..cb3edf0 --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,31 @@ +# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO +# +# When uploading crates to the registry Cargo will automatically +# "normalize" Cargo.toml files for maximal compatibility +# with all versions of Cargo and also rewrite `path` dependencies +# to registry (e.g., crates.io) dependencies. +# +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. + +[package] +edition = "2018" +name = "ouroboros" +version = "0.15.5" +authors = ["Joshua Maros <joshua-maros@github.com>"] +description = "Easy, safe self-referential struct generation." +documentation = "https://docs.rs/ouroboros" +readme = "README.md" +license = "MIT OR Apache-2.0" +repository = "https://github.com/joshua-maros/ouroboros" + +[dependencies.aliasable] +version = "0.1.3" + +[dependencies.ouroboros_macro] +version = "0.15.5" + +[features] +default = ["std"] +std = ["ouroboros_macro/std"] diff --git a/Cargo.toml.orig b/Cargo.toml.orig new file mode 100644 index 0000000..73d97ad --- /dev/null +++ b/Cargo.toml.orig @@ -0,0 +1,18 @@ +[package] +name = "ouroboros" +version = "0.15.5" +authors = ["Joshua Maros <joshua-maros@github.com>"] +edition = "2018" +license = "MIT OR Apache-2.0" +description = "Easy, safe self-referential struct generation." +readme = "../README.md" +documentation = "https://docs.rs/ouroboros" +repository = "https://github.com/joshua-maros/ouroboros" + +[dependencies] +aliasable = "0.1.3" +ouroboros_macro = { version = "0.15.5", path = "../ouroboros_macro" } + +[features] +default = ["std"] +std = ["ouroboros_macro/std"] @@ -0,0 +1 @@ +LICENSE_MIT
\ No newline at end of file diff --git a/LICENSE_APACHE b/LICENSE_APACHE new file mode 100644 index 0000000..574cb18 --- /dev/null +++ b/LICENSE_APACHE @@ -0,0 +1,202 @@ + 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 2021 Joshua Maros + + 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/LICENSE_MIT b/LICENSE_MIT new file mode 100644 index 0000000..9ed5b2a --- /dev/null +++ b/LICENSE_MIT @@ -0,0 +1,22 @@ +MIT License + +Copyright (c) 2021 Joshua Maros + +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/METADATA b/METADATA new file mode 100644 index 0000000..9628b1a --- /dev/null +++ b/METADATA @@ -0,0 +1,19 @@ +name: "ouroboros" +description: "Easy, safe self-referential struct generation." +third_party { + url { + type: HOMEPAGE + value: "https://crates.io/crates/ouroboros" + } + url { + type: ARCHIVE + value: "https://static.crates.io/crates/ouroboros/ouroboros-0.15.5.crate" + } + version: "0.15.5" + license_type: NOTICE + last_upgrade_date { + year: 2023 + month: 2 + day: 15 + } +} diff --git a/MODULE_LICENSE_APACHE2 b/MODULE_LICENSE_APACHE2 new file mode 100644 index 0000000..e69de29 --- /dev/null +++ b/MODULE_LICENSE_APACHE2 @@ -0,0 +1 @@ +include platform/prebuilts/rust:master:/OWNERS diff --git a/README.md b/README.md new file mode 100644 index 0000000..8e5af71 --- /dev/null +++ b/README.md @@ -0,0 +1,77 @@ +# Ouroboros + +[![Ouroboros on Crates.IO](https://img.shields.io/crates/v/ouroboros)](https://crates.io/crates/ouroboros) +[![Documentation](https://img.shields.io/badge/documentation-link-success)](https://docs.rs/ouroboros) + + +Easy self-referential struct generation for Rust. +Dual licensed under MIT / Apache 2.0. + +While this crate is `no_std` compatible, it still requires the `alloc` crate. + +Version notes: +- Version `0.13.0` and later contain checks for additional situations which + cause undefined behavior if not caught. +- Version `0.11.0` and later place restrictions on derive macros, earlier + versions allowed using them in ways which could lead to undefined behavior if + not used properly. +- Version `0.10.0` and later automatically box every field. This is done + to prevent undefined behavior, but has the side effect of making the library + easier to work with. + +Tests are located in the examples/ folder because they need to be in a crate +outside of `ouroboros` for the `self_referencing` macro to work properly. + +```rust +use ouroboros::self_referencing; + +#[self_referencing] +struct MyStruct { + int_data: i32, + float_data: f32, + #[borrows(int_data)] + // the 'this lifetime is created by the #[self_referencing] macro + // and should be used on all references marked by the #[borrows] macro + int_reference: &'this i32, + #[borrows(mut float_data)] + float_reference: &'this mut f32, +} + +fn main() { + // The builder is created by the #[self_referencing] macro + // and is used to create the struct + let mut my_value = MyStructBuilder { + int_data: 42, + float_data: 3.14, + + // Note that the name of the field in the builder + // is the name of the field in the struct + `_builder` + // ie: {field_name}_builder + // the closure that assigns the value for the field will be passed + // a reference to the field(s) defined in the #[borrows] macro + + int_reference_builder: |int_data: &i32| int_data, + float_reference_builder: |float_data: &mut f32| float_data, + }.build(); + + // The fields in the original struct can not be accesed directly + // The builder creates accessor methods which are called borrow_{field_name}() + + // Prints 42 + println!("{:?}", my_value.borrow_int_data()); + // Prints 3.14 + println!("{:?}", my_value.borrow_float_reference()); + // Sets the value of float_data to 84.0 + my_value.with_mut(|fields| { + **fields.float_reference = (**fields.int_reference as f32) * 2.0; + }); + + // We can hold on to this reference... + let int_ref = *my_value.borrow_int_reference(); + println!("{:?}", *int_ref); + // As long as the struct is still alive. + drop(my_value); + // This will cause an error! + // println!("{:?}", *int_ref); +} +``` diff --git a/src/lib.rs b/src/lib.rs new file mode 100644 index 0000000..7c5f016 --- /dev/null +++ b/src/lib.rs @@ -0,0 +1,407 @@ +//! A crate for creating safe self-referencing structs. +//! +//! See the documentation of [`ouroboros_examples`](https://docs.rs/ouroboros_examples) for +//! sample documentation of structs which have had the macro applied to them. + +#![no_std] +#![allow(clippy::needless_doctest_main)] + +/// This macro is used to turn a regular struct into a self-referencing one. An example: +/// ```rust +/// use ouroboros::self_referencing; +/// +/// #[self_referencing] +/// struct MyStruct { +/// int_data: i32, +/// float_data: f32, +/// #[borrows(int_data)] +/// // the 'this lifetime is created by the #[self_referencing] macro +/// // and should be used on all references marked by the #[borrows] macro +/// int_reference: &'this i32, +/// #[borrows(mut float_data)] +/// float_reference: &'this mut f32, +/// } +/// +/// fn main() { +/// // The builder is created by the #[self_referencing] macro +/// // and is used to create the struct +/// let mut my_value = MyStructBuilder { +/// int_data: 42, +/// float_data: 3.14, +/// +/// // Note that the name of the field in the builder +/// // is the name of the field in the struct + `_builder` +/// // ie: {field_name}_builder +/// // the closure that assigns the value for the field will be passed +/// // a reference to the field(s) defined in the #[borrows] macro +/// +/// int_reference_builder: |int_data: &i32| int_data, +/// float_reference_builder: |float_data: &mut f32| float_data, +/// }.build(); +/// +/// // The fields in the original struct can not be accesed directly +/// // The builder creates accessor methods which are called borrow_{field_name}() +/// +/// // Prints 42 +/// println!("{:?}", my_value.borrow_int_data()); +/// // Prints 3.14 +/// println!("{:?}", my_value.borrow_float_reference()); +/// // Sets the value of float_data to 84.0 +/// my_value.with_mut(|fields| { +/// **fields.float_reference = (**fields.int_reference as f32) * 2.0; +/// }); +/// +/// // We can hold on to this reference... +/// let int_ref = *my_value.borrow_int_reference(); +/// println!("{:?}", *int_ref); +/// // As long as the struct is still alive. +/// drop(my_value); +/// // This will cause an error! +/// // println!("{:?}", *int_ref); +/// } +/// ``` +/// To explain the features and limitations of this crate, some definitions are necessary: +/// # Definitions +/// - **immutably borrowed field**: a field which is immutably borrowed by at least one other field. +/// - **mutably borrowed field**: a field which is mutably borrowed by exactly one other field. +/// - **self-referencing field**: a field which borrows at least one other field. +/// - **head field**: a field which does not borrow any other fields, I.E. not self-referencing. +/// This does not include fields with empty borrows annotations (`#[borrows()]`.) +/// - **tail field**: a field which is not borrowed by any other fields. +/// +/// # Usage +/// To make a self-referencing struct, you must write a struct definition and place +/// `#[self_referencing]` on top. For every field that borrows other fields, you must place +/// `#[borrows()]` on top and place inside the parenthesis a list of fields that it borrows. Mut can +/// be prefixed to indicate that a mutable borrow is required. For example, +/// `#[borrows(a, b, mut c)]` indicates that the first two fields need to be borrowed immutably and +/// the third needs to be borrowed mutably. You can also use `#[borrows()]` without any arguments to +/// indicate a field that will eventually borrow from the struct, but does not borrow anything when +/// first created. For example, you could use this on a field like `error: Option<&'this str>`. +/// +/// # You must comply with these limitations +/// - Fields must be declared before the first time they are borrowed. +/// - Normal borrowing rules apply, E.G. a field cannot be borrowed mutably twice. +/// - Fields that use the `'this` lifetime must have a corresponding `#[borrows()]` annotation. +/// The error for this needs some work, currently you will get an error saying that `'this` is +/// undefined at the location it was illegally used in. +/// +/// Violating them will result in an error message directly pointing out the violated rule. +/// +/// # Flexibility of this crate +/// The example above uses plain references as the self-referencing part of the struct, but you can +/// use anything that is dependent on lifetimes of objects inside the struct. For example, you could +/// do something like this: +/// ```rust +/// use ouroboros::self_referencing; +/// +/// pub struct ComplexData<'a, 'b> { +/// aref: &'a i32, +/// bref: &'b mut i32, +/// number: i32, +/// } +/// +/// impl<'a, 'b> ComplexData<'a, 'b> { +/// fn new(aref: &'a i32, bref: &'b mut i32, number: i32) -> Self { +/// Self { aref, bref, number } +/// } +/// +/// /// Copies the value aref points to into what bref points to. +/// fn transfer(&mut self) { +/// *self.bref = *self.aref; +/// } +/// +/// /// Prints the value bref points to. +/// fn print_bref(&self) { +/// println!("{}", *self.bref); +/// } +/// } +/// +/// fn main() { +/// #[self_referencing] +/// struct DataStorage { +/// immutable: i32, +/// mutable: i32, +/// #[borrows(immutable, mut mutable)] +/// #[covariant] +/// complex_data: ComplexData<'this, 'this>, +/// } +/// +/// let mut data_storage = DataStorageBuilder { +/// immutable: 10, +/// mutable: 20, +/// complex_data_builder: |i: &i32, m: &mut i32| ComplexData::new(i, m, 12345), +/// }.build(); +/// data_storage.with_complex_data_mut(|data| { +/// // Copies the value in immutable into mutable. +/// data.transfer(); +/// // Prints 10 +/// data.print_bref(); +/// }); +/// } +/// ``` +/// +/// # Note on memory leaks +/// Currently, if a builder panics when creating a field, all previous fields will be leaked. This +/// does not cause any undefined behavior. This behavior may be resolved in the future so that all +/// previous fields are dropped when a builder panics. +/// +/// # Covariance +/// Many types in Rust have a property called "covariance". In practical tearms, this means that a +/// covariant type like `Box<&'this i32>` can be used as a `Box<&'a i32>` as long as `'a` is +/// smaller than `'this`. Since the lifetime is smaller, it does not violate the lifetime specified +/// by the original type. Contrast this to `Fn(&'this i32)`, which is not covariant. You cannot give +/// this function a reference with a lifetime shorter than `'this` as the function needs something +/// that lives at *least* as long as `'this`. Unfortunately, there is no easy way to determine +/// whether or not a type is covariant from inside the macro. As such, you may +/// receive a compiler error letting you know that the macro is uncertain if a particular field +/// uses a covariant type. Adding `#[covariant]` or `#[not_covariant]` will resolve this issue. +/// +/// These annotations control whether or not a `borrow_*` method is generated for that field. +/// Incorrectly using one of these tags will result in a compilation error. It is impossible to +/// use them unsoundly. +/// +/// # Async usage +/// All self-referencing structs can be initialized asynchronously by using either the +/// `MyStruct::new_async()` function or the `MyStructAsyncBuilder` builder. Due to limitations of +/// the rust compiler you closures must return a Future trait object wrapped in a `Pin<Box<_>>`. +/// +/// Here is the same example as above in its async version: +/// +/// ```ignore +/// use ouroboros::self_referencing; +/// +/// #[self_referencing] +/// struct MyStruct { +/// int_data: i32, +/// float_data: f32, +/// #[borrows(int_data)] +/// int_reference: &'this i32, +/// #[borrows(mut float_data)] +/// float_reference: &'this mut f32, +/// } +/// +/// #[tokio::main] +/// async fn main() { +/// let mut my_value = MyStructAsyncBuilder { +/// int_data: 42, +/// float_data: 3.14, +/// int_reference_builder: |int_data: &i32| Box::pin(async move { int_data }), +/// float_reference_builder: |float_data: &mut f32| Box::pin(async move { float_data }), +/// }.build().await; +/// +/// // Prints 42 +/// println!("{:?}", my_value.borrow_int_data()); +/// // Prints 3.14 +/// println!("{:?}", my_value.borrow_float_reference()); +/// // Sets the value of float_data to 84.0 +/// my_value.with_mut(|fields| { +/// **fields.float_reference = (**fields.int_reference as f32) * 2.0; +/// }); +/// +/// // We can hold on to this reference... +/// let int_ref = *my_value.borrow_int_reference(); +/// println!("{:?}", *int_ref); +/// // As long as the struct is still alive. +/// drop(my_value); +/// // This will cause an error! +/// // println!("{:?}", *int_ref); +/// } +/// ``` +/// +/// # Async Send +/// When Send trait is needed, the Send variant of async methods and builders is available. +/// +/// Here is the same example as above in its async send version: +/// +/// ```ignore +/// use ouroboros::self_referencing; +/// +/// #[self_referencing] +/// struct MyStruct { +/// int_data: i32, +/// float_data: f32, +/// #[borrows(int_data)] +/// int_reference: &'this i32, +/// #[borrows(mut float_data)] +/// float_reference: &'this mut f32, +/// } +/// +/// #[tokio::main] +/// async fn main() { +/// let mut my_value = MyStructAsyncSendBuilder { +/// int_data: 42, +/// float_data: 3.14, +/// int_reference_builder: |int_data: &i32| Box::pin(async move { int_data }), +/// float_reference_builder: |float_data: &mut f32| Box::pin(async move { float_data }), +/// }.build().await; +/// +/// // Prints 42 +/// println!("{:?}", my_value.borrow_int_data()); +/// // Prints 3.14 +/// println!("{:?}", my_value.borrow_float_reference()); +/// // Sets the value of float_data to 84.0 +/// my_value.with_mut(|fields| { +/// **fields.float_reference = (**fields.int_reference as f32) * 2.0; +/// }); +/// +/// // We can hold on to this reference... +/// let int_ref = *my_value.borrow_int_reference(); +/// println!("{:?}", *int_ref); +/// // As long as the struct is still alive. +/// drop(my_value); +/// // This will cause an error! +/// // println!("{:?}", *int_ref); +/// } +/// ``` +/// +/// # What does the macro generate? +/// The `#[self_referencing]` struct will replace your definition with an unsafe self-referencing +/// struct with a safe public interface. Many functions will be generated depending on your original +/// struct definition. Documentation is generated for all items, so building documentation for +/// your project allows accessing detailed information about available functions. Using +/// `#[self_referencing(no_doc)]` will hide the generated items from documentation if it is becoming +/// too cluttered. +/// +/// ### A quick note on visibility +/// The visibility of generated items is dependent on one of two things. If the +/// generated item is related to a specific field of the struct, it uses the visibility of the +/// original field. (The actual field in the struct will be made private since accessing it could cause +/// undefined behavior.) If the generated item is not related to any particular field, it will by +/// default only be visible to the module the struct is declared in. (This includes things like +/// `new()` and `with()`.) You can use `#[self_referencing(pub_extras)]` to make these items have the +/// same visibility as the struct itself. +/// +/// # List of generated items +/// ### `MyStruct::new(fields...) -> MyStruct` +/// A basic constructor. It accepts values for each field in the order you declared them in. For +/// **head fields**, you only need to pass in what value it should have and it will be moved in +/// to the output. For **self-referencing fields**, you must provide a function or closure which creates +/// the value based on the values it borrows. A field using the earlier example of +/// `#[borrow(a, b, mut c)]` would require a function typed as +/// `FnOnce(a: &_, b: &_, c: &mut _) -> _`. Fields which have an empty borrows annotation +/// (`#[borrows()]`) should have their value directly passed in. A field using the earlier example +/// of `Option<&'this str>` would require an input of `None`. Do not pass a function. Do not collect +/// 200 dollars. +/// ### `MyStruct::new_async(fields...) -> MyStruct` +/// A basic async constructor. It works identically to the sync constructor differing only in the +/// type of closures it expects. Whenever a closure is required it is expected to return a Pinned +/// and Boxed Future that Outputs the same type as the synchronous version. +/// ### `MyStruct::new_async_send(fields...) -> MyStruct` +/// An async send constructor. It works identically to the sync constructor differing only in the +/// Send trait being specified in the return type. +/// ### `MyStructBuilder` +/// This is the preferred way to create a new instance of your struct. It is similar to using the +/// `MyStruct { a, b, c, d }` syntax instead of `MyStruct::new(a, b, c, d)`. It contains one field +/// for every argument in the actual constructor. **Head fields** have the same name that you +/// originally defined them with. **self-referencing fields** are suffixed with `_builder` since you need +/// to provide a function instead of a value. Fields with an empty borrows annotation are not +/// initialized using builders. Calling `.build()` on an instance of `MyStructBuilder` +/// will convert it to an instance of `MyStruct` by calling all `_builder` functions in the order that +/// they were declared and storing their results. +/// ### `MyStructAsyncBuilder` +/// This is the preferred way to asynchronously create a new instance of your struct. It works +/// identically to the synchronous builder differing only in the type of closures it expects. In +/// particular, all builder functions are called serially in the order that they were declared. +/// Whenever a closure is required it is expected to return a Pinned and Boxed Future that Outputs +/// the same type as the synchronous version. +/// ### `MyStructAsyncSendBuilder` +/// Same as MyStructAsyncBuilder, but with Send trait specified in the return type. +/// ### `MyStruct::try_new<E>(fields...) -> Result<MyStruct, E>` +/// Similar to the regular `new()` function, except the functions wich create values for all +/// **self-referencing fields** can return `Result<>`s. If any of those are `Err`s, that error will be +/// returned instead of an instance of `MyStruct`. The preferred way to use this function is through +/// `MyStructTryBuilder` and its `try_build()` function. +/// ### `MyStruct::try_new_async<E>(fields...) -> Result<MyStruct, E>` +/// Similar to the regular `new_async()` function, except the functions wich create values for all +/// **self-referencing fields** can return `Result<>`s. If any of those are `Err`s, that error will be +/// returned instead of an instance of `MyStruct`. The preferred way to use this function is through +/// `MyStructAsyncTryBuilder` and its `try_build()` function. +/// ### `MyStruct::try_new_async_send<E>(fields...) -> Result<MyStruct, E>` +/// Same as `new_async()` function, but with Send trait specified in the return type. +/// ### `MyStruct::try_new_or_recover_async<E>(fields...) -> Result<MyStruct, (E, Heads)>` +/// Similar to the `try_new_async()` function, except that all the **head fields** are returned along side +/// the original error in case of an error. The preferred way to use this function is through +/// `MyStructAsyncTryBuilder` and its `try_build_or_recover()` function. +/// ### `MyStruct::try_new_or_recover_async_send<E>(fields...) -> Result<MyStruct, (E, Heads)>` +/// Same as `try_new_or_recover_async()` function, but with Send trait specified in the return type. +/// ### `MyStruct::with_FIELD<R>(&self, user: FnOnce(field: &FieldType) -> R) -> R` +/// This function is generated for every **tail and immutably-borrowed field** in your struct. It +/// allows safely accessing +/// a reference to that value. The function generates the reference and passes it to `user`. You +/// can do anything you want with the reference, it is constructed to not outlive the struct. +/// ### `MyStruct::borrow_FIELD(&self) -> &FieldType` +/// This function is generated for every **tail and immutably-borrowed field** in your struct. It +/// is equivalent to calling `my_struct.with_FIELD(|field| field)`. It is only generated for types +/// which are known to be covariant, either through the macro being able to detect it or through the +/// programmer adding the `#[covariant]` annotation to the field. +/// There is no `borrow_FIELD_mut`, unfortunately, as Rust's +/// borrow checker is currently not capable of ensuring that such a method would be used safely. +/// ### `MyStruct::with_FIELD_mut<R>(&mut self, user: FnOnce(field: &mut FieldType) -> R) -> R` +/// This function is generated for every **tail field** in your struct. It is the mutable version +/// of `with_FIELD`. +/// ### `MyStruct::with<R>(&self, user: FnOnce(fields: AllFields) -> R) -> R` +/// Allows borrowing all **tail and immutably-borrowed fields** at once. Functions similarly to +/// `with_FIELD`. +/// ### `MyStruct::with_mut<R>(&self, user: FnOnce(fields: AllFields) -> R) -> R` +/// Allows mutably borrowing all **tail fields** and immutably borrowing all **immutably-borrowed** +/// fields at once. Functions similarly to `with_FIELD_mut`, except that you can borrow multiple +/// fields as mutable at the same time and also have immutable access to any remaining fields. +/// ### `MyStruct::into_heads(self) -> Heads` +/// Drops all self-referencing fields and returns a struct containing all **head fields**. +pub use ouroboros_macro::self_referencing; + +#[doc(hidden)] +pub mod macro_help { + pub extern crate alloc; + + pub use aliasable::boxed::AliasableBox; + use aliasable::boxed::UniqueBox; + + pub struct CheckIfTypeIsStd<T>(core::marker::PhantomData<T>); + + macro_rules! std_type_check { + ($fn_name:ident $T:ident $check_for:ty) => { + impl<$T: ?Sized> CheckIfTypeIsStd<$check_for> { + pub fn $fn_name() {} + } + }; + } + + std_type_check!(is_std_box_type T alloc::boxed::Box<T>); + std_type_check!(is_std_arc_type T alloc::sync::Arc<T>); + std_type_check!(is_std_rc_type T alloc::rc::Rc<T>); + + pub fn aliasable_boxed<T>(data: T) -> AliasableBox<T> { + AliasableBox::from_unique(UniqueBox::new(data)) + } + + pub fn unbox<T>(boxed: AliasableBox<T>) -> T { + *AliasableBox::into_unique(boxed) + } + + /// Converts a reference to an object to a static reference This is + /// obviously unsafe because the compiler can no longer guarantee that the + /// data outlives the reference. It is up to the consumer to get rid of the + /// reference before the container is dropped. The + 'static ensures that + /// whatever we are referring to will remain valid indefinitely, that there + /// are no limitations on how long the pointer itself can live. + /// + /// # Safety + /// + /// The caller must ensure that the returned reference is not used after the originally passed + /// reference would become invalid. + pub unsafe fn change_lifetime<'old, 'new: 'old, T: 'new>(data: &'old T) -> &'new T { + &*(data as *const _) + } + + /// Like change_lifetime, but for mutable references. + /// + /// # Safety + /// + /// The caller must ensure that the returned reference is not used after the originally passed + /// reference would become invalid. + pub unsafe fn change_lifetime_mut<'old, 'new: 'old, T: 'new>(data: &'old mut T) -> &'new mut T { + &mut *(data as *mut _) + } +} |