├── .gitignore ├── .travis.yml ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md ├── boxext_derive ├── Cargo.toml ├── README.md └── src │ └── lib.rs └── src ├── allocator_box.rs ├── dummy.rs └── lib.rs /.gitignore: -------------------------------------------------------------------------------- 1 | 2 | /target 3 | **/*.rs.bk 4 | Cargo.lock 5 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | dist: trusty 2 | language: rust 3 | matrix: 4 | include: 5 | - rust: 1.28.0 6 | env: ALLOCATOR_API=0.5.0 7 | - rust: 1.33.0 8 | - rust: stable 9 | - rust: beta 10 | - rust: nightly 11 | cache: cargo 12 | script: 13 | - ${ALLOCATOR_API:+cargo update} 14 | - ${ALLOCATOR_API:+cargo update -p allocator_api --precise $ALLOCATOR_API} 15 | - cargo test --verbose 16 | - cargo test --verbose --features allocator_api 17 | - cargo test --verbose --features allocator_api --no-default-features 18 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "boxext" 3 | version = "0.1.6" 4 | authors = ["Mike Hommey "] 5 | license = "Apache-2.0/MIT" 6 | description = "Extensions to the `Box` type" 7 | repository = "https://github.com/glandium/boxext" 8 | readme = "README.md" 9 | keywords = ["box", "allocator"] 10 | 11 | [features] 12 | default = ["std"] 13 | std = [] 14 | # Below are dummy features for backwards compatibility. Remove when version bumps to 0.2. 15 | unstable-rust = [] 16 | fallible = [] 17 | 18 | [dependencies] 19 | allocator_api = { version = ">=0.5, <0.7", optional = true, default-features = false } 20 | 21 | [dev-dependencies] 22 | boxext_derive = { path = "boxext_derive", version = "0.1" } 23 | -------------------------------------------------------------------------------- /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 [yyyy] [name of copyright owner] 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 | Permission is hereby granted, free of charge, to any 2 | person obtaining a copy of this software and associated 3 | documentation files (the "Software"), to deal in the 4 | Software without restriction, including without 5 | limitation the rights to use, copy, modify, merge, 6 | publish, distribute, sublicense, and/or sell copies of 7 | the Software, and to permit persons to whom the Software 8 | is furnished to do so, subject to the following 9 | conditions: 10 | 11 | The above copyright notice and this permission notice 12 | shall be included in all copies or substantial portions 13 | of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF 16 | ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 17 | TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A 18 | PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT 19 | SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 20 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION 21 | OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR 22 | IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER 23 | DEALINGS IN THE SOFTWARE. 24 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # boxext 2 | 3 | ## Extensions to the `Box` type 4 | 5 | This crate provides extra initializer methods for `Box`, working around the 6 | current (as of writing) shortcomings from `Box::new`: 7 | 8 | * Since Rust 1.12, constructs such as `Box::new([0; 4096])` first create a 9 | temporary object on the stack before copying it into the newly allocated 10 | space (e.g. [issue #50047]). 11 | 12 | * Constructs such as `Box::new(some_function_call())` first get the result 13 | from the function call on the stack before copying it into the newly 14 | allocated space. 15 | 16 | [issue #50047]: https://github.com/rust-lang/rust/issues/50047 17 | 18 | Both can be worked around with some contortion but with caveats. This crate 19 | provides helpers doing those contortions for you, but can't deal with the 20 | caveats. Those caveats are essentially the same as why the unstable 21 | placement features were removed in nightly 1.27, namely that there are no 22 | guarantees that things will actually happen in place (and they don't in 23 | debug builds). 24 | 25 | The crates adds the following helper methods to the `Box` type: 26 | 27 | * [`new_with`], which takes a function or closure returning the object that 28 | will be placed in the Box. 29 | 30 | * [`new_zeroed`], which creates an object filled with zeroes, possibly 31 | using [`calloc`]/[`HeapAlloc(..., HEAP_ZERO_MEMORY, ...)`]/ 32 | [`mallocx(..., MALLOCX_ZERO)`] under the hood. 33 | 34 | * [`try_new`], [`try_new_with`], and [`try_new_zeroed`], which are equivalent 35 | to `new`, `new_with` and `new_zeroed`, but don't panic on allocation 36 | failure. 37 | 38 | [`new_with`]: https://docs.rs/boxext/0.1.0/boxext/trait.BoxExt.html#tymethod.new_with 39 | [`new_zeroed`]: https://docs.rs/boxext/0.1.0/boxext/trait.BoxExt.html#tymethod.new_zeroed 40 | [`try_new`]: https://docs.rs/boxext/0.1.0/boxext/trait.BoxExt.html#tymethod.try_new 41 | [`try_new_with`]: https://docs.rs/boxext/0.1.0/boxext/trait.BoxExt.html#tymethod.try_new_with 42 | [`try_new_zeroed`]: https://docs.rs/boxext/0.1.0/boxext/trait.BoxExt.html#tymethod.try_new_zeroed 43 | [`calloc`]: http://pubs.opengroup.org/onlinepubs/009695399/functions/calloc.html 44 | [`HeapAlloc(..., HEAP_ZERO_MEMORY, ...)`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366597(v=vs.85).aspx#HEAP_ZERO_MEMORY 45 | [`mallocx(..., MALLOCX_ZERO)`]: http://jemalloc.net/jemalloc.3.html#MALLOCX_ZERO 46 | 47 | ### Examples 48 | 49 | ```rust 50 | extern crate boxext; 51 | use boxext::BoxExt; 52 | 53 | struct Foo(usize, usize); 54 | 55 | impl Foo { 56 | fn new(a: usize, b: usize) -> Self { 57 | Foo(a, b) 58 | } 59 | } 60 | 61 | impl Default for Foo { 62 | fn default() -> Self { 63 | Foo::new(0, 1) 64 | } 65 | } 66 | 67 | fn main() { 68 | // equivalent to `Box::new(Foo(1, 2))` 69 | let buf = Box::new_with(|| Foo(1, 2)); 70 | 71 | // equivalent to `Box::new(Foo::new(2, 3))` 72 | let buf = Box::new_with(|| Foo::new(2, 3)); 73 | 74 | // equivalent to `Box::new(Foo::default())` 75 | let buf = Box::new_with(Foo::default); 76 | 77 | // equivalent to `Box::new([0usize; 64])` 78 | let buf: Box<[usize; 64]> = Box::new_zeroed(); 79 | } 80 | ``` 81 | 82 | ### Features 83 | 84 | * `std` (enabled by default): Uses libstd. Can be disabled to allow use 85 | with `no_std` code, in which case `allocator_api` needs to be enabled. 86 | 87 | * `allocator_api`: Add similar helpers to the `Box` type from the 88 | `allocator_api` crate. 89 | 90 | License: Apache-2.0/MIT 91 | -------------------------------------------------------------------------------- /boxext_derive/Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "boxext_derive" 3 | version = "0.1.3" 4 | authors = ["Mike Hommey "] 5 | license = "Apache-2.0/MIT" 6 | description = "Custom Derive for the `boxext::Zero` trait" 7 | repository = "https://github.com/glandium/boxext" 8 | readme = "README.md" 9 | keywords = ["box", "allocator", "derive"] 10 | 11 | [dependencies] 12 | syn = ">= 0.12, <0.16" 13 | quote = ">=0.4, <0.7" 14 | 15 | [lib] 16 | proc-macro = true 17 | -------------------------------------------------------------------------------- /boxext_derive/README.md: -------------------------------------------------------------------------------- 1 | ## Custom Derive for the `boxext::Zero` trait 2 | 3 | Add `#[derive(Zero)]` on your types to automatically derive the `boxext::Zero` trait. 4 | Only structs aggregating types implementing the `boxext::Zero` trait are valid to use this with. 5 | 6 | ### Example 7 | 8 | ```rust 9 | extern crate boxext; 10 | #[macro_use] 11 | extern crate boxext_derive; 12 | use boxext::BoxExt; 13 | 14 | #[derive(Zero)] 15 | struct Foo { 16 | a: usize, 17 | b: f64, 18 | c: [usize; 4], 19 | } 20 | 21 | // #[derive(Zero)] 22 | // ^ the trait `boxext::Zero` is not implemented for `std::boxed::Box` 23 | // struct Bar { 24 | // a: usize, 25 | // b: Box, 26 | // } 27 | 28 | fn main() { 29 | // equivalent to Box::new(Foo { a: 0, b: 0.0, c: [0; 4] }) 30 | let buf: Box = Box::new_zeroed(); 31 | } 32 | ``` 33 | -------------------------------------------------------------------------------- /boxext_derive/src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Mike Hommey 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | extern crate proc_macro; 10 | 11 | #[macro_use] 12 | extern crate syn; 13 | 14 | #[macro_use] 15 | extern crate quote; 16 | 17 | use proc_macro::TokenStream; 18 | use syn::{Data, DeriveInput, Fields, WhereClause, WherePredicate}; 19 | 20 | #[proc_macro_derive(Zero)] 21 | pub fn derive_zero(input: TokenStream) -> TokenStream { 22 | let input: DeriveInput = syn::parse(input).unwrap(); 23 | 24 | let name = input.ident; 25 | 26 | let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl(); 27 | 28 | let mut types = vec![]; 29 | 30 | match input.data { 31 | Data::Struct(ref data) => match data.fields { 32 | Fields::Named(ref fields) => for f in &fields.named { 33 | types.push(&f.ty); 34 | }, 35 | Fields::Unnamed(ref fields) => for f in &fields.unnamed { 36 | types.push(&f.ty); 37 | }, 38 | Fields::Unit => {} 39 | }, 40 | _ => panic!("Can only derive(Zero) for structs"), 41 | } 42 | 43 | let mut where_clause = where_clause.cloned().unwrap_or_else(|| WhereClause { 44 | where_token: Default::default(), 45 | predicates: Default::default(), 46 | }); 47 | for t in types { 48 | let p: WherePredicate = parse_quote! { #t: ::boxext::Zero }; 49 | where_clause.predicates.push(p); 50 | } 51 | 52 | let expanded = quote! { 53 | unsafe impl #impl_generics ::boxext::Zero for #name #ty_generics #where_clause {} 54 | }; 55 | 56 | expanded.into() 57 | } 58 | -------------------------------------------------------------------------------- /src/allocator_box.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Mike Hommey 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | use allocator_api::{Alloc, Box, Layout, handle_alloc_error}; 10 | use core::ptr::{self, NonNull}; 11 | use {BoxExt, Zero}; 12 | 13 | /// Extensions to the `allocator_api::Box` type 14 | pub trait BoxInExt { 15 | /// Type contained inside the `Box`. 16 | type Inner; 17 | 18 | /// Allocates memory in the given allocator and then places the result of 19 | /// `f` into it. 20 | /// 21 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 22 | /// 23 | /// When building with optimization enabled, this is expected to avoid 24 | /// copies, contrary to `Box::new_in`. 25 | /// 26 | /// # Examples 27 | /// 28 | /// ``` 29 | /// extern crate allocator_api; 30 | /// extern crate boxext; 31 | /// use allocator_api::Box; 32 | /// use boxext::BoxInExt; 33 | /// # include!("dummy.rs"); 34 | /// 35 | /// #[derive(Debug, PartialEq)] 36 | /// struct Foo(usize, usize); 37 | /// 38 | /// impl Foo { 39 | /// fn new(a: usize, b: usize) -> Self { 40 | /// Foo(a, b) 41 | /// } 42 | /// } 43 | /// 44 | /// impl Default for Foo { 45 | /// fn default() -> Self { 46 | /// Foo::new(0, 1) 47 | /// } 48 | /// } 49 | /// 50 | /// fn main() { 51 | /// // equivalent to `Box::new_in(Foo(1, 2), MyHeap)` 52 | /// let buf = Box::new_in_with(|| Foo(1, 2), MyHeap); 53 | /// assert_eq!(*buf, Foo(1, 2)); 54 | /// 55 | /// // equivalent to `Box::new_in(Foo::new(2, 3), MyHeap)` 56 | /// let buf = Box::new_in_with(|| Foo::new(2, 3), MyHeap); 57 | /// assert_eq!(*buf, Foo(2, 3)); 58 | /// 59 | /// // equivalent to `Box::new_in(Foo::default(), MyHeap)` 60 | /// let buf = Box::new_in_with(Foo::default, MyHeap); 61 | /// assert_eq!(*buf, Foo::default()); 62 | /// } 63 | /// ``` 64 | fn new_in_with Self::Inner>(f: F, a: A) -> Self; 65 | 66 | /// Allocates zeroed memory in the given allocator. 67 | /// 68 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 69 | /// 70 | /// This will get zeroed memory directly from the allocator. 71 | /// 72 | /// # Example 73 | /// 74 | /// ``` 75 | /// extern crate allocator_api; 76 | /// extern crate boxext; 77 | /// use allocator_api::Box; 78 | /// use boxext::BoxInExt; 79 | /// # include!("dummy.rs"); 80 | /// 81 | /// fn main() { 82 | /// // equivalent to `Box::new_in([0usize; 32], MyHeap)` 83 | /// let buf: Box<[usize; 32], _> = Box::new_zeroed_in(MyHeap); 84 | /// assert_eq!(*buf, [0usize; 32]); 85 | /// } 86 | /// ``` 87 | /// 88 | /// # Safety 89 | /// 90 | /// This method is only assumed safe for `Self::Inner` types implementing 91 | /// the [`Zero`] trait, and not available otherwise. See the definition 92 | /// of that trait. 93 | /// 94 | /// [`Zero`]: trait.Zero.html 95 | fn new_zeroed_in(a: A) -> Self 96 | where 97 | Self: Sized, 98 | Self::Inner: Zero; 99 | 100 | /// Fallible [`Box::new_in`] 101 | /// 102 | /// [`Box::new_in`]: https://docs.rs/allocator_api/*/allocator_api/boxed/struct.Box.html#method.new_in 103 | /// 104 | /// This returns `None` if memory couldn't be allocated. 105 | /// 106 | /// # Examples 107 | /// 108 | /// ``` 109 | /// extern crate allocator_api; 110 | /// extern crate boxext; 111 | /// use allocator_api::Box; 112 | /// use boxext::BoxInExt; 113 | /// # include!("dummy.rs"); 114 | /// 115 | /// fn main() { 116 | /// let five = Box::try_new_in(5, MyHeap).unwrap(); 117 | /// assert_eq!(*five, 5); 118 | /// } 119 | /// ``` 120 | fn try_new_in(x: Self::Inner, a: A) -> Option 121 | where 122 | Self: Sized; 123 | 124 | /// Fallible [`Box::new_in_with`] 125 | /// 126 | /// [`Box::new_in_with`]: #method.new_in_with 127 | /// 128 | /// This returns `None` if memory couldn't be allocated. 129 | /// 130 | /// # Examples 131 | /// 132 | /// ``` 133 | /// extern crate allocator_api; 134 | /// extern crate boxext; 135 | /// use allocator_api::Box; 136 | /// use boxext::BoxInExt; 137 | /// # include!("dummy.rs"); 138 | /// 139 | /// #[derive(Debug, PartialEq)] 140 | /// struct Foo(usize, usize); 141 | /// 142 | /// impl Foo { 143 | /// fn new(a: usize, b: usize) -> Self { 144 | /// Foo(a, b) 145 | /// } 146 | /// } 147 | /// 148 | /// impl Default for Foo { 149 | /// fn default() -> Self { 150 | /// Foo::new(0, 1) 151 | /// } 152 | /// } 153 | /// 154 | /// fn main() { 155 | /// // equivalent to `Box::try_new_in(Foo(1, 2), MyHeap)` 156 | /// let buf = Box::try_new_in_with(|| Foo(1, 2), MyHeap).unwrap(); 157 | /// assert_eq!(*buf, Foo(1, 2)); 158 | /// 159 | /// // equivalent to `Box::try_new_in(Foo::new(2, 3), MyHeap)` 160 | /// let buf = Box::try_new_in_with(|| Foo::new(2, 3), MyHeap).unwrap(); 161 | /// assert_eq!(*buf, Foo(2, 3)); 162 | /// 163 | /// // equivalent to `Box::new_in(Foo::default(), MyHeap)` 164 | /// let buf = Box::try_new_in_with(Foo::default, MyHeap).unwrap(); 165 | /// assert_eq!(*buf, Foo::default()); 166 | /// } 167 | /// ``` 168 | fn try_new_in_with Self::Inner>(f: F, a: A) -> Option 169 | where 170 | Self: Sized; 171 | 172 | /// Fallible [`Box::new_zeroed`] 173 | /// 174 | /// [`Box::new_zeroed`]: #method.new_zeroed 175 | /// 176 | /// This returns `None` if memory couldn't be allocated. 177 | /// 178 | /// # Example 179 | /// 180 | /// ``` 181 | /// extern crate allocator_api; 182 | /// extern crate boxext; 183 | /// use allocator_api::Box; 184 | /// use boxext::BoxInExt; 185 | /// # include!("dummy.rs"); 186 | /// 187 | /// fn main() { 188 | /// // equivalent to `Box::try_new_in([0usize; 32], MyHeap)` 189 | /// let buf: Box<[usize; 32], _> = Box::try_new_zeroed_in(MyHeap).unwrap(); 190 | /// assert_eq!(*buf, [0usize; 32]); 191 | /// } 192 | /// ``` 193 | /// 194 | /// # Safety 195 | /// 196 | /// This method is only assumed safe for `Self::Inner` types implementing 197 | /// the [`Zero`] trait, and not available otherwise. See the definition 198 | /// of that trait. 199 | /// 200 | /// [`Zero`]: trait.Zero.html 201 | fn try_new_zeroed_in(a: A) -> Option 202 | where 203 | Self: Sized; 204 | } 205 | 206 | // Creates a new box in the given allocator, for the given type. 207 | // If the memory could be allocated, returns Ok(box). Otherwise, returns Err(layout), 208 | // allowing the caller to access the layout that failed allocation. 209 | unsafe fn new_box_in(mut a: A, zeroed: bool) -> Result, Layout> { 210 | let layout = Layout::new::(); 211 | let raw = if layout.size() == 0 { 212 | Ok(NonNull::::dangling()) 213 | } else if zeroed { 214 | a.alloc_zeroed(layout).map(NonNull::cast) 215 | } else { 216 | a.alloc(layout).map(NonNull::cast) 217 | }; 218 | match raw { 219 | Ok(raw) => Ok(Box::from_raw_in(raw.as_ptr(), a)), 220 | Err(_) => Err(layout), 221 | } 222 | } 223 | 224 | impl BoxInExt for Box { 225 | type Inner = T; 226 | 227 | #[inline] 228 | fn new_in_with T>(f: F, a: A) -> Self { 229 | unsafe { 230 | let mut b = new_box_in::(a, false).unwrap_or_else(|l| handle_alloc_error(l)); 231 | ptr::write(b.as_mut(), f()); 232 | b 233 | } 234 | } 235 | 236 | #[inline] 237 | fn new_zeroed_in(a: A) -> Self 238 | where 239 | T: Zero, 240 | { 241 | unsafe { new_box_in::(a, true).unwrap_or_else(|l| handle_alloc_error(l)) } 242 | } 243 | 244 | #[inline] 245 | fn try_new_in(x: T, mut a: A) -> Option { 246 | unsafe { 247 | let raw = a.alloc(Layout::new::()).ok()?.cast().as_ptr(); 248 | ptr::write(raw, x); 249 | Some(Box::from_raw_in(raw, a)) 250 | } 251 | } 252 | 253 | #[inline] 254 | fn try_new_in_with Self::Inner>(f: F, mut a: A) -> Option { 255 | unsafe { 256 | let raw = a.alloc(Layout::new::()).ok()?.cast().as_ptr(); 257 | ptr::write(raw, f()); 258 | Some(Box::from_raw_in(raw, a)) 259 | } 260 | } 261 | 262 | #[inline] 263 | fn try_new_zeroed_in(mut a: A) -> Option { 264 | unsafe { 265 | let raw = a.alloc_zeroed(Layout::new::()).ok()?.cast(); 266 | Some(Box::from_raw_in(raw.as_ptr(), a)) 267 | } 268 | } 269 | } 270 | 271 | impl BoxExt for Box { 272 | type Inner = >::Inner; 273 | 274 | /// Allocates memory in the given allocator and then places the result of 275 | /// `f` into it. 276 | /// 277 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 278 | /// 279 | /// When building with optimization enabled, this is expected to avoid 280 | /// copies, contrary to `allocator_api::Box::new_in`. 281 | /// 282 | /// # Examples 283 | /// 284 | /// ``` 285 | /// extern crate allocator_api; 286 | /// extern crate boxext; 287 | /// use allocator_api::Box; 288 | /// use boxext::BoxExt; 289 | /// # include!("dummy.rs"); 290 | /// 291 | /// #[derive(Debug, PartialEq)] 292 | /// struct Foo(usize, usize); 293 | /// 294 | /// impl Foo { 295 | /// fn new(a: usize, b: usize) -> Self { 296 | /// Foo(a, b) 297 | /// } 298 | /// } 299 | /// 300 | /// fn main() { 301 | /// // equivalent to `Box::new_in(Foo(1, 2), MyHeap)` 302 | /// let buf: Box<_, MyHeap> = Box::new_with(|| Foo(1, 2)); 303 | /// assert_eq!(*buf, Foo(1, 2)); 304 | /// 305 | /// // equivalent to `Box::new_in(Foo::new(2, 3), MyHeap)` 306 | /// let buf: Box<_, MyHeap> = Box::new_with(|| Foo::new(2, 3)); 307 | /// assert_eq!(*buf, Foo(2, 3)); 308 | /// } 309 | /// ``` 310 | /// 311 | /// This is a convenience wrapper around [`allocator_api::Box::new_in_with`] 312 | /// when the allocator implements `Default`. 313 | /// 314 | /// [`allocator_api::Box::new_in_with`]: trait.BoxInExt.html#tymethod.new_in_with 315 | #[inline] 316 | fn new_with Self::Inner>(f: F) -> Self { 317 | BoxInExt::new_in_with(f, Default::default()) 318 | } 319 | 320 | /// Allocates zeroed memory in the given allocator. 321 | /// 322 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 323 | /// 324 | /// This will get zeroed memory directly from it. 325 | /// 326 | /// # Example 327 | /// 328 | /// ``` 329 | /// extern crate allocator_api; 330 | /// extern crate boxext; 331 | /// use allocator_api::Box; 332 | /// use boxext::BoxExt; 333 | /// # include!("dummy.rs"); 334 | /// 335 | /// fn main() { 336 | /// // equivalent to `Box::new_in([0usize; 32], MyHeap)` 337 | /// let buf: Box<[usize; 32], MyHeap> = Box::new_zeroed(); 338 | /// assert_eq!(*buf, [0usize; 32]); 339 | /// } 340 | /// ``` 341 | /// 342 | /// This is a convenience wrapper around [`allocator_api::Box::new_zeroed_in`] 343 | /// when the allocator implements `Default`. 344 | /// 345 | /// [`allocator_api::Box::new_zeroed_in`]: trait.BoxInExt.html#tymethod.new_zeroed_in 346 | /// 347 | /// # Safety 348 | /// 349 | /// This method is only assumed safe for `Self::Inner` types implementing 350 | /// the [`Zero`] trait, and not available otherwise. See the definition 351 | /// of that trait. 352 | /// 353 | /// [`Zero`]: trait.Zero.html 354 | #[inline] 355 | fn new_zeroed() -> Self 356 | where 357 | T: Zero, 358 | { 359 | BoxInExt::new_zeroed_in(Default::default()) 360 | } 361 | 362 | /// Fallible [`Box::new`] 363 | /// 364 | /// [`Box::new`]: https://docs.rs/allocator_api/*/allocator_api/boxed/struct.Box.html#method.new 365 | /// 366 | /// This returns `None` if memory couldn't be allocated. 367 | /// 368 | /// # Examples 369 | /// 370 | /// ``` 371 | /// extern crate allocator_api; 372 | /// extern crate boxext; 373 | /// use allocator_api::Box; 374 | /// use boxext::BoxExt; 375 | /// # include!("dummy.rs"); 376 | /// 377 | /// fn main() { 378 | /// // equivalent to `Box::try_new_in(5, MyHeap)` 379 | /// let five: Box<_, MyHeap> = Box::try_new(5).unwrap(); 380 | /// assert_eq!(*five, 5); 381 | /// } 382 | /// ``` 383 | /// 384 | /// This is a convenience wrapper around [`allocator_api::Box::try_new_in`] 385 | /// when the allocator implements `Default`. 386 | /// 387 | /// [`allocator_api::Box::try_new_in`]: trait.BoxInExt.html#tymethod.try_new_in 388 | #[inline] 389 | fn try_new(x: T) -> Option { 390 | BoxInExt::try_new_in(x, Default::default()) 391 | } 392 | 393 | /// Fallible [`Box::new_with`] 394 | /// 395 | /// [`Box::new_with`]: #method.new_with 396 | /// 397 | /// This returns `None` if memory couldn't be allocated. 398 | /// 399 | /// # Examples 400 | /// 401 | /// ``` 402 | /// extern crate allocator_api; 403 | /// extern crate boxext; 404 | /// use allocator_api::Box; 405 | /// use boxext::BoxExt; 406 | /// # include!("dummy.rs"); 407 | /// 408 | /// #[derive(Debug, PartialEq)] 409 | /// struct Foo(usize, usize); 410 | /// 411 | /// impl Foo { 412 | /// fn new(a: usize, b: usize) -> Self { 413 | /// Foo(a, b) 414 | /// } 415 | /// } 416 | /// 417 | /// impl Default for Foo { 418 | /// fn default() -> Self { 419 | /// Foo::new(0, 1) 420 | /// } 421 | /// } 422 | /// 423 | /// fn main() { 424 | /// // equivalent to `Box::try_new_in(Foo(1, 2))` 425 | /// let buf: Box<_, MyHeap> = Box::try_new_with(|| Foo(1, 2)).unwrap(); 426 | /// assert_eq!(*buf, Foo(1, 2)); 427 | /// 428 | /// // equivalent to `Box::try_new_in(Foo::new(2, 3))` 429 | /// let buf: Box<_, MyHeap> = Box::try_new_with(|| Foo::new(2, 3)).unwrap(); 430 | /// assert_eq!(*buf, Foo(2, 3)); 431 | /// 432 | /// // equivalent to `Box::try_new_in(Foo::default())` 433 | /// let buf: Box<_, MyHeap> = Box::try_new_with(Foo::default).unwrap(); 434 | /// assert_eq!(*buf, Foo::default()); 435 | /// } 436 | /// ``` 437 | /// 438 | /// This is a convenience wrapper around [`allocator_api::Box::try_new_in_with`] 439 | /// when the allocator implements `Default`. 440 | /// 441 | /// [`allocator_api::Box::try_new_in_with`]: trait.BoxInExt.html#tymethod.try_new_in_with 442 | #[inline] 443 | fn try_new_with Self::Inner>(f: F) -> Option { 444 | BoxInExt::try_new_in_with(f, Default::default()) 445 | } 446 | 447 | /// Fallible [`Box::new_zeroed`] 448 | /// 449 | /// [`Box::new_zeroed`]: #method.new_zeroed 450 | /// 451 | /// This returns `None` if memory couldn't be allocated. 452 | /// 453 | /// # Example 454 | /// 455 | /// ``` 456 | /// extern crate allocator_api; 457 | /// extern crate boxext; 458 | /// use allocator_api::Box; 459 | /// use boxext::BoxExt; 460 | /// # include!("dummy.rs"); 461 | /// 462 | /// fn main() { 463 | /// // equivalent to `Box::try_new([0usize; 32])` 464 | /// let buf: Box<[usize; 32], MyHeap> = Box::try_new_zeroed().unwrap(); 465 | /// assert_eq!(*buf, [0usize; 32]); 466 | /// } 467 | /// ``` 468 | /// 469 | /// This is a convenience wrapper around [`allocator_api::Box::try_new_zeroed_in`] 470 | /// when the allocator implements `Default`. 471 | /// 472 | /// [`allocator_api::Box::try_new_zeroed_in`]: trait.BoxInExt.html#tymethod.try_new_zeroed_in 473 | /// 474 | /// 475 | /// # Safety 476 | /// 477 | /// This method is only assumed safe for `Self::Inner` types implementing 478 | /// the [`Zero`] trait, and not available otherwise. See the definition 479 | /// of that trait. 480 | /// 481 | /// [`Zero`]: trait.Zero.html 482 | #[inline] 483 | fn try_new_zeroed() -> Option 484 | where 485 | Self::Inner: Zero, 486 | { 487 | BoxInExt::try_new_zeroed_in(Default::default()) 488 | } 489 | } 490 | -------------------------------------------------------------------------------- /src/dummy.rs: -------------------------------------------------------------------------------- 1 | /// A dummy allocator for tests. 2 | 3 | mod dummy { 4 | extern crate core; 5 | use super::allocator_api::{Alloc, AllocErr, Layout}; 6 | use self::core::ptr::NonNull; 7 | 8 | #[derive(Clone, Default)] 9 | pub struct MyHeap; 10 | 11 | static mut HEAP_BUF: [u8; 4096] = [0; 4096]; 12 | static mut HEAP_CURSOR: usize = 0; 13 | 14 | unsafe impl<'a> Alloc for MyHeap { 15 | unsafe fn alloc(&mut self, layout: Layout) -> Result, AllocErr> { 16 | let ptr = HEAP_BUF.as_ptr() as usize; 17 | let mut start = HEAP_CURSOR; 18 | let modulo = (ptr + start) & (layout.align() - 1); 19 | if modulo != 0 { 20 | start += layout.align() - modulo; 21 | } 22 | assert_eq!((ptr + start) & (layout.align() - 1), 0); 23 | let end = start + layout.size(); 24 | let buf = HEAP_BUF.get_mut(start..end); 25 | HEAP_CURSOR = end; 26 | buf.map(|b| NonNull::new_unchecked(b as *mut [u8] as *mut u8)) 27 | .ok_or_else(|| AllocErr) 28 | } 29 | unsafe fn dealloc(&mut self, _ptr: NonNull, _layout: Layout) {} 30 | } 31 | 32 | } 33 | 34 | use self::dummy::MyHeap; 35 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | // Copyright 2018 Mike Hommey 2 | // 3 | // Licensed under the Apache License, Version 2.0 or the MIT license 5 | // , at your 6 | // option. This file may not be copied, modified, or distributed 7 | // except according to those terms. 8 | 9 | #![deny(missing_docs)] 10 | 11 | //! # Extensions to the `Box` type 12 | //! 13 | //! This crate provides extra initializer methods for `Box`, working around the 14 | //! current (as of writing) shortcomings from `Box::new`: 15 | //! 16 | //! * Since Rust 1.12, constructs such as `Box::new([0; 4096])` first create a 17 | //! temporary object on the stack before copying it into the newly allocated 18 | //! space (e.g. [issue #50047]). 19 | //! 20 | //! * Constructs such as `Box::new(some_function_call())` first get the result 21 | //! from the function call on the stack before copying it into the newly 22 | //! allocated space. 23 | //! 24 | //! [issue #50047]: https://github.com/rust-lang/rust/issues/50047 25 | //! 26 | //! Both can be worked around with some contortion but with caveats. This crate 27 | //! provides helpers doing those contortions for you, but can't deal with the 28 | //! caveats. Those caveats are essentially the same as why the unstable 29 | //! placement features were removed in nightly 1.27, namely that there are no 30 | //! guarantees that things will actually happen in place (and they don't in 31 | //! debug builds). 32 | //! 33 | //! The crates adds the following helper methods to the `Box` type: 34 | //! 35 | //! * [`new_with`], which takes a function or closure returning the object that 36 | //! will be placed in the Box. 37 | //! 38 | //! * [`new_zeroed`], which creates an object filled with zeroes, possibly 39 | //! using [`calloc`]/[`HeapAlloc(..., HEAP_ZERO_MEMORY, ...)`]/ 40 | //! [`mallocx(..., MALLOCX_ZERO)`] under the hood. 41 | //! 42 | //! * [`try_new`], [`try_new_with`], and [`try_new_zeroed`], which are equivalent 43 | //! to `new`, `new_with` and `new_zeroed`, but don't panic on allocation 44 | //! failure. 45 | //! 46 | //! [`new_with`]: trait.BoxExt.html#tymethod.new_with 47 | //! [`new_zeroed`]: trait.BoxExt.html#tymethod.new_zeroed 48 | //! [`try_new`]: trait.BoxExt.html#tymethod.try_new 49 | //! [`try_new_with`]: trait.BoxExt.html#tymethod.try_new_with 50 | //! [`try_new_zeroed`]: trait.BoxExt.html#tymethod.try_new_zeroed 51 | //! [`calloc`]: http://pubs.opengroup.org/onlinepubs/009695399/functions/calloc.html 52 | //! [`HeapAlloc(..., HEAP_ZERO_MEMORY, ...)`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366597(v=vs.85).aspx#HEAP_ZERO_MEMORY 53 | //! [`mallocx(..., MALLOCX_ZERO)`]: http://jemalloc.net/jemalloc.3.html#MALLOCX_ZERO 54 | //! 55 | //! ## Features 56 | //! 57 | //! * `std` (enabled by default): Uses libstd. Can be disabled to allow use 58 | //! with `no_std` code, in which case `allocator_api` needs to be enabled. 59 | //! 60 | //! * `allocator_api`: Add similar helpers to the `Box` type from the 61 | //! `allocator_api` crate. 62 | 63 | #![cfg_attr(not(feature = "std"), no_std)] 64 | 65 | #[cfg(feature = "std")] 66 | use std::alloc::{handle_alloc_error, alloc, alloc_zeroed, Layout}; 67 | 68 | #[cfg(feature = "allocator_api")] 69 | extern crate allocator_api; 70 | 71 | #[cfg(feature = "std")] 72 | extern crate core; 73 | 74 | #[cfg(feature = "std")] 75 | use core::ptr; 76 | 77 | #[cfg(feature = "allocator_api")] 78 | mod allocator_box; 79 | #[cfg(feature = "allocator_api")] 80 | pub use allocator_box::*; 81 | 82 | /// Extensions to the `Box` type 83 | pub trait BoxExt { 84 | /// Type contained inside the `Box`. 85 | type Inner; 86 | 87 | /// Allocates memory on the heap and then places the result of `f` into it. 88 | /// 89 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 90 | /// 91 | /// When building with optimization enabled, this is expected to avoid 92 | /// copies, contrary to `Box::new`. 93 | /// 94 | /// # Examples 95 | /// 96 | /// ``` 97 | /// extern crate boxext; 98 | /// use boxext::BoxExt; 99 | /// 100 | /// #[derive(Debug, PartialEq)] 101 | /// struct Foo(usize, usize); 102 | /// 103 | /// impl Foo { 104 | /// fn new(a: usize, b: usize) -> Self { 105 | /// Foo(a, b) 106 | /// } 107 | /// } 108 | /// 109 | /// impl Default for Foo { 110 | /// fn default() -> Self { 111 | /// Foo::new(0, 1) 112 | /// } 113 | /// } 114 | /// 115 | /// fn main() { 116 | /// // equivalent to `Box::new(Foo(1, 2))` 117 | /// # #[cfg(feature = "std")] 118 | /// let buf = Box::new_with(|| Foo(1, 2)); 119 | /// # #[cfg(feature = "std")] 120 | /// assert_eq!(*buf, Foo(1, 2)); 121 | /// 122 | /// // equivalent to `Box::new(Foo::new(2, 3))` 123 | /// # #[cfg(feature = "std")] 124 | /// let buf = Box::new_with(|| Foo::new(2, 3)); 125 | /// # #[cfg(feature = "std")] 126 | /// assert_eq!(*buf, Foo(2, 3)); 127 | /// 128 | /// // equivalent to `Box::new(Foo::default())` 129 | /// # #[cfg(feature = "std")] 130 | /// let buf = Box::new_with(Foo::default); 131 | /// # #[cfg(feature = "std")] 132 | /// assert_eq!(*buf, Foo::default()); 133 | /// } 134 | /// ``` 135 | fn new_with Self::Inner>(f: F) -> Self; 136 | 137 | /// Allocates zeroed memory on the heap. 138 | /// 139 | /// This doesn't actually allocate if `Self::Inner` is zero-sized. 140 | /// 141 | /// This method will obtain zeroed memory directly from the underlying 142 | /// allocator, through the use of [`calloc`], [`HeapAlloc(..., 143 | /// HEAP_ZERO_MEMORY, ...)`] or [`mallocx(..., MALLOCX_ZERO)`], whichever 144 | /// is used as a global allocator by the rust compiler. 145 | /// 146 | /// [`calloc`]: http://pubs.opengroup.org/onlinepubs/009695399/functions/calloc.html 147 | /// [`HeapAlloc(..., HEAP_ZERO_MEMORY, ...)`]: https://msdn.microsoft.com/en-us/library/windows/desktop/aa366597(v=vs.85).aspx#HEAP_ZERO_MEMORY 148 | /// [`mallocx(..., MALLOCX_ZERO)`]: http://jemalloc.net/jemalloc.3.html#MALLOCX_ZERO 149 | /// 150 | /// # Example 151 | /// 152 | /// ``` 153 | /// extern crate boxext; 154 | /// use boxext::BoxExt; 155 | /// 156 | /// fn main() { 157 | /// // equivalent to `Box::new([0usize; 32])` 158 | /// # #[cfg(feature = "std")] 159 | /// let buf: Box<[usize; 32]> = Box::new_zeroed(); 160 | /// # #[cfg(feature = "std")] 161 | /// assert_eq!(*buf, [0usize; 32]); 162 | /// } 163 | /// ``` 164 | /// 165 | /// # Safety 166 | /// 167 | /// This method is only assumed safe for `Self::Inner` types implementing 168 | /// the [`Zero`] trait, and not available otherwise. See the definition 169 | /// of that trait. 170 | /// 171 | /// [`Zero`]: trait.Zero.html 172 | fn new_zeroed() -> Self 173 | where 174 | Self: Sized, 175 | Self::Inner: Zero; 176 | 177 | /// Fallible [`Box::new`] 178 | /// 179 | /// [`Box::new`]: https://doc.rust-lang.org/std/boxed/struct.Box.html#method.new 180 | /// 181 | /// This returns `None` if memory couldn't be allocated. 182 | /// 183 | /// # Examples 184 | /// 185 | /// ``` 186 | /// extern crate boxext; 187 | /// use boxext::BoxExt; 188 | /// 189 | /// fn main() { 190 | /// # #[cfg(feature = "std")] 191 | /// let five = Box::try_new(5).unwrap(); 192 | /// # #[cfg(feature = "std")] 193 | /// assert_eq!(*five, 5); 194 | /// } 195 | /// ``` 196 | fn try_new(x: Self::Inner) -> Option 197 | where 198 | Self: Sized; 199 | 200 | /// Fallible [`Box::new_with`] 201 | /// 202 | /// [`Box::new_with`]: #method.new_with 203 | /// 204 | /// This returns `None` if memory couldn't be allocated. 205 | /// 206 | /// # Examples 207 | /// 208 | /// ``` 209 | /// extern crate boxext; 210 | /// use boxext::BoxExt; 211 | /// 212 | /// #[derive(Debug, PartialEq)] 213 | /// struct Foo(usize, usize); 214 | /// 215 | /// impl Foo { 216 | /// fn new(a: usize, b: usize) -> Self { 217 | /// Foo(a, b) 218 | /// } 219 | /// } 220 | /// 221 | /// impl Default for Foo { 222 | /// fn default() -> Self { 223 | /// Foo::new(0, 1) 224 | /// } 225 | /// } 226 | /// 227 | /// fn main() { 228 | /// // equivalent to `Box::try_new(Foo(1, 2))` 229 | /// # #[cfg(feature = "std")] 230 | /// let buf = Box::try_new_with(|| Foo(1, 2)).unwrap(); 231 | /// # #[cfg(feature = "std")] 232 | /// assert_eq!(*buf, Foo(1, 2)); 233 | /// 234 | /// // equivalent to `Box::try_new(Foo::new(2, 3))` 235 | /// # #[cfg(feature = "std")] 236 | /// let buf = Box::try_new_with(|| Foo::new(2, 3)).unwrap(); 237 | /// # #[cfg(feature = "std")] 238 | /// assert_eq!(*buf, Foo(2, 3)); 239 | /// 240 | /// // equivalent to `Box::try_new(Foo::default())` 241 | /// # #[cfg(feature = "std")] 242 | /// let buf = Box::try_new_with(Foo::default).unwrap(); 243 | /// # #[cfg(feature = "std")] 244 | /// assert_eq!(*buf, Foo::default()); 245 | /// } 246 | /// ``` 247 | fn try_new_with Self::Inner>(f: F) -> Option 248 | where 249 | Self: Sized; 250 | 251 | /// Fallible [`Box::new_zeroed`] 252 | /// 253 | /// [`Box::new_zeroed`]: #method.new_zeroed 254 | /// 255 | /// This returns `None` if memory couldn't be allocated. 256 | /// 257 | /// # Example 258 | /// 259 | /// ``` 260 | /// extern crate boxext; 261 | /// use boxext::BoxExt; 262 | /// 263 | /// fn main() { 264 | /// // equivalent to `Box::try_new([0usize; 32])` 265 | /// # #[cfg(feature = "std")] 266 | /// let buf: Box<[usize; 32]> = Box::try_new_zeroed().unwrap(); 267 | /// # #[cfg(feature = "std")] 268 | /// assert_eq!(*buf, [0usize; 32]); 269 | /// } 270 | /// ``` 271 | /// 272 | /// # Safety 273 | /// 274 | /// This method is only assumed safe for `Self::Inner` types implementing 275 | /// the [`Zero`] trait, and not available otherwise. See the definition 276 | /// of that trait. 277 | /// 278 | /// [`Zero`]: trait.Zero.html 279 | fn try_new_zeroed() -> Option 280 | where 281 | Self: Sized, 282 | Self::Inner: Zero; 283 | } 284 | 285 | #[cfg(feature = "std")] 286 | unsafe fn try_new_box(zeroed: bool) -> Result, Layout> { 287 | let layout = Layout::new::(); 288 | let raw = if layout.size() == 0 { 289 | ptr::NonNull::::dangling().as_ptr() 290 | } else if zeroed { 291 | alloc_zeroed(layout) as *mut T 292 | } else { 293 | alloc(layout) as *mut T 294 | }; 295 | if !raw.is_null() { 296 | Ok(Box::from_raw(raw)) 297 | } else { 298 | Err(layout) 299 | } 300 | } 301 | 302 | #[cfg(feature = "std")] 303 | unsafe fn new_box(zeroed: bool) -> Box { 304 | try_new_box::(zeroed).unwrap_or_else(|l| handle_alloc_error(l)) 305 | } 306 | 307 | #[cfg(feature = "std")] 308 | impl BoxExt for Box { 309 | type Inner = T; 310 | 311 | #[inline] 312 | fn new_with T>(f: F) -> Box { 313 | unsafe { 314 | let mut b = new_box::(false); 315 | ptr::write(b.as_mut(), f()); 316 | b 317 | } 318 | } 319 | 320 | #[inline] 321 | fn new_zeroed() -> Box 322 | where 323 | T: Zero, 324 | { 325 | unsafe { new_box(true) } 326 | } 327 | 328 | #[inline] 329 | fn try_new(x: T) -> Option { 330 | unsafe { 331 | let mut b = try_new_box::(false).ok()?; 332 | ptr::write(b.as_mut(), x); 333 | Some(b) 334 | } 335 | } 336 | 337 | #[inline] 338 | fn try_new_with Self::Inner>(f: F) -> Option { 339 | unsafe { 340 | let mut b = try_new_box::(false).ok()?; 341 | ptr::write(b.as_mut(), f()); 342 | Some(b) 343 | } 344 | } 345 | 346 | #[inline] 347 | fn try_new_zeroed() -> Option 348 | where 349 | Self::Inner: Zero, 350 | { 351 | unsafe { try_new_box::(true).ok() } 352 | } 353 | } 354 | 355 | /// Trait indicating whether a value full of zeroes is valid. 356 | /// 357 | /// This trait is used to enable the [`Box::new_zeroed`] method for types where 358 | /// it's safe to use. 359 | /// 360 | /// [`Box::new_zeroed`]: trait.BoxExt.html#tymethod::new_zeroed 361 | /// 362 | /// # Safety 363 | /// 364 | /// Do **not** implement this trait for types where a raw byte array of 0 365 | /// doesn't represent a valid value for the type. Please double check it is 366 | /// valid and corresponds to what you want. 367 | /// 368 | /// # Examples 369 | /// 370 | /// ``` 371 | /// extern crate boxext; 372 | /// use boxext::{BoxExt, Zero}; 373 | /// 374 | /// #[derive(Debug, PartialEq)] 375 | /// struct Foo(usize); 376 | /// 377 | /// unsafe impl Zero for Foo {} 378 | /// 379 | /// fn main() { 380 | /// // equivalent to `Box::new(Foo(0))` 381 | /// # #[cfg(feature = "std")] 382 | /// let buf: Box = Box::new_zeroed(); 383 | /// # #[cfg(feature = "std")] 384 | /// assert_eq!(*buf, Foo(0)); 385 | /// } 386 | /// ``` 387 | /// 388 | /// For convenience, a `boxext_derive` crate is provided that provides a 389 | /// custom derive for `Zero`. 390 | /// 391 | /// ``` 392 | /// extern crate boxext; 393 | /// #[macro_use] 394 | /// extern crate boxext_derive; 395 | /// use boxext::BoxExt; 396 | /// 397 | /// #[derive(Zero, Debug, PartialEq)] 398 | /// struct Foo(usize); 399 | /// 400 | /// fn main() { 401 | /// // equivalent to `Box::new(Foo(0))` 402 | /// # #[cfg(feature = "std")] 403 | /// let buf: Box = Box::new_zeroed(); 404 | /// # #[cfg(feature = "std")] 405 | /// assert_eq!(*buf, Foo(0)); 406 | /// } 407 | /// ``` 408 | /// 409 | /// ```compile_fail 410 | /// extern crate boxext; 411 | /// #[macro_use] 412 | /// extern crate boxext_derive; 413 | /// use boxext::BoxExt; 414 | /// 415 | /// #[derive(Zero)] 416 | /// // ^ the trait `boxext::Zero` is not implemented for `Bar` 417 | /// struct Foo(Bar); 418 | /// 419 | /// struct Bar; 420 | /// 421 | /// fn main() { 422 | /// // equivalent to `Box::new(Foo(0))` 423 | /// let buf: Box = Box::new_zeroed(); 424 | /// } 425 | /// ``` 426 | /// 427 | pub unsafe trait Zero: Sized {} 428 | 429 | macro_rules! zero_num_impl { 430 | ($($t:ty)+) => { $(unsafe impl Zero for $t {})+ } 431 | } 432 | 433 | zero_num_impl! { 434 | u8 u16 u32 u64 usize 435 | i8 i16 i32 i64 isize 436 | f32 f64 437 | } 438 | 439 | unsafe impl Zero for *mut T {} 440 | 441 | unsafe impl Zero for *const T {} 442 | 443 | macro_rules! zero_array_impl { 444 | ($($n:expr)+) => {$( 445 | unsafe impl Zero for [T; $n] {} 446 | )+}; 447 | } 448 | 449 | zero_array_impl! { 450 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 451 | 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 452 | 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 453 | 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 454 | 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 455 | 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 456 | 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 457 | 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 458 | 160 192 200 224 256 384 512 768 1024 2048 4096 8192 16384 32768 459 | } 460 | 461 | #[cfg(any(target_pointer_width = "32", target_pointer_width = "64"))] 462 | zero_array_impl! { 463 | 65536 131072 262144 524288 1048576 2097152 4194304 8388608 464 | 16777216 33554432 67108864 134217728 268435456 536870912 465 | 1073741824 2147483648 466 | } 467 | 468 | #[cfg(target_pointer_width = "64")] 469 | zero_array_impl! { 470 | 4294967296 471 | } 472 | 473 | macro_rules! zero_tuple_impl { 474 | ($t:ident $($u:ident)+) => { 475 | zero_tuple_impl!(($t) $($u)+); 476 | }; 477 | (($($t:ident)+) $u:ident $($v:ident)*) => { 478 | zero_tuple_impl!(($($t)+)); 479 | zero_tuple_impl!(($($t)+ $u) $($v)*); 480 | }; 481 | (($($t:ident)+)) => { 482 | unsafe impl<$($t: Zero),+> Zero for ($($t,)+) {} 483 | }; 484 | } 485 | 486 | zero_tuple_impl! { 487 | A B C D E F G H I J K L 488 | } 489 | --------------------------------------------------------------------------------