From 4285ce08149bf7a2adfefbfd023d1fc50ccc4c46 Mon Sep 17 00:00:00 2001 From: missing Date: Mon, 26 Dec 2022 11:39:50 -0600 Subject: [PATCH] polish for crates.io --- .gitignore | 13 ---- Cargo.toml | 5 ++ LICENSE | 17 ----- LICENSE-APACHE | 201 +++++++++++++++++++++++++++++++++++++++++++++++++ LICENSE-MIT | 17 +++++ src/bench.rs | 10 +-- src/impls.rs | 62 +++++++-------- src/iter.rs | 64 +++++++--------- src/lib.rs | 84 +++++++++------------ src/ptr_ext.rs | 2 - src/test.rs | 14 +++- 11 files changed, 334 insertions(+), 155 deletions(-) delete mode 100644 LICENSE create mode 100644 LICENSE-APACHE create mode 100644 LICENSE-MIT diff --git a/.gitignore b/.gitignore index 61ae5aa..2c96eb1 100644 --- a/.gitignore +++ b/.gitignore @@ -1,15 +1,2 @@ -# ---> Rust -# Generated by Cargo -# will have compiled files and executables -debug/ target/ - -# Remove Cargo.lock from gitignore if creating an executable, leave it for libraries -# More information here https://doc.rust-lang.org/cargo/guide/cargo-toml-vs-cargo-lock.html Cargo.lock - -# These are backup files generated by rustfmt -**/*.rs.bk - -# MSVC Windows builds of rustc generate these, which store debugging information -*.pdb diff --git a/Cargo.toml b/Cargo.toml index db38f30..6bea64d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -2,6 +2,11 @@ name = "dyn_vec" version = "0.1.0" edition = "2021" +description = "A Vec" +repository = "https://git.karx.xyz/missing/dyn_vec" +license = "MIT OR Apache-2.0" +keywords = ["vec", "unsized"] +categories = ["data-structures", "memory-management", "rust-patterns"] # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html diff --git a/LICENSE b/LICENSE deleted file mode 100644 index d5075a3..0000000 --- a/LICENSE +++ /dev/null @@ -1,17 +0,0 @@ -Permission is hereby granted, without written agreement and without -license or royalty fees, to use, copy, modify, and distribute this -software and its documentation for any purpose, provided that the -above copyright notice and the following two paragraphs appear in -all copies of this software. - -IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE TO ANY PARTY FOR -DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES -ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN -IF THE COPYRIGHT HOLDER HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH -DAMAGE. - -THE COPYRIGHT HOLDER SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, -BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND -FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE PROVIDED HEREUNDER IS -ON AN "AS IS" BASIS, AND THE COPYRIGHT HOLDER HAS NO OBLIGATION TO -PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS. diff --git a/LICENSE-APACHE b/LICENSE-APACHE new file mode 100644 index 0000000..f49a4e1 --- /dev/null +++ b/LICENSE-APACHE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. \ No newline at end of file diff --git a/LICENSE-MIT b/LICENSE-MIT new file mode 100644 index 0000000..7215f69 --- /dev/null +++ b/LICENSE-MIT @@ -0,0 +1,17 @@ +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. \ No newline at end of file diff --git a/src/bench.rs b/src/bench.rs index bc091a9..5b47d8f 100644 --- a/src/bench.rs +++ b/src/bench.rs @@ -5,12 +5,12 @@ use test::{black_box, Bencher}; extern crate test; use super::DynVec; -use std::{fmt::Debug, mem, vec::Vec as StdVec}; +use std::{fmt::Debug, mem, vec::Vec}; #[bench] #[cfg_attr(miri, ignore)] fn std_push(b: &mut Bencher) { - let mut vec = StdVec::new(); + let mut vec = Vec::new(); b.iter(|| vec.push(black_box(5))); @@ -30,7 +30,7 @@ fn dyn_push(b: &mut Bencher) { #[bench] #[cfg_attr(miri, ignore)] fn std_push_box(b: &mut Bencher) { - let mut vec = StdVec::new(); + let mut vec = Vec::new(); b.iter(|| vec.push(black_box(Box::new(5) as Box))); @@ -72,11 +72,11 @@ fn dyn_push_then_unsize(b: &mut Bencher) { #[bench] #[cfg_attr(miri, ignore)] fn box_forget(b: &mut Bencher) { - b.iter(|| mem::forget(black_box(Box::new(5)))); + b.iter(|| mem::forget(black_box(Box::new(black_box(5))))); } #[bench] #[cfg_attr(miri, ignore)] fn box_dealloc(b: &mut Bencher) { - b.iter(|| drop(black_box(Box::new(5)))); + b.iter(|| drop(black_box(Box::new(black_box(5))))); } diff --git a/src/impls.rs b/src/impls.rs index 3f868cb..ba813e8 100644 --- a/src/impls.rs +++ b/src/impls.rs @@ -8,11 +8,11 @@ use std::{ ops::{Deref, DerefMut}, ptr::NonNull, slice, - vec::Vec as StdVec, + vec::Vec, }; -#[cfg(feature = "unstable")] -use std::ops::CoerceUnsized; +// #[cfg(any(doc, feature = "unstable"))] +// use std::ops::CoerceUnsized; impl Default for DynVec { fn default() -> Self { @@ -44,7 +44,7 @@ impl, U: ?Sized> PartialEq> for DynVec { impl Eq for DynVec {} // DynVec == [U] -impl, U> PartialEq<[U]> for DynVec { +impl + ?Sized, U> PartialEq<[U]> for DynVec { fn eq(&self, other: &[U]) -> bool { if self.len != other.len() { return false; @@ -59,83 +59,83 @@ impl, U> PartialEq<[U]> for DynVec { } // [U] == DynVec -impl, U> PartialEq> for [U] { +impl + ?Sized, U> PartialEq> for [U] { fn eq(&self, other: &DynVec) -> bool { other == self } } // DynVec == &[U] -impl, U> PartialEq<&[U]> for DynVec { +impl + ?Sized, U> PartialEq<&[U]> for DynVec { fn eq(&self, other: &&[U]) -> bool { *self == **other } } // &[U] == DynVec -impl, U> PartialEq> for &[U] { +impl + ?Sized, U> PartialEq> for &[U] { fn eq(&self, other: &DynVec) -> bool { *other == **self } } // DynVec == &mut [U] -impl, U> PartialEq<&mut [U]> for DynVec { +impl + ?Sized, U> PartialEq<&mut [U]> for DynVec { fn eq(&self, other: &&mut [U]) -> bool { *self == **other } } // &mut [U] == DynVec -impl, U> PartialEq> for &mut [U] { +impl + ?Sized, U> PartialEq> for &mut [U] { fn eq(&self, other: &DynVec) -> bool { *other == **self } } // DynVec == [U; N] -impl, U, const N: usize> PartialEq<[U; N]> for DynVec { +impl + ?Sized, U, const N: usize> PartialEq<[U; N]> for DynVec { fn eq(&self, other: &[U; N]) -> bool { *self == other[..] } } // [U; N] == DynVec -impl, U, const N: usize> PartialEq> for [U; N] { +impl + ?Sized, U, const N: usize> PartialEq> for [U; N] { fn eq(&self, other: &DynVec) -> bool { *other == self[..] } } // DynVec == &[U; N] -impl, U, const N: usize> PartialEq<&[U; N]> for DynVec { +impl + ?Sized, U, const N: usize> PartialEq<&[U; N]> for DynVec { fn eq(&self, other: &&[U; N]) -> bool { *self == other[..] } } // &[U; N] == DynVec -impl, U, const N: usize> PartialEq> for &[U; N] { +impl + ?Sized, U, const N: usize> PartialEq> for &[U; N] { fn eq(&self, other: &DynVec) -> bool { *other == self[..] } } // DynVec == &mut [U; N] -impl, U, const N: usize> PartialEq<&mut [U; N]> for DynVec { +impl + ?Sized, U, const N: usize> PartialEq<&mut [U; N]> for DynVec { fn eq(&self, other: &&mut [U; N]) -> bool { *self == other[..] } } // &mut [U; N] == DynVec -impl, U, const N: usize> PartialEq> for &mut [U; N] { +impl + ?Sized, U, const N: usize> PartialEq> for &mut [U; N] { fn eq(&self, other: &DynVec) -> bool { *other == self[..] } } -#[cfg(not(feature = "unstable"))] +// #[cfg(not(feature = "unstable"))] impl Extend> for DynVec { fn extend>>(&mut self, iter: I) { for item in iter { @@ -145,18 +145,18 @@ impl Extend> for DynVec { } } -#[cfg(feature = "unstable")] -impl Extend> for DynVec -where - Box: CoerceUnsized>, -{ - fn extend>>(&mut self, iter: I) { - for item in iter { - // TODO: optmize - self.push_box(item); - } - } -} +// #[cfg(feature = "unstable")] +// impl Extend> for DynVec +// where +// Box: CoerceUnsized>, +// { +// fn extend>>(&mut self, iter: I) { +// for item in iter { +// // TODO: optmize +// self.push_box(item); +// } +// } +// } impl Deref for DynVec { type Target = [T]; @@ -183,8 +183,8 @@ impl DerefMut for DynVec { unsafe impl Send for DynVec {} unsafe impl Sync for DynVec {} -impl From> for DynVec { - fn from(std_vec: StdVec) -> Self { +impl From> for DynVec { + fn from(std_vec: Vec) -> Self { let mut vec = Self::new(); let new_cap = (size_of::() + size_of::>()) * std_vec.len(); unsafe { @@ -199,7 +199,7 @@ impl From> for DynVec { } } -impl From> for StdVec { +impl From> for Vec { fn from(mut vec: DynVec) -> Self { let mut std_vec = Self::with_capacity(vec.len); diff --git a/src/iter.rs b/src/iter.rs index 3b92023..7858e07 100644 --- a/src/iter.rs +++ b/src/iter.rs @@ -1,6 +1,6 @@ //! Iteration. -use std::{marker::PhantomData, mem, ptr::NonNull}; +use std::{marker::PhantomData, mem::ManuallyDrop, ptr::NonNull}; use crate::{ptr_ext::PtrExt, DynVec}; @@ -13,7 +13,7 @@ unsafe impl Send for BaseIter {} unsafe impl Sync for BaseIter {} impl BaseIter { - fn new(vec: &DynVec) -> Self { + pub(crate) fn new(vec: &DynVec) -> Self { Self { ptr: vec.get_ptr_to_extra(vec.len).cast(), ptr_back: vec.get_ptr_to_extra(0).cast(), @@ -47,6 +47,16 @@ impl DoubleEndedIterator for BaseIter { } // By-ref iteration +impl DynVec { + /// Iterates over the vector by-ref. + pub fn iter(&self) -> Iter { + Iter { + base: BaseIter::new(self), + _phantom: PhantomData, + } + } +} + impl<'a, T: ?Sized> IntoIterator for &'a DynVec { type Item = &'a T; @@ -66,16 +76,6 @@ pub struct Iter<'a, T: ?Sized> { unsafe impl<'a, T: Send> Send for Iter<'a, T> {} unsafe impl<'a, T: Sync> Sync for Iter<'a, T> {} -impl<'a, T: ?Sized> Iter<'a, T> { - /// Creates a new by-ref iterator over a [`DynVec`]. usually seen as [`DynVec::iter`]. - pub fn new(vec: &'a DynVec) -> Self { - Self { - base: BaseIter::new(vec), - _phantom: PhantomData, - } - } -} - impl<'a, T: ?Sized> Iterator for Iter<'a, T> { type Item = &'a T; @@ -91,6 +91,16 @@ impl<'a, T: ?Sized> DoubleEndedIterator for Iter<'a, T> { } // By-mut iteration +impl DynVec { + /// Iterates over the vector by-mut. + pub fn iter_mut(&mut self) -> IterMut { + IterMut { + base: BaseIter::new(self), + _phantom: PhantomData, + } + } +} + impl<'a, T: ?Sized> IntoIterator for &'a mut DynVec { type Item = &'a mut T; @@ -111,16 +121,6 @@ pub struct IterMut<'a, T: ?Sized> { unsafe impl<'a, T: Send> Send for IterMut<'a, T> {} unsafe impl<'a, T: Sync> Sync for IterMut<'a, T> {} -impl<'a, T: ?Sized> IterMut<'a, T> { - /// Creates a new by-mut iterator over a [`DynVec`]. usually seen as [`DynVec::iter_mut`]. - pub fn new(vec: &'a mut DynVec) -> Self { - Self { - base: BaseIter::new(vec), - _phantom: PhantomData, - } - } -} - impl<'a, T: ?Sized> Iterator for IterMut<'a, T> { type Item = &'a mut T; @@ -142,7 +142,12 @@ impl IntoIterator for DynVec { type IntoIter = IntoIter; fn into_iter(self) -> Self::IntoIter { - IntoIter::new(self) + let this = ManuallyDrop::new(self); + IntoIter { + ptr: this.ptr, + capacity: this.capacity, + base: BaseIter::new(&this), + } } } @@ -157,19 +162,6 @@ pub struct IntoIter { unsafe impl Send for IntoIter {} unsafe impl Sync for IntoIter {} -impl IntoIter { - /// Creates a new by-value iterator over a [`DynVec`]. usually seen as [`DynVec::into_iter`]. - pub fn new(vec: DynVec) -> Self { - let this = Self { - ptr: vec.ptr, - capacity: vec.capacity, - base: BaseIter::new(&vec), - }; - mem::forget(vec); - this - } -} - impl Iterator for IntoIter { type Item = Box; diff --git a/src/lib.rs b/src/lib.rs index bb2d115..553756b 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -//! # A [`Vec`] +//! # A `Vec` //! //! [`DynVec`], a dynamic length collection of unsized elements, akin to [`std::vec::Vec`]. //! @@ -8,7 +8,7 @@ //! //! ``` //! # use std::fmt::Debug; -//! # use dyn_vec::prelude::*; +//! # use dyn_vec::DynVec; //! let vec: DynVec = DynVec::new(); //! # assert_eq!(format!("{:?}", vec), "[]"); //! ``` @@ -16,7 +16,7 @@ //! or with the [`dyn_vec!`] macro: //! //! ``` -//! # use dyn_vec::prelude::*; +//! # use dyn_vec::{dyn_vec, DynVec}; //! # use std::fmt::Debug; //! let vec: DynVec = dyn_vec![1, 2, 3]; //! // check the docs for `dyn_vec!` for more info on this syntax @@ -36,7 +36,7 @@ //! A vector can be pushed to with [`DynVec::push`]: //! //! ``` -//! # use dyn_vec::prelude::*; +//! # use dyn_vec::{dyn_vec, DynVec}; //! let mut vec: DynVec = dyn_vec![]; //! vec.push(1); //! vec.push(2); @@ -44,10 +44,10 @@ //! # assert_eq!(format!("{:?}", vec), "[1, 2, 3]"); //! ``` //! -//! ...and with [`push_box`] and [`push_unsize`] ([`push_unsize_stable`] without the `"unstable"` feature): +//! ...and with [`push_box`] and [`push_unsize`] ([`push_unsize_stable`] without the `"unstable"`feature): //! //! ``` -//! # use dyn_vec::prelude::*; +//! # use dyn_vec::{dyn_vec, DynVec}; //! # use std::fmt::Debug; //! let mut vec: DynVec = dyn_vec![]; //! vec.push_box(Box::new(1)); @@ -64,7 +64,7 @@ //! Finally, a vector can be [`unsize`]d to another vector ([`unsize_stable`] on stable): //! //! ``` -//! # use dyn_vec::prelude::*; +//! # use dyn_vec::{dyn_vec, DynVec}; //! # use std::fmt::Debug; //! let vec: DynVec = dyn_vec![1, 2, 3]; //! // vec.push_unsize_stable("foo", |v| v as _); // not yet... @@ -77,20 +77,20 @@ //! //! # Stability //! -//! This crate is currently stable, but lacks some functionality. To enable this functionality, use the `"unstable"` crate feature, which depends on the following nightly features: -//! - [`#![feature(coerce_unsized)]`](https://github.com/rust-lang/rust/issues/27732) +//! This crate is currently stable, but lacks some functionality. To enable this functionality, use +//! the `"unstable"` crate feature, which depends on the following nightly features: +//! - [`#![feature(coerce_unsized)]`](https://github.com/rust-lang/rust/issues/18598) //! -//! and enables the following functionality (note: these links are probably broken): +//! and enables the following functionality: //! - [`DynVec::push_unsize`] //! - [`DynVec::unsize`] //! - [`DynVec::extend_unsize`] //! -//! In addition, the `"unstable"` feature also enables dependance on the following nightly features: +//! In addition, the `"unstable"` feature also enables dependence on the following nightly features +//! in order to conform to [strict provenance](https://github.com/rust-lang/rust/issues/95228): //! - [`#![feature(set_ptr_value)]`](https://github.com/rust-lang/rust/issues/75091) //! - [`#![feature(pointer_byte_offsets)]`](https://github.com/rust-lang/rust/issues/96283) //! -//! in order to conform to [strict provenance](https://github.com/rust-lang/rust/issues/95228). -//! //! # Data Layout //! //! ```text @@ -111,7 +111,7 @@ //! │ │ └──────────────────────────────────────────┘ │ │ //! │ └─────────────────────────────────────────────────────────┘ │ //! │ │ -//! └─ aligned to align_of::<*const T>() also aligned to *const T ─┘ +//! └─────────────── aligned to align_of::<*const T>() ──────────────┘ //! ``` //! //! [`DynVec`]: DynVec @@ -130,6 +130,7 @@ feature(set_ptr_value), feature(pointer_byte_offsets) )] +#![cfg_attr(doc, feature(doc_cfg))] #![warn(missing_docs)] #![warn(clippy::pedantic)] #![warn(clippy::nursery)] @@ -150,12 +151,6 @@ use ptr_ext::{ConstPtrExt, MutPtrExt, PtrExt}; pub use iter::*; -// TODO: maybe remove this? Its not that many imports -/// Prelude, suitable for glob imports. -pub mod prelude { - pub use super::{dyn_vec, DynVec}; -} - use core::panic; use std::{ alloc::{alloc, dealloc, handle_alloc_error, Layout}, @@ -167,7 +162,7 @@ use std::{ slice, }; -#[cfg(feature = "unstable")] +#[cfg(any(doc, feature = "unstable"))] use std::ops::CoerceUnsized; type Coercer = for<'a> fn(&'a T) -> &'a U; @@ -225,7 +220,7 @@ impl DynVec { Self::with_capacity_for::(cap) } - /// Creates a new vector with the given capacity, measured in bytes.\ + /// Creates a new vector with the given capacity, measured in bytes. pub fn with_capacity_bytes(cap: usize) -> Self { let mut vec = Self::new(); unsafe { @@ -295,7 +290,7 @@ impl DynVec { unsafe { self.push_raw(&*ManuallyDrop::new(v)) } } - /// Appends an (possibly unsized) boxed element to the end of the vector. + /// Appends a (possibly unsized) boxed element to the end of the vector. pub fn push_box(&mut self, v: Box) { let ptr = Box::into_raw(v); unsafe { @@ -306,7 +301,8 @@ impl DynVec { } /// Appends a sized element of type `U` to the end of the vector, given that it can be `CoerceUnsized` to a `T`. - #[cfg(feature = "unstable")] + #[cfg(any(doc, feature = "unstable"))] + #[cfg_attr(doc, doc(cfg(feature = "unstable")))] pub fn push_unsize(&mut self, v: U) where for<'a> &'a U: CoerceUnsized<&'a T>, @@ -511,7 +507,7 @@ impl DynVec { } /// Returns a mutable pointer to the end of the last element of the vector. - pub fn as_end_ptr_mut(&mut self) -> *const u8 { + pub fn as_end_ptr_mut(&mut self) -> *mut u8 { self.end_ptr.as_ptr() } @@ -522,18 +518,9 @@ impl DynVec { self.as_end_ptr() as usize - self.as_ptr() as usize } - /// Iterates over the vector by-ref. - pub fn iter(&self) -> Iter { - Iter::new(self) - } - - /// Iterates over the vector by-mut. - pub fn iter_mut(&mut self) -> IterMut { - IterMut::new(self) - } - /// Converts a `DynVec` into a `DynVec`, given that `T` can be `CoerceUnsized` into `U`. - #[cfg(feature = "unstable")] + #[cfg(any(doc, feature = "unstable"))] + #[cfg_attr(doc, doc(cfg(feature = "unstable")))] pub fn unsize(self) -> DynVec where for<'a> &'a T: CoerceUnsized<&'a U>, @@ -599,7 +586,8 @@ impl DynVec { /// Extends this vector with an iterator. /// /// Similar to [`Extend::extend`], but seperate to prevent conflicting implementations. - #[cfg(feature = "unstable")] + #[cfg(any(doc, feature = "unstable"))] + #[cfg_attr(doc, doc(cfg(feature = "unstable")))] pub fn extend_unsize>(&mut self, iter: I) where for<'a> &'a U: CoerceUnsized<&'a T>, @@ -750,13 +738,12 @@ impl Index for DynVec { #[track_caller] fn index(&self, index: usize) -> &Self::Output { - match self.get(index) { - Some(v) => v, - None => panic!( + self.get(index).unwrap_or_else(|| { + panic!( "index out of bounds: the len is {} but the index is {}", self.len, index - ), - } + ) + }) } } @@ -764,13 +751,12 @@ impl IndexMut for DynVec { #[track_caller] fn index_mut(&mut self, index: usize) -> &mut Self::Output { let len = self.len; - match self.get_mut(index) { - Some(v) => v, - None => panic!( + self.get_mut(index).unwrap_or_else(|| { + panic!( "index out of bounds: the len is {} but the index is {}", len, index - ), - } + ) + }) } } @@ -779,7 +765,7 @@ impl IndexMut for DynVec { /// # Examples /// /// ``` -/// # use dyn_vec::prelude::*; +/// # use dyn_vec::{dyn_vec, DynVec}; /// # use std::fmt::Debug; /// let vec1: DynVec = dyn_vec![1, 2, 3]; /// let vec2: DynVec = dyn_vec![box: @@ -801,7 +787,7 @@ macro_rules! dyn_vec { }}; (unsized: $($elem:expr),+ $(,)?) => {{ let mut vec = $crate::DynVec::new(); - // TODO: when stuff stabalizes change this + // TODO: when stuff stabilizes change this $(vec.push_unsize_stable($elem, |v| v as _);)+ vec }}; diff --git a/src/ptr_ext.rs b/src/ptr_ext.rs index 2eddc1d..75419a6 100644 --- a/src/ptr_ext.rs +++ b/src/ptr_ext.rs @@ -62,7 +62,6 @@ impl PtrExt for *const T { #[cfg(not(feature = "unstable"))] { let mut this = self; - // TODO: aaaaand this is cheating. sorry yall, cant do this until `set_ptr_value` lands unsafe { *addr_of_mut!(this).cast() = addr } this } @@ -121,7 +120,6 @@ impl PtrExt for *mut T { #[cfg(not(feature = "unstable"))] { let mut this = self; - // TODO: aaaaand this is cheating. sorry yall, cant do this until `set_ptr_value` lands unsafe { *addr_of_mut!(this).cast() = addr } this } diff --git a/src/test.rs b/src/test.rs index 8b10f52..141de4b 100644 --- a/src/test.rs +++ b/src/test.rs @@ -1,8 +1,18 @@ //! Always use `cargo miri test --all-features`, and never just `cargo test`. +#[cfg(all(miri, not(feature = "unstable")))] +#[test] +#[allow(warnings)] +fn aaaaaaaaaa_first_alphabetical() { + let you_should_specify_dash_dash_all_features = std::ptr::null::<()>(); + unsafe { + *you_should_specify_dash_dash_all_features; + } +} + use rand::{thread_rng, Rng}; -use super::prelude::*; +use super::{dyn_vec, DynVec}; use std::{ any::Any, fmt::Debug, @@ -11,7 +21,7 @@ use std::{ trait DebugExt: Debug { fn debug(&self) -> String { - format!("{:?}", self) + format!("{self:?}") } }