├── .gitignore ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | /target 2 | Cargo.lock 3 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "recursive_reference" 3 | version = "0.3.0" # remember to bump the html_root_url as well 4 | authors = ["Noam Ta Shma "] 5 | edition = "2018" 6 | keywords = ["recursive", "data-structures", "smart-pointer", "reference"] 7 | categories = ["rust-patterns", "data-structures", "no-std"] 8 | description = "This crate provides a way to walk on recursive structures easily and safely." 9 | readme = "README.md" 10 | repository = "https://github.com/noamtashma/recursive_reference" 11 | license = "MIT OR Apache-2.0" 12 | 13 | # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html 14 | 15 | [dependencies] 16 | void = "1.0" 17 | 18 | [lib] 19 | name = "recursive_reference" 20 | path = "src/lib.rs" -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2021 Noam Ta Shma 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2021 noamtashma 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Recursive reference   [![Latest Version]][crates.io] [![Docs version]][docs] 2 | 3 | [Latest Version]: https://img.shields.io/crates/v/recursive_reference.svg 4 | [crates.io]: https://crates.io/crates/recursive_reference 5 | [Docs version]: https://docs.rs/recursive_reference/badge.svg 6 | [docs]: https://docs.rs/recursive_reference/ 7 | 8 | This crate provides a way to traverse recursive structures easily and safely. 9 | Rust's lifetime rules will usually force you to either only walk forward through the structure, 10 | or use recursion, calling your method recursively every time you go down a node, 11 | and returning every time you want to go back up, which leads to terrible code. 12 | 13 | Instead, you can use the [`RecRef`] type, to safely and dynamically walk up 14 | and down your recursive structure. 15 | 16 | [documentation](https://docs.rs/recursive_reference) 17 | [crates.io](https://crates.io/crates/recursive_reference) 18 | [repository](https://github.com/noamtashma/recursive_reference) 19 | 20 | # Examples 21 | 22 | Say we have a recursive linked list structure 23 | ---------------------------------------------- 24 | ```rust 25 | enum List { 26 | Root(Box>), 27 | Empty, 28 | } 29 | struct Node { 30 | value: T, 31 | next: List, 32 | } 33 | ``` 34 | 35 | We can use a [`RecRef`] directly 36 | ---------------------------------------------- 37 | ```rust 38 | use recursive_reference::*; 39 | 40 | fn main() -> Result<(), ()> { 41 | // crate a list to test 42 | let node1 = Node { 43 | value: 5, 44 | next: List::Empty, 45 | }; 46 | let mut node2 = Node { 47 | value: 2, 48 | next: List::Root(Box::new(node1)), 49 | }; 50 | 51 | // create a `RecRef` 52 | let mut rec_ref = RecRef::new(&mut node2); 53 | // rec_ref is a smart pointer to the current node 54 | assert_eq!(rec_ref.value, 2); 55 | 56 | // move forward through the list 57 | RecRef::extend_result(&mut rec_ref, |node| match &mut node.next { 58 | List::Root(next_node) => Ok(next_node), 59 | List::Empty => Err(()), 60 | })?; 61 | assert_eq!(rec_ref.value, 5); // now we're at the second node 62 | 63 | // pop the `RecRef`, moving it back to the head 64 | RecRef::pop(&mut rec_ref).ok_or(())?; 65 | assert_eq!(rec_ref.value, 2); 66 | Ok(()) 67 | } 68 | ``` 69 | 70 | We can also wrap a [`RecRef`] in a walker struct 71 | ---------------------------------------------- 72 | ```rust 73 | use recursive_reference::*; 74 | struct Walker<'a, T> { 75 | rec_ref: RecRef<'a, Node>, 76 | } 77 | impl<'a, T> Walker<'a, T> { 78 | /// Crates a new Walker 79 | pub fn new(node: &'a mut Node) -> Self { 80 | Walker { 81 | rec_ref: RecRef::new(node), 82 | } 83 | } 84 | 85 | /// Returns `None` when at the tail end of the list. 86 | /// Moves to the next node. 87 | pub fn next(&mut self) -> Option<()> { 88 | RecRef::extend_result(&mut self.rec_ref, |current| match &mut current.next { 89 | List::Empty => Err(()), 90 | List::Root(node) => Ok(node), 91 | }) 92 | .ok() 93 | } 94 | 95 | /// Returns `None` when at the head of the list. 96 | /// Goes back to the previous node. 97 | pub fn prev(&mut self) -> Option<()> { 98 | RecRef::pop(&mut self.rec_ref)?; 99 | Some(()) 100 | } 101 | 102 | /// Returns `None` when at the tail end of the list. 103 | /// Returns `Some(reference)` where `reference` is a mutable reference to the current value. 104 | pub fn value_mut(&mut self) -> &mut T { 105 | &mut self.rec_ref.value 106 | } 107 | } 108 | 109 | fn main() -> Result<(), ()> { 110 | // crate a list to test 111 | let node1 = Node { 112 | value: 5, 113 | next: List::Empty, 114 | }; 115 | let mut node2 = Node { 116 | value: 2, 117 | next: List::Root(Box::new(node1)), 118 | }; 119 | 120 | // create a walker for the list 121 | let mut walker = Walker::new(&mut node2); 122 | // walker has mutable access to the node value 123 | assert_eq!(*walker.value_mut(), 2); 124 | // move to the next node 125 | walker.next().ok_or(())?; 126 | assert_eq!(*walker.value_mut(), 5); 127 | assert_eq!(walker.next(), None); // currently at the end of the list 128 | // move back 129 | walker.prev().ok_or(())?; 130 | assert_eq!(*walker.value_mut(), 2); 131 | Ok(()) 132 | } 133 | ``` 134 | With a [`RecRef`] you can 135 | ---------------------------------------------- 136 | * Use the current reference (i.e, the top reference). 137 | the [`RecRef`] is a smart pointer to it. 138 | * Freeze the current reference 139 | and extend the [`RecRef`] with a new reference derived from it, using [`extend`] and similar functions. 140 | for example, push to the stack a reference to the child of the current node. 141 | * Pop the stack to get back to the previous reference, unfreezing it. 142 | 143 | 144 | 145 | # Alternative Comparison 146 | There are many alternatives to using [`RecRef`]. They all have their upsides and downsides. 147 | We only compare them to `RecRef`, so we only list the downsides that `RecRef` solves. 148 | Many of these alternatives can be better, depending on the usecase. Here are they, roughly from the basic to the sophisticated: 149 | * Plain recursive data structures. They require writing recursive functions where the recursion matches exactly with your access pattern. Anything but the most basic functions are very hard to write this way. 150 | * Pointer-based data structures can be efficient and convenient, but unsafe. 151 | * `Rc` and `RefCell` based data structures can be convenient, but require overhead to store metadata and check it. They also make ownership bugs surface at runtime rather than compile time. (You might want to look at `static-rc`, which is a crate that can improve this). 152 | * Slab-based. That is, store all of your nodes in some kind of collection, and have the links be 153 | indices into the collection. 154 | * Requires your pointers to go through an extra indirection. 155 | * Your structure will be tied to the slab (you can't split parts of it and send them to another owner) 156 | * If you give a borrow to the structure, the whole structure could be changed. 157 | * Arena-based recursive data structures. That is, an arena is like a slab, that can't delete its elements, and can therefore give long-lasting references to its elements. 158 | * The nodes can't be freed until the whole structure is freed. 159 | * Your structure will be tied to the arena (you can't split parts of it and send them to another owner) 160 | * There are also alternative cells in the `qcell` crate and the `ghost-cell` crate, and maybe even more 161 | Interesting options. 162 | 163 | # [`RecRef`] Pros 164 | * [`RecRef`] can be used with any existing data structure, including any data structure 165 | that is not written by you. [`RecRef`] can work with plain structures, `Rc`/`RefCell` based structures, arena based structures, and so on. Although, working with plain structures is recommended. 166 | * [`RecRef`] incurs no space overhead to the structure. 167 | * [`RecRef`] is safe and doesn't panic. 168 | * [`RecRef`] does not tie it down, i.e, prevent you from splitting the structure's ownership. 169 | 170 | # [`RecRef`] Cons 171 | * [`RecRef`] only allows you to modify your structure at a single point at a time. 172 | * The [`RecRef`] itself requires a space overhead the size of your path in the recursive structure when 173 | traversing it. It also takes some time to pop and push elements to the vector. 174 | This is the same overhead that is needed in every structure that doesn't have parent pointers. 175 | * The [`RecRef`] is overall efficient, but internally pushes elements to a vector. 176 | 177 | 178 | 179 | 180 | # Minor details 181 | * All code is tested with a real-world library under miri. 182 | * Since version "0.3.0", the library requires rust version 1.53 to compile correctly. If it is not present, use version "0.2.0". 183 | * Internally, [`RecRef`] pushes and pops elements from a vector. That means that the library 184 | requires an allocator to be present. In addition, it means that you might have latency problems if you're using a very large [`RecRef`]. 185 | This can be theoretically solved by switching the [`RecRef`] to a low-latency stack. 186 | 187 | 188 | # Safety 189 | The [`RecRef`] type is implemented using unsafe rust, but provides a safe interface. 190 | The [`RecRef`]'s methods' types guarantee that the references will always have a legal lifetime 191 | and will respect rust's borrow rules, even if that lifetime is not known in advance. 192 | 193 | The [`RecRef`] obeys rust's borrowing rules, by simulating freezing. Whenever 194 | you extend a [`RecRef`] with a reference `child_ref` that is derived from the current 195 | reference `parent_ref`, the [`RecRef`] freezes `parent_ref`, and no longer allows 196 | `parent_ref` to be used. 197 | When `child_ref` will be popped from the [`RecRef`], 198 | `parent_ref` will be allowed to be used again. 199 | 200 | This is essentially the same as what would have happened if you wrote your functions recursively, 201 | but it's decoupled from the actual call stack. 202 | 203 | Another important point to consider is the safety of 204 | the actual call to [`extend`]: see its documentation. 205 | 206 | # License 207 | dual licensed with MIT and APACHE 2.0 208 | 209 | [`RecRef`]: https://docs.rs/recursive_reference/*/recursive_reference/struct.RecRef.html 210 | [`extend`]: https://docs.rs/recursive_reference/*/recursive_reference/struct.RecRef.html#method.extend -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! Recursive reference. 2 | //! 3 | //!This crate provides a way to traverse recursive structures easily and safely. 4 | //!Rust's lifetime rules will usually force you to either only walk forward through the structure, 5 | //!or use recursion, calling your method recursively every time you go down a node, 6 | //!and returning every time you want to go back up, which leads to terrible code. 7 | //! 8 | //!Instead, you can use the [`RecRef`] type, to safely and dynamically walk up 9 | //!and down your recursive structure. 10 | //! 11 | //!# Examples 12 | //! 13 | //! Say we have a recursive linked list structure 14 | //! ---------------------------------------------- 15 | //!```rust 16 | //!enum List { 17 | //! Root(Box>), 18 | //! Empty, 19 | //!} 20 | //!struct Node { 21 | //! value: T, 22 | //! next: List, 23 | //!} 24 | //!``` 25 | //! 26 | //!We can use a [`RecRef`] directly 27 | //!---------------------------------------------- 28 | //!```rust 29 | //!use recursive_reference::*; 30 | //! 31 | //! # enum List { 32 | //! # Root(Box>), 33 | //! # Empty, 34 | //! # } 35 | //! # struct Node { 36 | //! # value: T, 37 | //! # next: List, 38 | //! # } 39 | //! 40 | //!fn main() -> Result<(), ()> { 41 | //! // crate a list to test 42 | //! let node1 = Node { 43 | //! value: 5, 44 | //! next: List::Empty, 45 | //! }; 46 | //! let mut node2 = Node { 47 | //! value: 2, 48 | //! next: List::Root(Box::new(node1)), 49 | //! }; 50 | //! 51 | //! // create a `RecRef` 52 | //! let mut rec_ref = RecRef::new(&mut node2); 53 | //! // rec_ref is a smart pointer to the current node 54 | //! assert_eq!(rec_ref.value, 2); 55 | //! 56 | //! // move forward through the list 57 | //! RecRef::extend_result(&mut rec_ref, |node| match &mut node.next { 58 | //! List::Root(next_node) => Ok(next_node), 59 | //! List::Empty => Err(()), 60 | //! })?; 61 | //! assert_eq!(rec_ref.value, 5); // now we're at the second node 62 | //! 63 | //! // pop the `RecRef`, moving it back to the head 64 | //! RecRef::pop(&mut rec_ref).ok_or(())?; 65 | //! assert_eq!(rec_ref.value, 2); 66 | //! Ok(()) 67 | //!} 68 | //!``` 69 | //! 70 | //!We can also wrap a [`RecRef`] in a walker struct 71 | //!---------------------------------------------- 72 | //!Note: this time we are using a `RecRef>` and not a `RecRef>`, to allow pointing 73 | //!at the empty end of the list. 74 | //!```rust 75 | //!use recursive_reference::*; 76 | //! # enum List { 77 | //! # Root(Box>), 78 | //! # Empty, 79 | //! # } 80 | //! # struct Node { 81 | //! # value: T, 82 | //! # next: List, 83 | //! # } 84 | //!struct Walker<'a, T> { 85 | //! rec_ref: RecRef<'a, Node>, 86 | //!} 87 | //!impl<'a, T> Walker<'a, T> { 88 | //! /// Crates a new Walker 89 | //! pub fn new(node: &'a mut Node) -> Self { 90 | //! Walker { 91 | //! rec_ref: RecRef::new(node), 92 | //! } 93 | //! } 94 | //! 95 | //! /// Returns `None` when at the tail end of the list. 96 | //! /// Moves to the next node. 97 | //! pub fn next(&mut self) -> Option<()> { 98 | //! RecRef::extend_result(&mut self.rec_ref, |current| match &mut current.next { 99 | //! List::Empty => Err(()), 100 | //! List::Root(node) => Ok(node), 101 | //! }) 102 | //! .ok() 103 | //! } 104 | //! 105 | //! /// Returns `None` when at the head of the list. 106 | //! /// Goes back to the previous node. 107 | //! pub fn prev(&mut self) -> Option<()> { 108 | //! RecRef::pop(&mut self.rec_ref)?; 109 | //! Some(()) 110 | //! } 111 | //! 112 | //! /// Returns `None` when at the tail end of the list. 113 | //! /// Returns `Some(reference)` where `reference` is a mutable reference to the current value. 114 | //! pub fn value_mut(&mut self) -> &mut T { 115 | //! &mut self.rec_ref.value 116 | //! } 117 | //!} 118 | //! 119 | //!fn main() -> Result<(), ()> { 120 | //! // crate a list to test 121 | //! let node1 = Node { 122 | //! value: 5, 123 | //! next: List::Empty, 124 | //! }; 125 | //! let mut node2 = Node { 126 | //! value: 2, 127 | //! next: List::Root(Box::new(node1)), 128 | //! }; 129 | //! 130 | //! // create a walker for the list 131 | //! let mut walker = Walker::new(&mut node2); 132 | //! // walker has mutable access to the node value 133 | //! assert_eq!(*walker.value_mut(), 2); 134 | //! // move to the next node 135 | //! walker.next().ok_or(())?; 136 | //! assert_eq!(*walker.value_mut(), 5); 137 | //! assert_eq!(walker.next(), None); // currently at the end of the list 138 | //! // move back 139 | //! walker.prev().ok_or(())?; 140 | //! assert_eq!(*walker.value_mut(), 2); 141 | //! Ok(()) 142 | //!} 143 | //!``` 144 | //! With a [`RecRef`] you can 145 | //! ---------------------------------------------- 146 | //! * Use the current reference (i.e, the top reference). 147 | //! the [`RecRef`] is a smart pointer to it. 148 | //! * Freeze the current reference 149 | //! and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions. 150 | //! for example, push to the stack a reference to the child of the current node. 151 | //! * Pop the stack to get back to the previous reference, unfreezing it. 152 | //! 153 | //! # Safety 154 | //! The [`RecRef`] type is implemented using unsafe rust, but provides a safe interface. 155 | //! The [`RecRef`] methods' types guarantee that the references will always have a legal lifetime 156 | //! and will respect rust's borrow rules, even if that lifetime is not known in advance. 157 | //! 158 | //! The [`RecRef`] obeys rust's borrowing rules, by simulating freezing. Whenever 159 | //! you extend a [`RecRef`] with a reference `child_ref` that is derived from the current 160 | //! reference `parent_ref`, the [`RecRef`] freezes `parent_ref`, and no longer allows 161 | //! `parent_ref` to be used. 162 | //! When `child_ref` will be popped from the [`RecRef`], 163 | //! `parent_ref` will be allowed to be used again. 164 | //! 165 | //! This is essentially the same as what would have happened if you wrote your functions recursively, 166 | //! but it's decoupled from the actual call stack. 167 | //! 168 | //! Another important point to consider is the safety of 169 | //! the actual call to [`extend`][RecRef::extend]: see its documentation. 170 | #![no_std] 171 | #![doc(html_root_url = "https://docs.rs/recursive_reference/0.3.0/recursive_reference/")] 172 | 173 | extern crate alloc; 174 | use alloc::vec::*; 175 | 176 | use core::marker::PhantomData; 177 | use core::ops::{Deref, DerefMut}; 178 | use core::ptr::NonNull; 179 | use void::ResultVoidExt; 180 | 181 | /// A Recursive reference. 182 | /// This struct is used to allow recursively reborrowing mutable references in a dynamic 183 | /// but safe way. 184 | /// 185 | /// `RecRef<'a, T>` represents a reference to a value of type `T`, with lifetime `'a`, 186 | /// which can move recursively into and out of its subfields of the same type `T`. 187 | /// 188 | /// With a [`RecRef`] you can 189 | /// ---------------------------------------------- 190 | /// * Use the current reference (i.e, the top reference). 191 | /// The [`RecRef`] is a smart pointer to it. 192 | /// * Freeze the current reference 193 | /// and extend the [`RecRef`] with a new reference derived from it, using [`extend`][RecRef::extend] and similar functions. 194 | /// For example, push to the stack a reference to the child of the current node. 195 | /// * Pop the stack to get back to the previous reference, unfreezing it. 196 | /// 197 | /// The methods' types guarantee that the references will always have a legal lifetime 198 | /// and will respect rust's borrow rules, even if that lifetime is not known in advance. 199 | /// 200 | /// Internally, the [`RecRef`] stores a [`Vec`] of pointers, that it extends and pops from. 201 | 202 | // Safety invariants (please read `RecRef::extend`'s documentation before reading this): 203 | // The values in `vec` are allowed to alias. However: 204 | // For any index `i`, `vec[i]` can be safely used under these conditions: 205 | // * all of the values in `vec[..i]` are considered frozen. 206 | // * all of the values in `vec[i+1..]` are gone (e.g, if they are popped from the RecRef). 207 | // In such a case `vec[i]` could be unfrozen, converted to a `&'x mut T` for any `'a : 'x` and used. 208 | // Specifically, this happens when the values in `vec[i+1..]` are references produced 209 | // through `vec[i]`. 210 | // See `RecRef::extend`'s documentation for more details on how this is ensured. 211 | // 212 | // In particular, all values in `vec` have been produced from valid mutable references `&mut T`. 213 | pub struct RecRef<'a, T: ?Sized> { 214 | head: NonNull, 215 | vec: Vec>, 216 | phantom: PhantomData<&'a mut T>, 217 | } 218 | 219 | impl<'a, T: ?Sized> RecRef<'a, T> { 220 | /// Creates a new RecRef containing only a single reference. 221 | pub fn new(r: &'a mut T) -> Self { 222 | RecRef { 223 | head: NonNull::from(r), 224 | vec: Vec::new(), 225 | phantom: PhantomData, 226 | } 227 | } 228 | 229 | /// Returns the size of `rec_ref`, i.e, the amount of references in it. 230 | /// It increases every time you extend `rec_ref`, and decreases every time you pop 231 | /// `rec_ref`. 232 | /// The size of a new [`RecRef`] is always `1`. 233 | pub fn size(rec_ref: &Self) -> usize { 234 | rec_ref.vec.len() + 1 235 | } 236 | 237 | /// This function extends `rec_ref` one time. If the current 238 | /// reference is `current_ref: &mut T`, then this call extends `rec_ref` 239 | /// with the new reference `ref2: &mut T = func(current_ref)`. 240 | /// After this call, `rec_ref` will expose the new `ref2`, and `current_ref` 241 | /// will be frozen (As it is borrowed by `ref2`), until `ref2` is 242 | /// popped off, unfreezing `current_ref`. 243 | /// 244 | /// # Safety: 245 | /// Pay close attention to the type of `func`: we require that 246 | /// `F: for<'b> FnOnce(&'b mut T) -> &'b mut T`. That is, for every lifetime `'b`, 247 | /// we require that `F: FnOnce(&'b mut T) -> &'b mut T`. 248 | /// 249 | /// Let's define `'freeze_time` to be the time `ref2` will be in the [`RecRef`]. 250 | /// That is, `'freeze_time` 251 | /// is the time for which `ref2` will live, and the lifetime in which `current_ref` 252 | /// will be frozen by `ref2`. Then, the type of `func` should have been 253 | /// `FnOnce(&'freeze_time mut T) -> &'freeze_time mut T`. If that woudld have been the type 254 | /// of `func`, the code would've followed rust's borrowing rules correctly. 255 | /// 256 | /// However, we can't know yet what that 257 | /// lifetime is: it will be whatever amount of time passes until the programmer decides 258 | /// to pop `ref2` out of the [`RecRef`]. And that hasn't even been decided at this point. 259 | /// Whatever lifetime `'freeze_time` that turns out to be, we will know 260 | /// after-the-fact that the type of `func` should have been 261 | /// `FnOnce(&'freeze_time mut T) -> &'freeze_time mut T`. 262 | /// 263 | /// Therefore, the solution is to require that `func` will be able to work with any value of 264 | /// `'freeze_time`. Then we can be 265 | /// sure that the code would've worked correctly if we put the correct lifetime there. 266 | /// Therefore, we can always pick correct lifetimes after-the-fact, so the code must be safe. 267 | /// 268 | /// Also note: 269 | /// The type ensures that the current reference can't be leaked outside of `func`. 270 | /// `func` can't guarantee that 271 | /// `current_ref` will live for any length of time, so it can't store it outside anywhere 272 | /// or give it to anything. 273 | /// It can only use `current_ref` while still inside `func`, 274 | /// and use it in order to return `ref2`, which is the 275 | /// intended usage. 276 | pub fn extend(rec_ref: &mut Self, func: F) 277 | where 278 | F: for<'b> FnOnce(&'b mut T) -> &'b mut T, 279 | { 280 | Self::extend_result(rec_ref, |r| Ok(func(r))).void_unwrap() 281 | } 282 | 283 | /// Same as [`Self::extend`], but allows the function to return an error value. 284 | pub fn extend_result(rec_ref: &mut Self, func: F) -> Result<(), E> 285 | where 286 | F: for<'b> FnOnce(&'b mut T) -> Result<&'b mut T, E>, 287 | { 288 | Self::extend_result_precise(rec_ref, |r, _phantom| func(r)) 289 | } 290 | 291 | /// Same as [`Self::extend`], but allows the function to return an error value, 292 | /// and also tells the inner function that `'a : 'b` using a phantom argument. 293 | pub fn extend_result_precise(rec_ref: &mut Self, func: F) -> Result<(), E> 294 | where 295 | F: for<'b> FnOnce(&'b mut T, PhantomData<&'b &'a ()>) -> Result<&'b mut T, E>, 296 | { 297 | // Safety: 298 | // `rec_ref.head` was produced from a `&mut T`, and by RecRef's 299 | // safety invariant, it can be used. Furthermore, 300 | // Pushing another reference derived from it into the `rec_ref` preserves 301 | // the safety invariant. 302 | // 303 | // To understand how the invariant is ensured (and what it means) 304 | // see `RecRef::extend`'s documentation. 305 | // 306 | // However, there's another assumption here. 307 | // The lifetime of the reference here is indeterminate. 308 | // It could be any value. Thus by default the compiler will choose it 309 | // to be extremely short, that is, only until where `NonNull::from` is called on it. 310 | // 311 | // In fact, we want this lifetime to be a lifetime we haven't chosen yet. 312 | // It could be anything from as short as `'_` to as long as `'a`. 313 | // I arbitrarily chose it to be set to `'_`. 314 | // 315 | // Essentially, we assume here that calling `func` will have the same effect 316 | // even if we give it the wrong lifetime. In other words, we assume some form 317 | // of parametricity. 318 | // Semantically, this is true: code can't ever access the lifetimes. All lifetime 319 | // information is deleted at compile time. 320 | // However, we also assume that rust's optimizations 321 | // won't change the program's meaning because we used the wrong lifetime. 322 | let head_ref: &'_ mut T = unsafe { rec_ref.head.as_mut() }; 323 | 324 | match func(head_ref, PhantomData) { 325 | Ok(p) => { 326 | Self::push(rec_ref, p); 327 | Ok(()) 328 | } 329 | Err(e) => Err(e), 330 | } 331 | } 332 | 333 | /// This function maps the top of the [`RecRef`]. It's similar to [`Self::extend`], but 334 | /// it replaces the current reference instead of keeping it. See [`Self::extend`] for more details. 335 | pub fn map(rec_ref: &mut Self, func: F) 336 | where 337 | F: for<'b> FnOnce(&'b mut T) -> &'b mut T, 338 | { 339 | Self::map_result(rec_ref, |r| Ok(func(r))).void_unwrap() 340 | } 341 | 342 | /// Same as [`Self::map`], but allows the function to return an error value. 343 | pub fn map_result(rec_ref: &mut Self, func: F) -> Result<(), E> 344 | where 345 | F: for<'b> FnOnce(&'b mut T) -> Result<&'b mut T, E>, 346 | { 347 | Self::map_result_precise(rec_ref, |r, _| func(r)) 348 | } 349 | 350 | /// Same as [`Self::map`], but allows the function to return an error value, 351 | /// and also tells the inner function that `'a : 'b` using a phantom argument. 352 | pub fn map_result_precise(rec_ref: &mut Self, func: F) -> Result<(), E> 353 | where 354 | F: for<'b> FnOnce(&'b mut T, PhantomData<&'b &'a ()>) -> Result<&'b mut T, E>, 355 | { 356 | // Safety: 357 | // `rec_ref.head` was produced from a `&mut T`, and by RecRef's 358 | // safety invariant, it can be used. Furthermore, 359 | // Pushing another reference derived from it into the `rec_ref` preserves 360 | // the safety invariant. 361 | // 362 | // To understand how the invariant is ensured (and what it means) 363 | // see `RecRef::extend`'s documentation. 364 | // 365 | // However, there's another assumption here. 366 | // The lifetime of the reference here is indeterminate. 367 | // It could be any value. Thus by default the compiler will choose it 368 | // to be extremely short, that is, only until where `NonNull::from` is called on it. 369 | // 370 | // In fact, we want this lifetime to be a lifetime we haven't chosen yet. 371 | // It could be anything from as short as `'_` to as long as `'a`. 372 | // I arbitrarily chose it to be set to `'_`. 373 | // 374 | // Essentially, we assume here that calling `func` will have the same effect 375 | // even if we give it the wrong lifetime. In other words, we assume some form 376 | // of parametricity. 377 | // Semantically, this is true: code can't ever access the lifetimes. All lifetime 378 | // information is deleted at compile time. 379 | // However, we also assume that rust's optimizations 380 | // won't change the program's meaning because we used the wrong lifetime. 381 | 382 | let head_ref: &'_ mut T = unsafe { rec_ref.head.as_mut() }; 383 | 384 | match func(head_ref, PhantomData) { 385 | Ok(p) => { 386 | rec_ref.head = NonNull::from(p); 387 | Ok(()) 388 | } 389 | Err(e) => Err(e), 390 | } 391 | } 392 | 393 | /// Push another reference to the [`RecRef`], unrelated to the current one. 394 | /// `rec_ref.push(new_ref)` is morally equivalent to `rec_ref.extend_result_precise(move |_, _| { Ok(new_ref) })`. 395 | /// However, you might have some trouble making the anonymous function conform to the 396 | /// right type. 397 | pub fn push(rec_ref: &mut Self, r: &'a mut T) { 398 | rec_ref.vec.push(rec_ref.head); 399 | rec_ref.head = NonNull::from(r); 400 | 401 | /* alternative definition using a call to `extend_result_precise`. 402 | // in order to name 'x, replace the signature with: 403 | // pub fn push<'x>(rec_ref: &'x mut Self, r : &'a mut T) { 404 | // this is used in order to tell the closure to conform to the right type 405 | fn helper<'a,'x, T : ?Sized, F> (f : F) -> F where 406 | F : for<'b> FnOnce(&'b mut T, PhantomData<&'b &'a ()>) 407 | -> Result<&'b mut T, void::Void> + 'x 408 | { f } 409 | 410 | Self::extend_result_precise(rec_ref, 411 | helper::<'a,'x>(move |_, _phantom| { Ok(r) }) 412 | ).void_unwrap(); 413 | */ 414 | } 415 | 416 | /// Lets the user use the last reference for some time, and discards it completely. 417 | /// After the user uses it, the next time they inspect the [`RecRef`], it won't be there. 418 | /// If the [`RecRef`] has only one reference left, this returns `None`, because 419 | /// the [`RecRef`] can't be empty. 420 | pub fn pop(rec_ref: &mut Self) -> Option<&mut T> { 421 | // Safety: 422 | // This pointer was produced from a `&mut T`. 423 | // 424 | // By RecRef's safety invariant, this reference can be used. 425 | // Whenever it's used, `rec_ref` is frozen, preventing further 426 | // access until this reference is dropped. 427 | let res = unsafe { rec_ref.head.as_mut() }; 428 | rec_ref.head = rec_ref.vec.pop()?; // We can't pop the original reference. In that case, Return None. 429 | Some(res) 430 | } 431 | 432 | /// Discards the [`RecRef`] and returns the last reference. 433 | /// The difference between this and using [`Self::pop`] are: 434 | /// * This will consume the [`RecRef`] 435 | /// * [`Self::pop`] will never pop the first original reference, because that would produce an 436 | /// invalid [`RecRef`]. [`Self::into_ref`] will. 437 | pub fn into_ref(mut rec_ref: Self) -> &'a mut T { 438 | // Safety: 439 | // This pointer was produced from a `&mut T`. 440 | // 441 | // By RecRef's safety invariant, this reference can be used with lifetime `'a`. 442 | // `rec_ref` is consumed, preventing further 443 | // access until this reference is dropped. 444 | unsafe { rec_ref.head.as_mut() } 445 | } 446 | } 447 | 448 | /// [`RecRef`] represents a reference to a value of type `T`, 449 | /// which can move recursively into and out of its subfields of the same type `T`. 450 | /// Therefore, it implements `Deref` and `DerefMut` with `Item=T`. 451 | impl<'a, T: ?Sized> Deref for RecRef<'a, T> { 452 | type Target = T; 453 | fn deref(&self) -> &T { 454 | // Safety: 455 | // This pointer was produced from a `&mut T`. 456 | // 457 | // By RecRef's safety invariant, this reference can be used. 458 | // Whenever it's used, `rec_ref` is borrowed immutably, preventing mutable 459 | // access until this reference is dropped. 460 | unsafe { self.head.as_ref() } 461 | } 462 | } 463 | 464 | /// [`RecRef`] represents a reference to a value of type `T`, 465 | /// which can move recursively into and out of its subfields of the same type `T`. 466 | /// Therefore, it implements `Deref` and `DerefMut` with `Item=T`. 467 | impl<'a, T: ?Sized> DerefMut for RecRef<'a, T> { 468 | fn deref_mut(&mut self) -> &mut T { 469 | // Safety: 470 | // This pointer was produced from a `&mut T`. 471 | // 472 | // By RecRef's safety invariant, this reference can be used. 473 | // Whenever it's used, `rec_ref` is frozen, preventing further 474 | // access until this reference is dropped. 475 | unsafe { self.head.as_mut() } 476 | } 477 | } 478 | 479 | impl<'a, Q: ?Sized, T: ?Sized + AsRef> AsRef for RecRef<'a, T> { 480 | fn as_ref(&self) -> &Q { 481 | AsRef::as_ref(&**self) 482 | } 483 | } 484 | 485 | impl<'a, Q: ?Sized, T: ?Sized + AsMut> AsMut for RecRef<'a, T> { 486 | fn as_mut(&mut self) -> &mut Q { 487 | AsMut::as_mut(&mut **self) 488 | } 489 | } 490 | 491 | impl<'a, T: ?Sized> From<&'a mut T> for RecRef<'a, T> { 492 | fn from(r: &'a mut T) -> Self { 493 | Self::new(r) 494 | } 495 | } 496 | 497 | /// # Safety: 498 | /// Behaviorally, A [`RecRef`] is the same as `&'a mut T`, and 499 | /// should be [`Send`] for the same reason. Additionally, it contains a [`Vec`]. 500 | /// The [`Send`] instance for [`Vec`] contains the bound `A: Send` for the allocator type `A`, 501 | /// so we should require that as well. However, we don't have direct access to the 502 | /// default allocator type. So instead we require `Vec<&'a mut T>: Send`. 503 | unsafe impl<'a, T: ?Sized + Send> Send for RecRef<'a, T> where Vec<&'a mut T>: Send {} 504 | 505 | /// # Safety: 506 | /// Behaviorally, A [`RecRef`] is the same as `&'a mut T`, and 507 | /// should be [`Sync`] for the same reason. Additionally, it contains a [`Vec`]. 508 | /// The [`Sync`] instance for [`Vec`] contains the bound `A: Sync` for the allocator type `A`, 509 | /// so we should require that as well. However, we don't have direct access to the 510 | /// default allocator type. So instead we require `Vec<&'a mut T>: Sync`. 511 | unsafe impl<'a, T: ?Sized + Sync> Sync for RecRef<'a, T> where Vec<&'a mut T>: Sync {} 512 | --------------------------------------------------------------------------------