maybe-uninit-2.0.0/.gitignore010066400017500001750000000000371351074657300143400ustar0000000000000000/target/ **/*.rs.bk Cargo.lock maybe-uninit-2.0.0/.travis.yml010066400017500001750000000002641351136140300144450ustar0000000000000000language: rust rust: - 1.20.0 - 1.22.0 - 1.28.0 - 1.36.0 - nightly - beta - stable script: - cargo build --verbose - cargo test --verbose - cargo doc --verbose maybe-uninit-2.0.0/Cargo.toml.orig010066400017500001750000000004661351136535400152400ustar0000000000000000[package] name = "maybe-uninit" version = "2.0.0" description = "MaybeUninit for friends of backwards compatibility" authors = ["est31 ", "The Rust Project Developers"] license = "Apache-2.0 OR MIT" readme = "README.md" repository = "https://github.com/est31/maybe-uninit" [dependencies] maybe-uninit-2.0.0/Cargo.toml0000644000000015030000000000000114700ustar00# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies # # If you believe there's an error in this file please file an # issue against the rust-lang/cargo repository. If you're # editing this file be aware that the upstream Cargo.toml # will likely look very different (and much more reasonable) [package] name = "maybe-uninit" version = "2.0.0" authors = ["est31 ", "The Rust Project Developers"] description = "MaybeUninit for friends of backwards compatibility" readme = "README.md" license = "Apache-2.0 OR MIT" repository = "https://github.com/est31/maybe-uninit" [dependencies] maybe-uninit-2.0.0/LICENSE-APACHE010066400017500001750000000251371351074665400143040ustar0000000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright [yyyy] [name of copyright owner] Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. maybe-uninit-2.0.0/LICENSE-MIT010066400017500001750000000020571351074665400140100ustar0000000000000000Copyright (c) 2010 The Rust Project Developers Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. maybe-uninit-2.0.0/README.md010066400017500001750000000017441351136220300136160ustar0000000000000000# maybe-uninit Quite often, uses of `std::mem::uninitialized()` end up in unsound code. Therefore, the `MaybeUninit` union has been added to `std::mem` and `std::mem::uninitialized()` is being deprecated. However, `MaybeUninit` has been added quite recently. Sometimes you might want to support older versions of Rust as well. Here is where `maybe-uninit` comes in: it supports stable Rust versions starting with 1.20.0. Sadly, a feature-complete implementation of `MaybeUninit` is not possible on stable Rust. Therefore, the library offers the guarantees of `MaybeUninit` in a staged fashion: * Rust 1.36.0 onward: `MaybeUninit` implementation of Rust stable is being re-exported * Rust 1.22.x - 1.35.0: No panicing on uninhabited types, unsoundness when used with types like `bool` or enums. However, there is protection from accidentially `Drop`ing e.g. during unwind! * Rust 1.20.x - 1.21.x: No support for Copy/Clone of `MaybeUninit`, even if `T` impls `Copy` or even `Clone`. maybe-uninit-2.0.0/build.rs010066400017500001750000000020531351136134700140060ustar0000000000000000use std::env; use std::process::Command; use std::str::FromStr; fn main() { let minor = match rustc_minor_version() { Some(minor) => minor, None => return, }; if minor >= 22 { println!("cargo:rustc-cfg=derive_copy"); } if minor >= 28 { println!("cargo:rustc-cfg=repr_transparent"); } if minor >= 36 { println!("cargo:rustc-cfg=native_uninit"); } } fn rustc_minor_version() -> Option { let rustc = env::var_os("RUSTC"); let output = rustc.and_then(|rustc| { Command::new(rustc).arg("--version").output().ok() }); let version = output.and_then(|output| { String::from_utf8(output.stdout).ok() }); let version = if let Some(version) = version { version } else { return None; }; let mut pieces = version.split('.'); if pieces.next() != Some("rustc 1") { return None; } let next = match pieces.next() { Some(next) => next, None => return None, }; u32::from_str(next).ok() } maybe-uninit-2.0.0/src/lib.rs010066400017500001750000000002571351136142700142470ustar0000000000000000#![no_std] #[cfg(not(native_uninit))] mod maybe_uninit; #[cfg(not(native_uninit))] pub use maybe_uninit::MaybeUninit; #[cfg(native_uninit)] pub use core::mem::MaybeUninit; maybe-uninit-2.0.0/src/maybe_uninit.rs010066400017500001750000000532031351136454600161700ustar0000000000000000//use core::intrinsics; use core::mem::ManuallyDrop; use core::ptr; use core::mem::uninitialized; /// A wrapper type to construct uninitialized instances of `T`. /// /// # Initialization invariant /// /// The compiler, in general, assumes that variables are properly initialized /// at their respective type. For example, a variable of reference type must /// be aligned and non-NULL. This is an invariant that must *always* be upheld, /// even in unsafe code. As a consequence, zero-initializing a variable of reference /// type causes instantaneous [undefined behavior][ub], no matter whether that reference /// ever gets used to access memory: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::mem; /// /// let x: &i32 = unsafe { mem::zeroed() }; // undefined behavior! /// // The equivalent code with `MaybeUninit<&i32>`: /// let x: &i32 = unsafe { MaybeUninit::zeroed().assume_init() }; // undefined behavior! /// # } /// ``` /// /// This is exploited by the compiler for various optimizations, such as eliding /// run-time checks and optimizing `enum` layout. /// /// Similarly, entirely uninitialized memory may have any content, while a `bool` must /// always be `true` or `false`. Hence, creating an uninitialized `bool` is undefined behavior: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::mem; /// /// let b: bool = unsafe { mem::uninitialized() }; // undefined behavior! /// // The equivalent code with `MaybeUninit`: /// let b: bool = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! /// # } /// ``` /// /// Moreover, uninitialized memory is special in that the compiler knows that /// it does not have a fixed value. This makes it undefined behavior to have /// uninitialized data in a variable even if that variable has an integer type, /// which otherwise can hold any *fixed* bit pattern: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::mem; /// /// let x: i32 = unsafe { mem::uninitialized() }; // undefined behavior! /// // The equivalent code with `MaybeUninit`: /// let x: i32 = unsafe { MaybeUninit::uninit().assume_init() }; // undefined behavior! /// # } /// ``` /// (Notice that the rules around uninitialized integers are not finalized yet, but /// until they are, it is advisable to avoid them.) /// /// On top of that, remember that most types have additional invariants beyond merely /// being considered initialized at the type level. For example, a `1`-initialized [`Vec`] /// is considered initialized because the only requirement the compiler knows about it /// is that the data pointer must be non-null. Creating such a `Vec` does not cause /// *immediate* undefined behavior, but will cause undefined behavior with most /// safe operations (including dropping it). /// /// [`Vec`]: ../../std/vec/struct.Vec.html /// /// # Examples /// /// `MaybeUninit` serves to enable unsafe code to deal with uninitialized data. /// It is a signal to the compiler indicating that the data here might *not* /// be initialized: /// /// ```rust /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr::write; /// /// // Create an explicitly uninitialized reference. The compiler knows that data inside /// // a `MaybeUninit` may be invalid, and hence this is not UB: /// let mut x = MaybeUninit::<&i32>::uninit(); /// // Set it to a valid value. /// const V: &'static i32 = &0; /// unsafe { write(x.as_mut_ptr(), V); } /// // Extract the initialized data -- this is only allowed *after* properly /// // initializing `x`! /// let x = unsafe { x.assume_init() }; /// # } /// ``` /// /// The compiler then knows to not make any incorrect assumptions or optimizations on this code. /// /// You can think of `MaybeUninit` as being a bit like `Option` but without /// any of the run-time tracking and without any of the safety checks. /// /// ## out-pointers /// /// You can use `MaybeUninit` to implement "out-pointers": instead of returning data /// from a function, pass it a pointer to some (uninitialized) memory to put the /// result into. This can be useful when it is important for the caller to control /// how the memory the result is stored in gets allocated, and you want to avoid /// unnecessary moves. /// /// ``` /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr; /// /// unsafe fn make_vec(out: *mut Vec) { /// // `write` does not drop the old contents, which is important. /// ptr::write(out, vec![1, 2, 3]); /// } /// /// let mut v = MaybeUninit::uninit(); /// unsafe { make_vec(v.as_mut_ptr()); } /// // Now we know `v` is initialized! This also makes sure the vector gets /// // properly dropped. /// let v = unsafe { v.assume_init() }; /// assert_eq!(&v, &[1, 2, 3]); /// # } /// ``` /// /// ## Initializing an array element-by-element /// /// `MaybeUninit` can be used to initialize a large array element-by-element: /// /// ``` /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::mem; /// use std::ptr; /// /// let data = { /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is /// // safe because the type we are claiming to have initialized here is a /// // bunch of `MaybeUninit`s, which do not require initialization. /// let mut data: [MaybeUninit>; 1000] = unsafe { /// MaybeUninit::uninit().assume_init() /// }; /// /// // Dropping a `MaybeUninit` does nothing, so if there is a panic during this loop, /// // we have a memory leak, but there is no memory safety issue. /// for elem in &mut data[..] { /// unsafe { ptr::write(elem.as_mut_ptr(), vec![42]); } /// } /// /// // Everything is initialized. Transmute the array to the /// // initialized type. /// unsafe { mem::transmute::<_, [Vec; 1000]>(data) } /// }; /// /// assert_eq!(&data[0], &[42]); /// # } /// ``` /// /// You can also work with partially initialized arrays, which could /// be found in low-level datastructures. /// /// ``` /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr; /// /// // Create an uninitialized array of `MaybeUninit`. The `assume_init` is /// // safe because the type we are claiming to have initialized here is a /// // bunch of `MaybeUninit`s, which do not require initialization. /// let mut data: [MaybeUninit; 1000] = unsafe { MaybeUninit::uninit().assume_init() }; /// // Count the number of elements we have assigned. /// let mut data_len: usize = 0; /// /// for elem in &mut data[0..500] { /// unsafe { ptr::write(elem.as_mut_ptr(), String::from("hello")); } /// data_len += 1; /// } /// /// // For each item in the array, drop if we allocated it. /// for elem in &mut data[0..data_len] { /// unsafe { ptr::drop_in_place(elem.as_mut_ptr()); } /// } /// # } /// ``` /// /// ## Initializing a struct field-by-field /// /// There is currently no supported way to create a raw pointer or reference /// to a field of a struct inside `MaybeUninit`. That means it is not possible /// to create a struct by calling `MaybeUninit::uninit::()` and then writing /// to its fields. /// /// [ub]: ../../reference/behavior-considered-undefined.html /// /// # Layout /// /// `MaybeUninit` is guaranteed to have the same size, alignment, and ABI as `T`: /// /// ```rust /// # extern crate maybe_uninit; /// # #[cfg(not(derive_copy))] fn main() {} /// # #[cfg(derive_copy)] fn main() { /// use maybe_uninit::MaybeUninit; /// use std::mem::{size_of, align_of}; /// assert_eq!(size_of::>(), size_of::()); /// assert_eq!(align_of::>(), align_of::()); /// # } /// ``` /// /// However remember that a type *containing* a `MaybeUninit` is not necessarily the same /// layout; Rust does not in general guarantee that the fields of a `Foo` have the same order as /// a `Foo` even if `T` and `U` have the same size and alignment. Furthermore because any bit /// value is valid for a `MaybeUninit` the compiler can't apply non-zero/niche-filling /// optimizations, potentially resulting in a larger size: /// /// ```no_run /// # extern crate maybe_uninit; /// # fn main() { /// # use maybe_uninit::MaybeUninit; /// # use std::mem::size_of; /// assert_eq!(size_of::>(), 1); /// assert_eq!(size_of::>>(), 2); /// # } /// ``` /// /// If `T` is FFI-safe, then so is `MaybeUninit`. /// /// While `MaybeUninit` is `#[repr(transparent)]` (indicating it guarantees the same size, /// alignment, and ABI as `T`), this does *not* change any of the previous caveats. `Option` and /// `Option>` may still have different sizes, and types containing a field of type /// `T` may be laid out (and sized) differently than if that field were `MaybeUninit`. /// `MaybeUninit` is a union type, and `#[repr(transparent)]` on unions is unstable (see [the /// tracking issue](https://github.com/rust-lang/rust/issues/60405)). Over time, the exact /// guarantees of `#[repr(transparent)]` on unions may evolve, and `MaybeUninit` may or may not /// remain `#[repr(transparent)]`. That said, `MaybeUninit` will *always* guarantee that it has /// the same size, alignment, and ABI as `T`; it's just that the way `MaybeUninit` implements that /// guarantee may evolve. #[cfg_attr(derive_copy, derive(Copy))] #[cfg_attr(repr_transparent, repr(transparent))] #[cfg_attr(not(repr_transparent), repr(C))] pub struct MaybeUninit { value: ManuallyDrop, } #[cfg(derive_copy)] impl Clone for MaybeUninit { #[inline(always)] fn clone(&self) -> Self { // Not calling `T::clone()`, we cannot know if we are initialized enough for that. *self } } impl MaybeUninit { /// Creates a new `MaybeUninit` initialized with the given value. /// It is safe to call [`assume_init`] on the return value of this function. /// /// Note that dropping a `MaybeUninit` will never call `T`'s drop code. /// It is your responsibility to make sure `T` gets dropped if it got initialized. /// /// [`assume_init`]: #method.assume_init #[inline(always)] pub fn new(val: T) -> MaybeUninit { MaybeUninit { value: ManuallyDrop::new(val) } } /// Creates a new `MaybeUninit` in an uninitialized state. /// /// Note that dropping a `MaybeUninit` will never call `T`'s drop code. /// It is your responsibility to make sure `T` gets dropped if it got initialized. /// /// See the [type-level documentation][type] for some examples. /// /// [type]: union.MaybeUninit.html #[inline(always)] pub fn uninit() -> MaybeUninit { unsafe { MaybeUninit { value: uninitialized() } } } /// Creates a new `MaybeUninit` in an uninitialized state, with the memory being /// filled with `0` bytes. It depends on `T` whether that already makes for /// proper initialization. For example, `MaybeUninit::zeroed()` is initialized, /// but `MaybeUninit<&'static i32>::zeroed()` is not because references must not /// be null. /// /// Note that dropping a `MaybeUninit` will never call `T`'s drop code. /// It is your responsibility to make sure `T` gets dropped if it got initialized. /// /// # Example /// /// Correct usage of this function: initializing a struct with zero, where all /// fields of the struct can hold the bit-pattern 0 as a valid value. /// /// ```rust /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// /// let x = MaybeUninit::<(u8, bool)>::zeroed(); /// let x = unsafe { x.assume_init() }; /// assert_eq!(x, (0, false)); /// # } /// ``` /// /// *Incorrect* usage of this function: initializing a struct with zero, where some fields /// cannot hold 0 as a valid value. /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// /// enum NotZero { One = 1, Two = 2 }; /// /// let x = MaybeUninit::<(u8, NotZero)>::zeroed(); /// let x = unsafe { x.assume_init() }; /// // Inside a pair, we create a `NotZero` that does not have a valid discriminant. /// // This is undefined behavior. /// # } /// ``` #[inline] pub fn zeroed() -> MaybeUninit { let mut u = MaybeUninit::::uninit(); unsafe { ptr::write_bytes(u.as_mut_ptr(), 0u8, 1); } u } /* /// Sets the value of the `MaybeUninit`. This overwrites any previous value /// without dropping it, so be careful not to use this twice unless you want to /// skip running the destructor. For your convenience, this also returns a mutable /// reference to the (now safely initialized) contents of `self`. #[unstable(feature = "maybe_uninit_extra", issue = "53491")] #[inline(always)] pub fn write(&mut self, val: T) -> &mut T { unsafe { self.value = ManuallyDrop::new(val); self.get_mut() } } */ /// Gets a pointer to the contained value. Reading from this pointer or turning it /// into a reference is undefined behavior unless the `MaybeUninit` is initialized. /// Writing to memory that this pointer (non-transitively) points to is undefined behavior /// (except inside an `UnsafeCell`). /// /// # Examples /// /// Correct usage of this method: /// /// ```rust /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr; /// /// let mut x = MaybeUninit::>::uninit(); /// unsafe { ptr::write(x.as_mut_ptr(), vec![0,1,2]); } /// // Create a reference into the `MaybeUninit`. This is okay because we initialized it. /// let x_vec = unsafe { &*x.as_ptr() }; /// assert_eq!(x_vec.len(), 3); /// # } /// ``` /// /// *Incorrect* usage of this method: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// /// let x = MaybeUninit::>::uninit(); /// let x_vec = unsafe { &*x.as_ptr() }; /// // We have created a reference to an uninitialized vector! This is undefined behavior. /// # } /// ``` /// /// (Notice that the rules around references to uninitialized data are not finalized yet, but /// until they are, it is advisable to avoid them.) #[inline(always)] pub fn as_ptr(&self) -> *const T { &*self.value as *const T } /// Gets a mutable pointer to the contained value. Reading from this pointer or turning it /// into a reference is undefined behavior unless the `MaybeUninit` is initialized. /// /// # Examples /// /// Correct usage of this method: /// /// ```rust /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr; /// /// let mut x = MaybeUninit::>::uninit(); /// unsafe { ptr::write(x.as_mut_ptr(), vec![0,1,2]); } /// // Create a reference into the `MaybeUninit>`. /// // This is okay because we initialized it. /// let x_vec = unsafe { &mut *x.as_mut_ptr() }; /// x_vec.push(3); /// assert_eq!(x_vec.len(), 4); /// # } /// ``` /// /// *Incorrect* usage of this method: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// /// let mut x = MaybeUninit::>::uninit(); /// let x_vec = unsafe { &mut *x.as_mut_ptr() }; /// // We have created a reference to an uninitialized vector! This is undefined behavior. /// # } /// ``` /// /// (Notice that the rules around references to uninitialized data are not finalized yet, but /// until they are, it is advisable to avoid them.) #[inline(always)] pub fn as_mut_ptr(&mut self) -> *mut T { &mut *self.value as *mut T } /// Extracts the value from the `MaybeUninit` container. This is a great way /// to ensure that the data will get dropped, because the resulting `T` is /// subject to the usual drop handling. /// /// # Safety /// /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized /// state. Calling this when the content is not yet fully initialized causes immediate undefined /// behavior. The [type-level documentation][inv] contains more information about /// this initialization invariant. /// /// [inv]: #initialization-invariant /// /// # Examples /// /// Correct usage of this method: /// /// ```rust /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// use std::ptr::write; /// /// let mut x = MaybeUninit::::uninit(); /// unsafe { write(x.as_mut_ptr(), true); } /// let x_init = unsafe { x.assume_init() }; /// assert_eq!(x_init, true); /// # } /// ``` /// /// *Incorrect* usage of this method: /// /// ```rust,no_run /// # extern crate maybe_uninit; /// # fn main() { /// use maybe_uninit::MaybeUninit; /// /// let x = MaybeUninit::>::uninit(); /// let x_init = unsafe { x.assume_init() }; /// // `x` had not been initialized yet, so this last line caused undefined behavior. /// # } /// ``` #[inline(always)] pub unsafe fn assume_init(self) -> T { //intrinsics::panic_if_uninhabited::(); ManuallyDrop::into_inner(self.value) } /* /// Reads the value from the `MaybeUninit` container. The resulting `T` is subject /// to the usual drop handling. /// /// Whenever possible, it is preferrable to use [`assume_init`] instead, which /// prevents duplicating the content of the `MaybeUninit`. /// /// # Safety /// /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized /// state. Calling this when the content is not yet fully initialized causes undefined /// behavior. The [type-level documentation][inv] contains more information about /// this initialization invariant. /// /// Moreover, this leaves a copy of the same data behind in the `MaybeUninit`. When using /// multiple copies of the data (by calling `read` multiple times, or first /// calling `read` and then [`assume_init`]), it is your responsibility /// to ensure that that data may indeed be duplicated. /// /// [inv]: #initialization-invariant /// [`assume_init`]: #method.assume_init /// /// # Examples /// /// Correct usage of this method: /// /// ```rust /// #![feature(maybe_uninit_extra)] /// use std::mem::MaybeUninit; /// /// let mut x = MaybeUninit::::uninit(); /// x.write(13); /// let x1 = unsafe { x.read() }; /// // `u32` is `Copy`, so we may read multiple times. /// let x2 = unsafe { x.read() }; /// assert_eq!(x1, x2); /// /// let mut x = MaybeUninit::>>::uninit(); /// x.write(None); /// let x1 = unsafe { x.read() }; /// // Duplicating a `None` value is okay, so we may read multiple times. /// let x2 = unsafe { x.read() }; /// assert_eq!(x1, x2); /// ``` /// /// *Incorrect* usage of this method: /// /// ```rust,no_run /// #![feature(maybe_uninit_extra)] /// use std::mem::MaybeUninit; /// /// let mut x = MaybeUninit::>>::uninit(); /// x.write(Some(vec![0,1,2])); /// let x1 = unsafe { x.read() }; /// let x2 = unsafe { x.read() }; /// // We now created two copies of the same vector, leading to a double-free when /// // they both get dropped! /// ``` #[unstable(feature = "maybe_uninit_extra", issue = "53491")] #[inline(always)] pub unsafe fn read(&self) -> T { intrinsics::panic_if_uninhabited::(); self.as_ptr().read() } /// Gets a reference to the contained value. /// /// # Safety /// /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized /// state. Calling this when the content is not yet fully initialized causes undefined /// behavior. #[unstable(feature = "maybe_uninit_ref", issue = "53491")] #[inline(always)] pub unsafe fn get_ref(&self) -> &T { &*self.value } /// Gets a mutable reference to the contained value. /// /// # Safety /// /// It is up to the caller to guarantee that the `MaybeUninit` really is in an initialized /// state. Calling this when the content is not yet fully initialized causes undefined /// behavior. // FIXME(#53491): We currently rely on the above being incorrect, i.e., we have references // to uninitialized data (e.g., in `libcore/fmt/float.rs`). We should make // a final decision about the rules before stabilization. #[unstable(feature = "maybe_uninit_ref", issue = "53491")] #[inline(always)] pub unsafe fn get_mut(&mut self) -> &mut T { &mut *self.value } /// Gets a pointer to the first element of the array. #[unstable(feature = "maybe_uninit_slice", issue = "53491")] #[inline(always)] pub fn first_ptr(this: &[MaybeUninit]) -> *const T { this as *const [MaybeUninit] as *const T } /// Gets a mutable pointer to the first element of the array. #[unstable(feature = "maybe_uninit_slice", issue = "53491")] #[inline(always)] pub fn first_ptr_mut(this: &mut [MaybeUninit]) -> *mut T { this as *mut [MaybeUninit] as *mut T }*/ } maybe-uninit-2.0.0/tests/doesnt_drop.rs010066400017500001750000000013651351136461400163760ustar0000000000000000extern crate maybe_uninit; use maybe_uninit::MaybeUninit; use std::cell::Cell; struct DecrementOnDrop<'a>(&'a Cell); impl<'a> DecrementOnDrop<'a> { pub fn new(ref_:&'a Cell) -> Self { ref_.set(1); DecrementOnDrop(ref_) } } impl<'a> Clone for DecrementOnDrop<'a> { fn clone(&self) -> Self { self.0.set(self.0.get() + 1); DecrementOnDrop(self.0) } } impl<'a> Drop for DecrementOnDrop<'a>{ fn drop(&mut self) { self.0.set(self.0.get() - 1); } } #[test] fn doesnt_drop(){ let count = Cell::new(0); let arc = DecrementOnDrop::new(&count); let maybe = MaybeUninit::new(arc.clone()); assert_eq!(count.get(), 2); drop(maybe); assert_eq!(count.get(), 2); } maybe-uninit-2.0.0/.cargo_vcs_info.json0000644000000001120000000000000134650ustar00{ "git": { "sha1": "758af09f0823415ec6431831c5f28bde98da4c29" } }