From 0f4ee301cee247d4033ab6056b8752d0ee71d654 Mon Sep 17 00:00:00 2001 From: Joel Galenson Date: Wed, 19 May 2021 17:27:31 -0700 Subject: Upgrade rust/crates/tinyvec to 1.2.0 Test: make Change-Id: Icb69d21bb8a873d0b5d5805b06c0836a4f70c178 --- .cargo_vcs_info.json | 2 +- .gitignore | 4 +- CHANGELOG.md | 6 ++ Cargo.toml | 2 +- Cargo.toml.orig | 2 +- LICENSE-APACHE.md | 267 ++++++++++++++++++++++++++++++++++++++------------- METADATA | 8 +- TEST_MAPPING | 11 ++- src/arrayvec.rs | 145 +++++++++++++++++++++++++--- src/slicevec.rs | 72 ++++++++++++-- src/tinyvec.rs | 89 ++++++++++++----- tests/arrayvec.rs | 29 ++++++ tests/tinyvec.rs | 9 ++ 13 files changed, 528 insertions(+), 118 deletions(-) diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index 974ca7e..d6de403 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,5 @@ { "git": { - "sha1": "b2b3e0c7eb38ff288d32726594d32a90d0e684fc" + "sha1": "b6313725a26509d574ccf72885bc9c85fc4f476b" } } diff --git a/.gitignore b/.gitignore index 96ef6c0..e85ef84 100644 --- a/.gitignore +++ b/.gitignore @@ -1,2 +1,2 @@ -/target -Cargo.lock +/target +Cargo.lock diff --git a/CHANGELOG.md b/CHANGELOG.md index 6baa057..8cc2ad7 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,11 @@ # Changelog +## 1.2.0 + +* [Cryptjar](https://github.com/Cryptjar) removed the `A:Array` bound on the struct of `ArrayVec`, + and added the `from_array_empty` method, which is a `const fn` constructor + [pr 141](https://github.com/Lokathor/tinyvec/pull/141). + ## 1.1.1 * [saethlin](https://github.com/saethlin) contributed many PRs ( diff --git a/Cargo.toml b/Cargo.toml index c7d90dd..905979a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ [package] edition = "2018" name = "tinyvec" -version = "1.1.1" +version = "1.2.0" authors = ["Lokathor "] description = "`tinyvec` provides 100% safe vec-like data structures." keywords = ["vec", "no_std", "no-std"] diff --git a/Cargo.toml.orig b/Cargo.toml.orig index ea42ed8..2652d09 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,7 +1,7 @@ [package] name = "tinyvec" description = "`tinyvec` provides 100% safe vec-like data structures." -version = "1.1.1" +version = "1.2.0" authors = ["Lokathor "] edition = "2018" license = "Zlib OR Apache-2.0 OR MIT" diff --git a/LICENSE-APACHE.md b/LICENSE-APACHE.md index 92b19fb..75b5248 100644 --- a/LICENSE-APACHE.md +++ b/LICENSE-APACHE.md @@ -1,67 +1,202 @@ -Apache License -Version 2.0, January 2004 -http://www.apache.org/licenses/ -TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION - -1. Definitions. - -"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. - -"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. - -"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. - -"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. - -"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. - -"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. - -"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). - -"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. - -"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." - -"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. - -2. Grant of Copyright License. - -Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. - -3. Grant of Patent License. - -Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. - -4. Redistribution. - -You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: - -You must give any other recipients of the Work or Derivative Works a copy of this License; and -You must cause any modified files to carry prominent notices stating that You changed the files; and -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 -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 + 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. diff --git a/METADATA b/METADATA index 32fb288..e240ffb 100644 --- a/METADATA +++ b/METADATA @@ -7,13 +7,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/tinyvec/tinyvec-1.1.1.crate" + value: "https://static.crates.io/crates/tinyvec/tinyvec-1.2.0.crate" } - version: "1.1.1" + version: "1.2.0" license_type: NOTICE last_upgrade_date { year: 2021 - month: 2 - day: 9 + month: 5 + day: 19 } } diff --git a/TEST_MAPPING b/TEST_MAPPING index ef16d49..bf91080 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -1,14 +1,23 @@ // Generated by update_crate_tests.py for tests that depend on this crate. { "presubmit": [ + { + "name": "doh_unit_test" + }, { "name": "quiche_device_test_src_lib" }, + { + "name": "unicode-normalization_device_test_src_lib" + }, { "name": "url_device_test_src_lib" }, { - "name": "unicode-normalization_device_test_src_lib" + "name": "url_device_test_tests_data" + }, + { + "name": "url_device_test_tests_unit" } ] } diff --git a/src/arrayvec.rs b/src/arrayvec.rs index 55e67db..ba351c1 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -1,5 +1,5 @@ use super::*; -use core::convert::TryInto; +use core::convert::{TryFrom, TryInto}; #[cfg(feature = "serde")] use core::marker::PhantomData; @@ -96,10 +96,13 @@ macro_rules! array_vec { /// /// let more_ints = ArrayVec::from_array_len([5, 6, 7, 8], 2); /// assert_eq!(more_ints.len(), 2); +/// +/// let no_ints: ArrayVec<[u8; 5]> = ArrayVec::from_array_empty([1, 2, 3, 4, 5]); +/// assert_eq!(no_ints.len(), 0); /// ``` #[repr(C)] #[derive(Clone, Copy)] -pub struct ArrayVec { +pub struct ArrayVec { len: u16, pub(crate) data: A, } @@ -954,6 +957,37 @@ impl ArrayVec { } } +impl ArrayVec { + /// Wraps up an array as a new empty `ArrayVec`. + /// + /// If you want to simply use the full array, use `from` instead. + /// + /// ## Examples + /// + /// This method in particular allows to create values for statics: + /// + /// ```rust + /// # use tinyvec::ArrayVec; + /// static DATA: ArrayVec<[u8; 5]> = ArrayVec::from_array_empty([0; 5]); + /// assert_eq!(DATA.len(), 0); + /// ``` + /// + /// But of course it is just an normal empty `ArrayVec`: + /// + /// ```rust + /// # use tinyvec::ArrayVec; + /// let mut data = ArrayVec::from_array_empty([1, 2, 3, 4]); + /// assert_eq!(&data[..], &[]); + /// data.push(42); + /// assert_eq!(&data[..], &[42]); + /// ``` + #[inline] + #[must_use] + pub const fn from_array_empty(data: A) -> Self { + Self { data, len: 0 } + } +} + #[cfg(feature = "grab_spare_slice")] impl ArrayVec { /// Obtain the shared slice of the array _after_ the active memory. @@ -1190,6 +1224,41 @@ impl From for ArrayVec { } } +/// The error type returned when a conversion from a slice to an [`ArrayVec`] +/// fails. +#[derive(Debug, Copy, Clone)] +pub struct TryFromSliceError(()); + +impl TryFrom<&'_ [T]> for ArrayVec +where + T: Clone + Default, + A: Array, +{ + type Error = TryFromSliceError; + + #[inline] + #[must_use] + /// The output has a length equal to that of the slice, with the same capacity + /// as `A`. + fn try_from(slice: &[T]) -> Result { + if slice.len() > A::CAPACITY { + Err(TryFromSliceError(())) + } else { + let mut arr = ArrayVec::new(); + // We do not use ArrayVec::extend_from_slice, because it looks like LLVM + // fails to deduplicate all the length-checking logic between the + // above if and the contents of that method, thus producing much + // slower code. Unlike many of the other optimizations in this + // crate, this one is worth keeping an eye on. I see no reason, for + // any element type, that these should produce different code. But + // they do. (rustc 1.51.0) + arr.set_len(slice.len()); + arr.as_mut_slice().clone_from_slice(slice); + Ok(arr) + } + } +} + impl FromIterator for ArrayVec { #[inline] #[must_use] @@ -1420,12 +1489,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Binary::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1437,12 +1512,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Debug::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1454,12 +1535,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Display::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1471,12 +1558,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1488,12 +1581,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1505,12 +1604,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Octal::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1522,12 +1627,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Pointer::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1539,12 +1650,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1556,12 +1673,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } diff --git a/src/slicevec.rs b/src/slicevec.rs index 0ba8128..11664e1 100644 --- a/src/slicevec.rs +++ b/src/slicevec.rs @@ -879,12 +879,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Binary::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -896,12 +902,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Debug::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -913,12 +925,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Display::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -930,12 +948,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -947,12 +971,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -964,12 +994,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Octal::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -981,12 +1017,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Pointer::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -998,12 +1040,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1015,12 +1063,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } diff --git a/src/tinyvec.rs b/src/tinyvec.rs index c578ccb..8b058a4 100644 --- a/src/tinyvec.rs +++ b/src/tinyvec.rs @@ -3,6 +3,7 @@ use super::*; use alloc::vec::{self, Vec}; +use core::convert::TryFrom; use tinyvec_macros::impl_mirrored; #[cfg(feature = "serde")] @@ -1114,20 +1115,10 @@ where #[inline] #[must_use] fn from(slice: &[T]) -> Self { - if slice.len() > A::CAPACITY { - TinyVec::Heap(slice.into()) - } else { - let mut arr = ArrayVec::new(); - // We do not use ArrayVec::extend_from_slice, because it looks like LLVM - // fails to deduplicate all the length-checking logic between the - // above if and the contents of that method, thus producing much - // slower code. Unlike many of the other optimizations in this - // crate, this one is worth keeping an eye on. I see no reason, for - // any element type, that these should produce different code. But - // they do. (rustc 1.51.0) - arr.set_len(slice.len()); - arr.as_mut_slice().clone_from_slice(slice); + if let Ok(arr) = ArrayVec::try_from(slice) { TinyVec::Inline(arr) + } else { + TinyVec::Heap(slice.into()) } } } @@ -1318,12 +1309,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Binary::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1335,12 +1332,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Debug::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1352,12 +1355,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Display::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1369,12 +1378,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1386,12 +1401,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } LowerHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1403,12 +1424,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Octal::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1420,12 +1447,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } Pointer::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1437,12 +1470,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperExp::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } @@ -1454,12 +1493,18 @@ where #[allow(clippy::missing_inline_in_public_items)] fn fmt(&self, f: &mut Formatter) -> core::fmt::Result { write!(f, "[")?; + if f.alternate() { + write!(f, "\n ")?; + } for (i, elem) in self.iter().enumerate() { if i > 0 { - write!(f, ", ")?; + write!(f, ",{}", if f.alternate() { "\n " } else { " " })?; } UpperHex::fmt(elem, f)?; } + if f.alternate() { + write!(f, ",\n")?; + } write!(f, "]") } } diff --git a/tests/arrayvec.rs b/tests/arrayvec.rs index 37db5b2..15c5b64 100644 --- a/tests/arrayvec.rs +++ b/tests/arrayvec.rs @@ -445,3 +445,32 @@ fn ArrayVec_ser_de() { ], ); } + +#[test] +fn ArrayVec_try_from_slice() { + use std::convert::TryFrom; + + let nums = [1, 2, 3, 4]; + + let empty: Result, _> = ArrayVec::try_from(&nums[..0]); + assert!(empty.is_ok()); + assert_eq!(empty.unwrap().as_slice(), &[]); + + let fits: Result, _> = ArrayVec::try_from(&nums[..2]); + assert!(fits.is_ok()); + assert_eq!(fits.unwrap().as_slice(), &[1, 2]); + + let doesnt_fit: Result, _> = ArrayVec::try_from(&nums[..4]); + assert!(doesnt_fit.is_err()); +} + +#[test] +fn ArrayVec_pretty_debug() { + let arr: [i32; 3] = [1, 2, 3]; + let expect = format!("{:#?}", arr); + + let arr: ArrayVec<[i32; 3]> = array_vec![1, 2, 3]; + let got = format!("{:#?}", arr); + + assert_eq!(got, expect); +} diff --git a/tests/tinyvec.rs b/tests/tinyvec.rs index df17004..e59a83b 100644 --- a/tests/tinyvec.rs +++ b/tests/tinyvec.rs @@ -385,3 +385,12 @@ fn TinyVec_ser_de_heap() { ], ); } + +#[test] +fn TinyVec_pretty_debug() { + let tv: TinyVec<[i32; 6]> = tiny_vec![1, 2, 3]; + let s = format!("{:#?}", tv); + let expected = format!("{:#?}", tv.as_slice()); + + assert_eq!(s, expected); +} -- cgit v1.2.3 From 874ba7dc380c50540af907bcbe65182c9d331707 Mon Sep 17 00:00:00 2001 From: Joel Galenson Date: Mon, 9 Aug 2021 10:47:58 -0700 Subject: Upgrade rust/crates/tinyvec to 1.3.1 Test: make Change-Id: I1a901c023db9f9c52760e89d3cd1b2ab903821d0 --- .cargo_vcs_info.json | 2 +- CHANGELOG.md | 9 +++++++++ Cargo.toml | 6 +++++- Cargo.toml.orig | 4 +++- METADATA | 8 ++++---- rustfmt.toml | 4 +--- src/arrayvec.rs | 54 ++++++++++++++++++++++++++++++++++++++++++++++++- src/tinyvec.rs | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++- tests/arrayvec.rs | 3 ++- 9 files changed, 134 insertions(+), 13 deletions(-) diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index d6de403..a951fcc 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,5 @@ { "git": { - "sha1": "b6313725a26509d574ccf72885bc9c85fc4f476b" + "sha1": "a4bbfa9864d6a9d5ac607841025b517e618f3c8f" } } diff --git a/CHANGELOG.md b/CHANGELOG.md index 8cc2ad7..ea5226b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,14 @@ # Changelog +## 1.3.1 + +* Improved the performance of the `clone_from` method [pr 144](https://github.com/Lokathor/tinyvec/pull/144) + +## 1.3.0 + +* [jeffa5](https://github.com/jeffa5) added arbitrary implementations for `TinyVec` and `ArrayVec` [pr 146](https://github.com/Lokathor/tinyvec/pull/146). +* [elomatreb](https://github.com/elomatreb) implemented `DoubleEndedIterator` for `TinyVecIterator` [pr 145](https://github.com/Lokathor/tinyvec/pull/145). + ## 1.2.0 * [Cryptjar](https://github.com/Cryptjar) removed the `A:Array` bound on the struct of `ArrayVec`, diff --git a/Cargo.toml b/Cargo.toml index 905979a..fec505e 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -13,7 +13,7 @@ [package] edition = "2018" name = "tinyvec" -version = "1.2.0" +version = "1.3.1" authors = ["Lokathor "] description = "`tinyvec` provides 100% safe vec-like data structures." keywords = ["vec", "no_std", "no-std"] @@ -37,6 +37,10 @@ required-features = ["alloc"] name = "macros" harness = false required-features = ["alloc"] +[dependencies.arbitrary] +version = "1" +optional = true + [dependencies.serde] version = "1.0" optional = true diff --git a/Cargo.toml.orig b/Cargo.toml.orig index 2652d09..d0b0e31 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,7 +1,7 @@ [package] name = "tinyvec" description = "`tinyvec` provides 100% safe vec-like data structures." -version = "1.2.0" +version = "1.3.1" authors = ["Lokathor "] edition = "2018" license = "Zlib OR Apache-2.0 OR MIT" @@ -13,6 +13,8 @@ repository = "https://github.com/Lokathor/tinyvec" tinyvec_macros = { version = "0.1", optional = true } # Provides `Serialize` and `Deserialize` implementations serde = { version = "1.0", optional = true, default-features = false } +# Provides derived `Arbitrary` implementations +arbitrary = { version = "1", optional = true } [features] default = [] diff --git a/METADATA b/METADATA index e240ffb..b1c756c 100644 --- a/METADATA +++ b/METADATA @@ -7,13 +7,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/tinyvec/tinyvec-1.2.0.crate" + value: "https://static.crates.io/crates/tinyvec/tinyvec-1.3.1.crate" } - version: "1.2.0" + version: "1.3.1" license_type: NOTICE last_upgrade_date { year: 2021 - month: 5 - day: 19 + month: 8 + day: 9 } } diff --git a/rustfmt.toml b/rustfmt.toml index 23b0fd5..59b3aae 100644 --- a/rustfmt.toml +++ b/rustfmt.toml @@ -1,5 +1,3 @@ -# Based on -# https://github.com/rust-lang/rustfmt/blob/rustfmt-1.4.19/Configurations.md # Stable edition = "2018" @@ -12,5 +10,5 @@ use_small_heuristics = "Max" # Unstable format_code_in_doc_comments = true -merge_imports = true wrap_comments = true +imports_granularity="Crate" diff --git a/src/arrayvec.rs b/src/arrayvec.rs index ba351c1..7cf1bfc 100644 --- a/src/arrayvec.rs +++ b/src/arrayvec.rs @@ -101,12 +101,48 @@ macro_rules! array_vec { /// assert_eq!(no_ints.len(), 0); /// ``` #[repr(C)] -#[derive(Clone, Copy)] pub struct ArrayVec { len: u16, pub(crate) data: A, } +impl Clone for ArrayVec +where + A: Array + Clone, + A::Item: Clone, +{ + #[inline] + fn clone(&self) -> Self { + Self { data: self.data.clone(), len: self.len } + } + + #[inline] + fn clone_from(&mut self, o: &Self) { + let iter = self + .data + .as_slice_mut() + .iter_mut() + .zip(o.data.as_slice()) + .take(self.len.max(o.len) as usize); + for (dst, src) in iter { + dst.clone_from(src) + } + if let Some(to_drop) = + self.data.as_slice_mut().get_mut((o.len as usize)..(self.len as usize)) + { + to_drop.iter_mut().for_each(|x| drop(take(x))); + } + self.len = o.len; + } +} + +impl Copy for ArrayVec +where + A: Array + Copy, + A::Item: Copy, +{ +} + impl Default for ArrayVec { fn default() -> Self { Self { len: 0, data: A::default() } @@ -180,6 +216,22 @@ where } } +#[cfg(all(feature = "arbitrary", feature = "nightly_const_generics"))] +#[cfg_attr( + docs_rs, + doc(cfg(all(feature = "arbitrary", feature = "nightly_const_generics"))) +)] +impl<'a, T, const N: usize> arbitrary::Arbitrary<'a> for ArrayVec<[T; N]> +where + T: arbitrary::Arbitrary<'a> + Default, +{ + fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { + let v = <[T; N]>::arbitrary(u)?; + let av = ArrayVec::from(v); + Ok(av) + } +} + impl ArrayVec { /// Move all values from `other` into this vec. /// diff --git a/src/tinyvec.rs b/src/tinyvec.rs index 8b058a4..3e884fc 100644 --- a/src/tinyvec.rs +++ b/src/tinyvec.rs @@ -91,7 +91,6 @@ pub enum TinyVecConstructor { /// let empty_tv = tiny_vec!([u8; 16]); /// let some_ints = tiny_vec!([i32; 4] => 1, 2, 3); /// ``` -#[derive(Clone)] #[cfg_attr(docs_rs, doc(cfg(feature = "alloc")))] pub enum TinyVec { #[allow(missing_docs)] @@ -100,6 +99,34 @@ pub enum TinyVec { Heap(Vec), } +impl Clone for TinyVec +where + A: Array + Clone, + A::Item: Clone, +{ + #[inline] + fn clone(&self) -> Self { + match self { + Self::Heap(v) => Self::Heap(v.clone()), + Self::Inline(v) => Self::Inline(v.clone()), + } + } + + #[inline] + fn clone_from(&mut self, o: &Self) { + if o.len() > self.len() { + self.reserve(o.len() - self.len()); + } else { + self.truncate(o.len()); + } + let (start, end) = o.split_at(self.len()); + for (dst, src) in self.iter_mut().zip(start) { + dst.clone_from(src); + } + self.extend_from_slice(end); + } +} + impl Default for TinyVec { #[inline] #[must_use] @@ -178,6 +205,21 @@ where } } +#[cfg(feature = "arbitrary")] +#[cfg_attr(docs_rs, doc(cfg(feature = "arbitrary")))] +impl<'a, A> arbitrary::Arbitrary<'a> for TinyVec +where + A: Array, + A::Item: arbitrary::Arbitrary<'a>, +{ + fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result { + let v = Vec::arbitrary(u)?; + let mut tv = TinyVec::Heap(v); + tv.shrink_to_fit(); + Ok(tv) + } +} + impl TinyVec { /// Returns whether elements are on heap #[inline(always)] @@ -1190,6 +1232,19 @@ impl Iterator for TinyVecIterator { } } +impl DoubleEndedIterator for TinyVecIterator { + impl_mirrored! { + type Mirror = TinyVecIterator; + + #[inline] + fn next_back(self: &mut Self) -> Option; + + #[cfg(feature = "rustc_1_40")] + #[inline] + fn nth_back(self: &mut Self, n: usize) -> Option; + } +} + impl Debug for TinyVecIterator where A::Item: Debug, diff --git a/tests/arrayvec.rs b/tests/arrayvec.rs index 15c5b64..e400317 100644 --- a/tests/arrayvec.rs +++ b/tests/arrayvec.rs @@ -460,7 +460,8 @@ fn ArrayVec_try_from_slice() { assert!(fits.is_ok()); assert_eq!(fits.unwrap().as_slice(), &[1, 2]); - let doesnt_fit: Result, _> = ArrayVec::try_from(&nums[..4]); + let doesnt_fit: Result, _> = + ArrayVec::try_from(&nums[..4]); assert!(doesnt_fit.is_err()); } -- cgit v1.2.3 From 153eaf0a1efb03649054d826c49449076c0e397d Mon Sep 17 00:00:00 2001 From: Joel Galenson Date: Wed, 22 Sep 2021 11:24:58 -0700 Subject: Upgrade rust/crates/tinyvec to 1.4.0 Test: make Change-Id: Iab5b8bbf28c57673b410246638c53e60bc2eddf6 --- .cargo_vcs_info.json | 2 +- Android.bp | 5 ++--- CHANGELOG.md | 5 +++++ Cargo.toml | 17 ++++++++--------- Cargo.toml.orig | 13 +++++++------ METADATA | 8 ++++---- src/array.rs | 6 +++--- src/lib.rs | 4 ---- 8 files changed, 30 insertions(+), 30 deletions(-) diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index a951fcc..3d0fa1e 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,5 @@ { "git": { - "sha1": "a4bbfa9864d6a9d5ac607841025b517e618f3c8f" + "sha1": "7518868e4b9c802b214ce393f79f82fa13bef251" } } diff --git a/Android.bp b/Android.bp index 47bf80c..30327d3 100644 --- a/Android.bp +++ b/Android.bp @@ -43,6 +43,8 @@ rust_library { name: "libtinyvec", host_supported: true, crate_name: "tinyvec", + cargo_env_compat: true, + cargo_pkg_version: "1.4.0", srcs: ["src/lib.rs"], edition: "2018", features: [ @@ -59,6 +61,3 @@ rust_library { ], min_sdk_version: "29", } - -// dependent_library ["feature_list"] -// tinyvec_macros-0.1.0 diff --git a/CHANGELOG.md b/CHANGELOG.md index ea5226b..1bcc2a1 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,10 @@ # Changelog +## 1.4.0 + +* [saethlin](https://github.com/saethlin) stabilized the usage of const generics and array map with the `rustc_1_55` feature. + [pr 149](https://github.com/Lokathor/tinyvec/pull/149) + ## 1.3.1 * Improved the performance of the `clone_from` method [pr 144](https://github.com/Lokathor/tinyvec/pull/144) diff --git a/Cargo.toml b/Cargo.toml index fec505e..3ab13bd 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -3,17 +3,16 @@ # 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 +# 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) +# If you are reading this file be aware that the original Cargo.toml +# will likely look very different (and much more reasonable). +# See Cargo.toml.orig for the original contents. [package] edition = "2018" name = "tinyvec" -version = "1.3.1" +version = "1.4.0" authors = ["Lokathor "] description = "`tinyvec` provides 100% safe vec-like data structures." keywords = ["vec", "no_std", "no-std"] @@ -21,11 +20,11 @@ categories = ["data-structures", "no-std"] license = "Zlib OR Apache-2.0 OR MIT" repository = "https://github.com/Lokathor/tinyvec" [package.metadata.docs.rs] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "serde"] +features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] rustdoc-args = ["--cfg", "docs_rs"] [package.metadata.playground] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "serde"] +features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] [profile.test] opt-level = 3 @@ -60,6 +59,6 @@ alloc = ["tinyvec_macros"] default = [] experimental_write_impl = [] grab_spare_slice = [] -nightly_const_generics = [] nightly_slice_partition_dedup = [] rustc_1_40 = [] +rustc_1_55 = ["rustc_1_40"] diff --git a/Cargo.toml.orig b/Cargo.toml.orig index d0b0e31..a262ed1 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,7 +1,7 @@ [package] name = "tinyvec" description = "`tinyvec` provides 100% safe vec-like data structures." -version = "1.3.1" +version = "1.4.0" authors = ["Lokathor "] edition = "2018" license = "Zlib OR Apache-2.0 OR MIT" @@ -31,14 +31,15 @@ grab_spare_slice = [] # DoubleEndedIterator::nth_back - 1.40 rustc_1_40 = [] +# features that require rustc 1.55 +# use const generics to implement Array for all array lengths +rustc_1_55 = ["rustc_1_40"] + # allow use of nightly feature `slice_partition_dedup`, # will become useless once that is stabilized: # https://github.com/rust-lang/rust/issues/54279 nightly_slice_partition_dedup = [] -# use const generics for arrays -nightly_const_generics = [] - # EXPERIMENTAL: Not part of SemVer. It adds `core::fmt::Write` to `ArrayVec` # and `SliceVec`. It works on Stable Rust, but Vec normally supports the # `std::io::Write` trait instead of `core::fmt::Write`, so we're keeping it as @@ -46,11 +47,11 @@ nightly_const_generics = [] experimental_write_impl = [] [package.metadata.docs.rs] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "serde"] +features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] rustdoc-args = ["--cfg","docs_rs"] [package.metadata.playground] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "serde"] +features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] [profile.test] opt-level = 3 diff --git a/METADATA b/METADATA index b1c756c..8445b96 100644 --- a/METADATA +++ b/METADATA @@ -7,13 +7,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/tinyvec/tinyvec-1.3.1.crate" + value: "https://static.crates.io/crates/tinyvec/tinyvec-1.4.0.crate" } - version: "1.3.1" + version: "1.4.0" license_type: NOTICE last_upgrade_date { year: 2021 - month: 8 - day: 9 + month: 9 + day: 22 } } diff --git a/src/array.rs b/src/array.rs index 75f33c6..cc84aaf 100644 --- a/src/array.rs +++ b/src/array.rs @@ -8,7 +8,7 @@ /// /// You are generally **not** expected to need to implement this yourself. It is /// already implemented for all the major array lengths (`0..=32` and the powers -/// of 2 up to 4,096). +/// of 2 up to 4,096), or for all array lengths with the feature `rustc_1_55`. /// /// **Additional lengths can easily be added upon request.** /// @@ -41,8 +41,8 @@ pub trait Array { fn default() -> Self; } -#[cfg(feature = "nightly_const_generics")] +#[cfg(feature = "rustc_1_55")] mod const_generic_impl; -#[cfg(not(feature = "nightly_const_generics"))] +#[cfg(not(feature = "rustc_1_55"))] mod generated_impl; diff --git a/src/lib.rs b/src/lib.rs index ce06601..b3ee259 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -4,10 +4,6 @@ feature = "nightly_slice_partition_dedup", feature(slice_partition_dedup) )] -#![cfg_attr( - feature = "nightly_const_generics", - feature(min_const_generics, array_map) -)] #![cfg_attr(docs_rs, feature(doc_cfg))] #![warn(clippy::missing_inline_in_public_items)] #![warn(clippy::must_use_candidate)] -- cgit v1.2.3 From 7080eb50e93caac826d15fa858f3394a5e1dfd40 Mon Sep 17 00:00:00 2001 From: Jeff Vander Stoep Date: Tue, 19 Oct 2021 21:32:45 +0200 Subject: Enable tests Test: atest ------- x86_64 tinyvec_host_test_tests_arrayvec: Passed: 14, Failed: 0, Ignored: 0, Assumption Failed: 0, x86_64 tinyvec_host_test_tests_tinyvec: Passed: 13, Failed: 0, Ignored: 0, Assumption Failed: 0, x86 tinyvec_device_test_tests_arrayvec: Passed: 14, Failed: 0, Ignored: 0, Assumption Failed: 0, x86 tinyvec_device_test_tests_tinyvec: Passed: 13, Failed: 0, Ignored: 0, Assumption Failed: 0, Change-Id: I21f07c389a824e36cd4b0e59c756c45acbd45ffc --- Android.bp | 55 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ TEST_MAPPING | 6 ++++++ cargo2android.json | 5 +++-- 3 files changed, 64 insertions(+), 2 deletions(-) diff --git a/Android.bp b/Android.bp index 30327d3..c3e5a0d 100644 --- a/Android.bp +++ b/Android.bp @@ -61,3 +61,58 @@ rust_library { ], min_sdk_version: "29", } + +rust_defaults { + name: "tinyvec_test_defaults", + crate_name: "tinyvec", + cargo_env_compat: true, + cargo_pkg_version: "1.4.0", + test_suites: ["general-tests"], + auto_gen_config: true, + edition: "2018", + features: [ + "alloc", + "default", + "tinyvec_macros", + ], + flags: [ + "-C debug-assertions=on", + "-C opt-level=3", + ], + rustlibs: [ + "libcriterion", + "libserde_test", + "libtinyvec", + "libtinyvec_macros", + ], +} + +rust_test_host { + name: "tinyvec_host_test_tests_arrayvec", + defaults: ["tinyvec_test_defaults"], + srcs: ["tests/arrayvec.rs"], + test_options: { + unit_test: true, + }, +} + +rust_test { + name: "tinyvec_device_test_tests_arrayvec", + defaults: ["tinyvec_test_defaults"], + srcs: ["tests/arrayvec.rs"], +} + +rust_test_host { + name: "tinyvec_host_test_tests_tinyvec", + defaults: ["tinyvec_test_defaults"], + srcs: ["tests/tinyvec.rs"], + test_options: { + unit_test: true, + }, +} + +rust_test { + name: "tinyvec_device_test_tests_tinyvec", + defaults: ["tinyvec_test_defaults"], + srcs: ["tests/tinyvec.rs"], +} diff --git a/TEST_MAPPING b/TEST_MAPPING index bf91080..e448918 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -7,6 +7,12 @@ { "name": "quiche_device_test_src_lib" }, + { + "name": "tinyvec_device_test_tests_arrayvec" + }, + { + "name": "tinyvec_device_test_tests_tinyvec" + }, { "name": "unicode-normalization_device_test_src_lib" }, diff --git a/cargo2android.json b/cargo2android.json index 9b0c9be..b86e1c0 100644 --- a/cargo2android.json +++ b/cargo2android.json @@ -7,5 +7,6 @@ "dependencies": true, "features": "alloc,default,tinyvec_macros", "device": true, - "run": true -} \ No newline at end of file + "run": true, + "tests": true +} -- cgit v1.2.3 From 930746e7fe4cc8bfb772d2d90c7c3a9442febad7 Mon Sep 17 00:00:00 2001 From: Joel Galenson Date: Mon, 29 Nov 2021 14:05:39 -0800 Subject: Refresh Android.bp, cargo2android.json, TEST_MAPPING. Test: None Change-Id: Id87f4b1ca31672e14a5f0c66f6c91ed5ae4ed441 --- Android.bp | 20 +++++--------------- TEST_MAPPING | 27 +++++++++++++++++---------- cargo2android.json | 6 +++--- 3 files changed, 25 insertions(+), 28 deletions(-) diff --git a/Android.bp b/Android.bp index c3e5a0d..15a216e 100644 --- a/Android.bp +++ b/Android.bp @@ -87,9 +87,10 @@ rust_defaults { ], } -rust_test_host { - name: "tinyvec_host_test_tests_arrayvec", +rust_test { + name: "tinyvec_test_tests_arrayvec", defaults: ["tinyvec_test_defaults"], + host_supported: true, srcs: ["tests/arrayvec.rs"], test_options: { unit_test: true, @@ -97,22 +98,11 @@ rust_test_host { } rust_test { - name: "tinyvec_device_test_tests_arrayvec", - defaults: ["tinyvec_test_defaults"], - srcs: ["tests/arrayvec.rs"], -} - -rust_test_host { - name: "tinyvec_host_test_tests_tinyvec", + name: "tinyvec_test_tests_tinyvec", defaults: ["tinyvec_test_defaults"], + host_supported: true, srcs: ["tests/tinyvec.rs"], test_options: { unit_test: true, }, } - -rust_test { - name: "tinyvec_device_test_tests_tinyvec", - defaults: ["tinyvec_test_defaults"], - srcs: ["tests/tinyvec.rs"], -} diff --git a/TEST_MAPPING b/TEST_MAPPING index e448918..45f8bcc 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -1,29 +1,36 @@ // Generated by update_crate_tests.py for tests that depend on this crate. { - "presubmit": [ + "imports": [ { - "name": "doh_unit_test" + "path": "external/rust/crates/quiche" }, { - "name": "quiche_device_test_src_lib" + "path": "external/rust/crates/unicode-normalization" }, { - "name": "tinyvec_device_test_tests_arrayvec" - }, + "path": "external/rust/crates/url" + } + ], + "presubmit": [ { - "name": "tinyvec_device_test_tests_tinyvec" + "name": "doh_unit_test" }, { - "name": "unicode-normalization_device_test_src_lib" + "name": "tinyvec_test_tests_arrayvec" }, { - "name": "url_device_test_src_lib" + "name": "tinyvec_test_tests_tinyvec" + } + ], + "presubmit-rust": [ + { + "name": "doh_unit_test" }, { - "name": "url_device_test_tests_data" + "name": "tinyvec_test_tests_arrayvec" }, { - "name": "url_device_test_tests_unit" + "name": "tinyvec_test_tests_tinyvec" } ] } diff --git a/cargo2android.json b/cargo2android.json index b86e1c0..5974d19 100644 --- a/cargo2android.json +++ b/cargo2android.json @@ -3,10 +3,10 @@ "//apex_available:platform", "com.android.resolv" ], - "min_sdk_version": "29", "dependencies": true, - "features": "alloc,default,tinyvec_macros", "device": true, + "features": "alloc,default,tinyvec_macros", + "min-sdk-version": "29", "run": true, "tests": true -} +} \ No newline at end of file -- cgit v1.2.3 From 38f28c3b882cf5d08d93f59e7feb6d087a13d88f Mon Sep 17 00:00:00 2001 From: David LeGare Date: Wed, 2 Mar 2022 16:21:19 +0000 Subject: Update tinyvec to 1.5.1 Test: cd external/rust/crates && atest --host -c Change-Id: I5939f4f57114b38250ecb3020af58e64b84663fe --- .cargo_vcs_info.json | 7 +- .github/workflows/rust.yml | 10 +- Android.bp | 40 +--- CHANGELOG.md | 11 + Cargo.toml | 21 +- Cargo.toml.orig | 55 +++-- METADATA | 10 +- benches/smallvec.rs | 500 +++++++++++++++++++++++++++++++++++++++++++++ compare_benchmarks.py | 30 +++ src/lib.rs | 2 +- src/tinyvec.rs | 19 +- tests/tinyvec.rs | 15 ++ 12 files changed, 656 insertions(+), 64 deletions(-) create mode 100644 benches/smallvec.rs create mode 100644 compare_benchmarks.py diff --git a/.cargo_vcs_info.json b/.cargo_vcs_info.json index 3d0fa1e..6772581 100644 --- a/.cargo_vcs_info.json +++ b/.cargo_vcs_info.json @@ -1,5 +1,6 @@ { "git": { - "sha1": "7518868e4b9c802b214ce393f79f82fa13bef251" - } -} + "sha1": "1ef53f632b9cb6f2e7ff603586f4472317b9a25c" + }, + "path_in_vcs": "" +} \ No newline at end of file diff --git a/.github/workflows/rust.yml b/.github/workflows/rust.yml index 16bf072..050e70d 100644 --- a/.github/workflows/rust.yml +++ b/.github/workflows/rust.yml @@ -11,6 +11,7 @@ jobs: matrix: rust: - 1.34.0 + - 1.36.0 - stable - beta - nightly @@ -25,9 +26,16 @@ jobs: uses: actions-rs/cargo@v1 with: command: build - - name: Test on Stable/Beta + - name: Build the crate on 1.36 with features. if: matrix.rust != '1.34.0' uses: actions-rs/cargo@v1 + with: + command: build + # Using `extern crate alloc` is only possible after 1.36 + args: --features=alloc,std,grab_spare_slice + - name: Test on Stable/Beta + if: matrix.rust != '1.34.0' && matrix.rust != '1.36.0' + uses: actions-rs/cargo@v1 with: command: test args: --features=alloc --features=grab_spare_slice --features=rustc_1_40 diff --git a/Android.bp b/Android.bp index 15a216e..3888f8c 100644 --- a/Android.bp +++ b/Android.bp @@ -44,7 +44,7 @@ rust_library { host_supported: true, crate_name: "tinyvec", cargo_env_compat: true, - cargo_pkg_version: "1.4.0", + cargo_pkg_version: "1.5.1", srcs: ["src/lib.rs"], edition: "2018", features: [ @@ -62,47 +62,29 @@ rust_library { min_sdk_version: "29", } -rust_defaults { - name: "tinyvec_test_defaults", - crate_name: "tinyvec", +rust_test { + name: "tinyvec_test_tests_arrayvec", + host_supported: true, + crate_name: "arrayvec", cargo_env_compat: true, - cargo_pkg_version: "1.4.0", + cargo_pkg_version: "1.5.1", + srcs: ["tests/arrayvec.rs"], test_suites: ["general-tests"], auto_gen_config: true, + test_options: { + unit_test: true, + }, edition: "2018", features: [ "alloc", "default", "tinyvec_macros", ], - flags: [ - "-C debug-assertions=on", - "-C opt-level=3", - ], rustlibs: [ "libcriterion", "libserde_test", + "libsmallvec", "libtinyvec", "libtinyvec_macros", ], } - -rust_test { - name: "tinyvec_test_tests_arrayvec", - defaults: ["tinyvec_test_defaults"], - host_supported: true, - srcs: ["tests/arrayvec.rs"], - test_options: { - unit_test: true, - }, -} - -rust_test { - name: "tinyvec_test_tests_tinyvec", - defaults: ["tinyvec_test_defaults"], - host_supported: true, - srcs: ["tests/tinyvec.rs"], - test_options: { - unit_test: true, - }, -} diff --git a/CHANGELOG.md b/CHANGELOG.md index 1bcc2a1..93ef808 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,16 @@ # Changelog +## 1.5.1 + +* [madsmtm](https://github.com/madsmtm) fixed an error with the `alloc` feature on very old rustc versions. + [pr 154](https://github.com/Lokathor/tinyvec/pull/154) + +## 1.5.0 + +* [eeeebbbbrrrr](https://github.com/eeeebbbbrrrr) added an impl for [std::io::Write](https://doc.rust-lang.org/std/io/trait.Write.html) to `TinyVec` when the element type is `u8`. + This is gated behind the new `std` feature. + [pr 152](https://github.com/Lokathor/tinyvec/pull/152) + ## 1.4.0 * [saethlin](https://github.com/saethlin) stabilized the usage of const generics and array map with the `rustc_1_55` feature. diff --git a/Cargo.toml b/Cargo.toml index 3ab13bd..24dfa0d 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,7 +12,7 @@ [package] edition = "2018" name = "tinyvec" -version = "1.4.0" +version = "1.5.1" authors = ["Lokathor "] description = "`tinyvec` provides 100% safe vec-like data structures." keywords = ["vec", "no_std", "no-std"] @@ -20,22 +20,30 @@ categories = ["data-structures", "no-std"] license = "Zlib OR Apache-2.0 OR MIT" repository = "https://github.com/Lokathor/tinyvec" [package.metadata.docs.rs] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] +features = ["alloc", "std", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] rustdoc-args = ["--cfg", "docs_rs"] [package.metadata.playground] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] +features = ["alloc", "std", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] +[profile.bench] +debug = 2 + [profile.test] opt-level = 3 [[test]] name = "tinyvec" -required-features = ["alloc"] +required-features = ["alloc", "std"] [[bench]] name = "macros" harness = false required-features = ["alloc"] + +[[bench]] +name = "smallvec" +harness = false +required-features = ["alloc", "real_blackbox"] [dependencies.arbitrary] version = "1" optional = true @@ -54,11 +62,16 @@ version = "0.3.0" [dev-dependencies.serde_test] version = "1.0" +[dev-dependencies.smallvec] +version = "1" + [features] alloc = ["tinyvec_macros"] default = [] experimental_write_impl = [] grab_spare_slice = [] nightly_slice_partition_dedup = [] +real_blackbox = ["criterion/real_blackbox"] rustc_1_40 = [] rustc_1_55 = ["rustc_1_40"] +std = [] diff --git a/Cargo.toml.orig b/Cargo.toml.orig index a262ed1..28a5874 100644 --- a/Cargo.toml.orig +++ b/Cargo.toml.orig @@ -1,73 +1,90 @@ [package] name = "tinyvec" description = "`tinyvec` provides 100% safe vec-like data structures." -version = "1.4.0" +version = "1.5.1" authors = ["Lokathor "] edition = "2018" license = "Zlib OR Apache-2.0 OR MIT" keywords = ["vec", "no_std", "no-std"] categories = ["data-structures", "no-std"] repository = "https://github.com/Lokathor/tinyvec" - + [dependencies] tinyvec_macros = { version = "0.1", optional = true } # Provides `Serialize` and `Deserialize` implementations serde = { version = "1.0", optional = true, default-features = false } # Provides derived `Arbitrary` implementations arbitrary = { version = "1", optional = true } - + [features] default = [] - + # Provide things that utilize the `alloc` crate, namely `TinyVec`. alloc = ["tinyvec_macros"] - + +# Provide things that require Rust's `std` module +std = [] + # (not part of Vec!) Extra methods to let you grab the slice of memory after the # "active" portion of an `ArrayVec` or `SliceVec`. grab_spare_slice = [] - + # features that require rustc 1.40 # use Vec::append if possible in TinyVec::append - 1.37 # DoubleEndedIterator::nth_back - 1.40 rustc_1_40 = [] - + # features that require rustc 1.55 # use const generics to implement Array for all array lengths rustc_1_55 = ["rustc_1_40"] - + # allow use of nightly feature `slice_partition_dedup`, # will become useless once that is stabilized: # https://github.com/rust-lang/rust/issues/54279 nightly_slice_partition_dedup = [] - + # EXPERIMENTAL: Not part of SemVer. It adds `core::fmt::Write` to `ArrayVec` # and `SliceVec`. It works on Stable Rust, but Vec normally supports the # `std::io::Write` trait instead of `core::fmt::Write`, so we're keeping it as # an experimental impl only for now. experimental_write_impl = [] - + +# Some benchmarks are optimized away with the stable black_box function +# which is based on read_volatile. This feature requires inline assembly +# and thus a nightly compiler, but is only used in benchmarks. +real_blackbox = ["criterion/real_blackbox"] + [package.metadata.docs.rs] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] +features = ["alloc", "std", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] rustdoc-args = ["--cfg","docs_rs"] - + [package.metadata.playground] -features = ["alloc", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] - +features = ["alloc", "std", "grab_spare_slice", "rustc_1_40", "rustc_1_55", "serde"] + [profile.test] opt-level = 3 - + +[profile.bench] +debug = 2 + [workspace] members = ["fuzz"] - + [dev-dependencies] criterion = "0.3.0" serde_test = "1.0" - +smallvec = "1" + [[test]] name = "tinyvec" -required-features = ["alloc"] - +required-features = ["alloc", "std"] + [[bench]] name = "macros" harness = false required-features = ["alloc"] + +[[bench]] +name = "smallvec" +harness = false +required-features = ["alloc", "real_blackbox"] diff --git a/METADATA b/METADATA index 8445b96..a632067 100644 --- a/METADATA +++ b/METADATA @@ -7,13 +7,13 @@ third_party { } url { type: ARCHIVE - value: "https://static.crates.io/crates/tinyvec/tinyvec-1.4.0.crate" + value: "https://static.crates.io/crates/tinyvec/tinyvec-1.5.1.crate" } - version: "1.4.0" + version: "1.5.1" license_type: NOTICE last_upgrade_date { - year: 2021 - month: 9 - day: 22 + year: 2022 + month: 3 + day: 1 } } diff --git a/benches/smallvec.rs b/benches/smallvec.rs new file mode 100644 index 0000000..8cd16d3 --- /dev/null +++ b/benches/smallvec.rs @@ -0,0 +1,500 @@ +//! Benchmarks that compare TinyVec to SmallVec +//! +//! All the following commentary is based on the latest nightly at the time: +//! rustc 1.55.0 (c8dfcfe04 2021-09-06). +//! +//! Some of these benchmarks are just a few instructions, so we put our own for loop inside +//! the criterion::Bencher::iter call. This seems to improve the stability of measurements, and it +//! has the wonderful side effect of making the emitted assembly easier to follow. Some of these +//! benchmarks are totally inlined so that there are no calls at all in the hot path, so finding +//! this for loop is an easy way to find your way around the emitted assembly. +//! +//! The clear method is cheaper to call for arrays of elements without a Drop impl, so wherever +//! possible we reuse a single object in the benchmark loop, with a clear + black_box on each +//! iteration in an attempt to not make that visible to the optimizer. +//! +//! We always call black_box(&v), instead of v = black_box(v) because the latter does a move of the +//! inline array, which is linear in the size of the array and thus varies based on the array type +//! being benchmarked, and this move can be more expensive than the function we're trying to +//! benchmark. +//! +//! We also black_box the input to each method call. This has a significant effect on the assembly +//! emitted, for example if we do not black_box the range we iterate over in the ::push benchmarks, +//! the loop is unrolled. It's not entirely clear if it's better to black_box the iterator that +//! yields the items being pushed, or to black_box at a deeper level: v.push(black_box(i)) for +//! example. Anecdotally, it seems like the latter approach produces unreasonably bad assembly. +//! + +use criterion::{black_box, criterion_group, criterion_main, Criterion}; +use smallvec::SmallVec; +use std::iter::FromIterator; +use tinyvec::TinyVec; + +const ITERS: usize = 10_000; + +macro_rules! tinyvec_benches { + ($c:expr, $type:ty ; $len:expr) => {{ + let mut g = $c.benchmark_group(concat!( + "TinyVec_", + stringify!($type), + "_", + stringify!($len) + )); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::default" + ), + |b| { + b.iter(|| { + for _ in 0..ITERS { + let v: TinyVec<[$type; $len]> = TinyVec::default(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::clone" + ), + |b| { + b.iter(|| { + let outer: TinyVec<[$type; $len]> = + black_box(TinyVec::from_iter(0..=($len as usize - 1) as _)); + for _ in 0..ITERS { + let v = outer.clone(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::clear" + ), + |b| { + b.iter(|| { + let mut v: TinyVec<[$type; $len]> = TinyVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::push" + ), + |b| { + b.iter(|| { + let mut v: TinyVec<[$type; $len]> = TinyVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + for i in black_box(0..=($len as usize - 1) as _) { + v.push(i); + } + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::from_iter" + ), + |b| { + b.iter(|| { + for _ in 0..ITERS { + let v: TinyVec<[$type; $len]> = + TinyVec::from_iter(black_box(0..=($len as usize - 1) as _)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::from_slice" + ), + |b| { + b.iter(|| { + let data: &[$type] = &[0, 1, 2, 3, 4, 5, 6, 7]; + for _ in 0..ITERS { + let v: TinyVec<[$type; $len]> = TinyVec::from(black_box(data)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::extend" + ), + |b| { + b.iter(|| { + let mut v: TinyVec<[$type; $len]> = black_box(TinyVec::default()); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + v.extend(black_box(0..=($len as usize - 1) as _)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::extend_from_slice" + ), + |b| { + b.iter(|| { + let data: &[$type] = black_box(&[0, 1, 2, 3, 4, 5, 6, 7]); + let mut v: TinyVec<[$type; $len]> = black_box(TinyVec::default()); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + v.extend_from_slice(data); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::insert" + ), + |b| { + b.iter(|| { + let mut v: TinyVec<[$type; $len]> = TinyVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + for i in black_box(0..=($len as usize - 1) as _) { + v.insert(i as usize, i); + } + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "TinyVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::remove" + ), + |b| { + b.iter(|| { + let outer: TinyVec<[$type; $len]> = + black_box(TinyVec::from_iter(0..=($len as usize - 1) as _)); + for _ in 0..ITERS { + let mut v = outer.clone(); + for i in black_box((0..=($len as usize - 1) as _).rev()) { + v.remove(i); + } + black_box(&v); + } + }); + }, + ); + }}; +} + +fn tinyvec_benches(c: &mut Criterion) { + tinyvec_benches!(c, u8; 8); + tinyvec_benches!(c, u8; 16); + tinyvec_benches!(c, u8; 32); + tinyvec_benches!(c, u8; 64); + tinyvec_benches!(c, u8; 128); + tinyvec_benches!(c, u8; 256); + tinyvec_benches!(c, u64; 2); + tinyvec_benches!(c, u64; 4); + tinyvec_benches!(c, u64; 8); + tinyvec_benches!(c, u64; 16); + tinyvec_benches!(c, u64; 32); +} + +macro_rules! smallvec_benches { + ($c:expr, $type:ty ; $len:expr) => {{ + let mut g = $c.benchmark_group(concat!( + "SmallVec_", + stringify!($type), + "_", + stringify!($len) + )); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::default" + ), + |b| { + b.iter(|| { + for _ in 0..ITERS { + let v: SmallVec<[$type; $len]> = SmallVec::default(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::clone" + ), + |b| { + b.iter(|| { + let outer: SmallVec<[$type; $len]> = + black_box(SmallVec::from_iter(0..=($len as usize - 1) as _)); + for _ in 0..ITERS { + let v = outer.clone(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::clear" + ), + |b| { + b.iter(|| { + let mut v: SmallVec<[$type; $len]> = SmallVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::push" + ), + |b| { + b.iter(|| { + let mut v: SmallVec<[$type; $len]> = SmallVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + for i in black_box(0..=($len as usize - 1) as _) { + v.push(i); + } + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::from_iter" + ), + |b| { + b.iter(|| { + for _ in 0..ITERS { + let v: SmallVec<[$type; $len]> = + SmallVec::from_iter(black_box(0..=($len as usize - 1) as _)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::from_slice" + ), + |b| { + b.iter(|| { + let data: &[$type] = &[0, 1, 2, 3, 4, 5, 6, 7]; + for _ in 0..ITERS { + let v: SmallVec<[$type; $len]> = SmallVec::from(black_box(data)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::extend" + ), + |b| { + b.iter(|| { + let mut v: SmallVec<[$type; $len]> = black_box(SmallVec::default()); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + v.extend(black_box(0..=($len as usize - 1) as _)); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::extend_from_slice" + ), + |b| { + b.iter(|| { + let data: &[$type] = black_box(&[0, 1, 2, 3, 4, 5, 6, 7]); + let mut v: SmallVec<[$type; $len]> = black_box(SmallVec::default()); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + v.extend_from_slice(data); + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::insert" + ), + |b| { + b.iter(|| { + let mut v: SmallVec<[$type; $len]> = SmallVec::default(); + for _ in 0..ITERS { + v.clear(); + black_box(&v); + for i in black_box(0..=($len as usize - 1) as _) { + v.insert(i as usize, i); + } + black_box(&v); + } + }); + }, + ); + + g.bench_function( + concat!( + "SmallVec<[", + stringify!($type), + "; ", + stringify!($len), + "]>::remove" + ), + |b| { + b.iter(|| { + let outer: SmallVec<[$type; $len]> = + black_box(SmallVec::from_iter(0..=($len as usize - 1) as _)); + for _ in 0..ITERS { + let mut v = outer.clone(); + for i in black_box((0..=($len as usize - 1) as _).rev()) { + v.remove(i); + } + black_box(&v); + } + }); + }, + ); + }}; +} + +fn smallvec_benches(c: &mut Criterion) { + smallvec_benches!(c, u8; 8); + smallvec_benches!(c, u8; 16); + smallvec_benches!(c, u8; 32); + smallvec_benches!(c, u8; 64); + smallvec_benches!(c, u8; 128); + smallvec_benches!(c, u8; 256); + smallvec_benches!(c, u64; 2); + smallvec_benches!(c, u64; 4); + smallvec_benches!(c, u64; 8); + smallvec_benches!(c, u64; 16); + smallvec_benches!(c, u64; 32); +} + +criterion_group!(benches, tinyvec_benches, smallvec_benches); +criterion_main!(benches); diff --git a/compare_benchmarks.py b/compare_benchmarks.py new file mode 100644 index 0000000..86eb7e8 --- /dev/null +++ b/compare_benchmarks.py @@ -0,0 +1,30 @@ +import os +import os.path +import json + +comparisons = [] + +for (root, _dirs, files) in os.walk('target/criterion'): + for file in files: + if file == 'estimates.json' and root.endswith( + 'new') and 'TinyVec' in root: + path = os.path.join(root, file) + + bench_name = path.split('/')[3] + tinyvec_time = json.load(open(path))['mean']['point_estimate'] + + path = path.replace('TinyVec', 'SmallVec') + + smallvec_time = json.load(open(path))['mean']['point_estimate'] + + comparisons.append((bench_name, tinyvec_time / smallvec_time)) + +comparisons.sort(key=lambda x: x[1]) +longest_name = max(len(c[0]) for c in comparisons) +for (name, ratio) in comparisons: + # Undo the criterion name mangling + name = name.replace('_[', '<[') + name = name.replace(']___', ']>::') + + name = name.ljust(longest_name) + print(f"{name} {ratio:.2f}") diff --git a/src/lib.rs b/src/lib.rs index b3ee259..c66705d 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1,4 +1,4 @@ -#![no_std] +#![cfg_attr(not(feature = "std"), no_std)] #![forbid(unsafe_code)] #![cfg_attr( feature = "nightly_slice_partition_dedup", diff --git a/src/tinyvec.rs b/src/tinyvec.rs index 3e884fc..1e11a47 100644 --- a/src/tinyvec.rs +++ b/src/tinyvec.rs @@ -107,8 +107,8 @@ where #[inline] fn clone(&self) -> Self { match self { - Self::Heap(v) => Self::Heap(v.clone()), - Self::Inline(v) => Self::Inline(v.clone()), + TinyVec::Heap(v) => TinyVec::Heap(v.clone()), + TinyVec::Inline(v) => TinyVec::Inline(v.clone()), } } @@ -172,6 +172,21 @@ impl> IndexMut for TinyVec { } } +#[cfg(feature = "std")] +#[cfg_attr(docs_rs, doc(cfg(feature = "std")))] +impl> std::io::Write for TinyVec { + #[inline(always)] + fn write(&mut self, buf: &[u8]) -> std::io::Result { + self.extend_from_slice(buf); + Ok(buf.len()) + } + + #[inline(always)] + fn flush(&mut self) -> std::io::Result<()> { + Ok(()) + } +} + #[cfg(feature = "serde")] #[cfg_attr(docs_rs, doc(cfg(feature = "serde")))] impl Serialize for TinyVec diff --git a/tests/tinyvec.rs b/tests/tinyvec.rs index e59a83b..ab4d9bd 100644 --- a/tests/tinyvec.rs +++ b/tests/tinyvec.rs @@ -394,3 +394,18 @@ fn TinyVec_pretty_debug() { assert_eq!(s, expected); } + +#[cfg(feature = "std")] +#[test] +fn TinyVec_std_io_write() { + use std::io::Write; + let mut tv: TinyVec<[u8; 3]> = TinyVec::new(); + + tv.write_all(b"foo").ok(); + assert!(tv.is_inline()); + assert_eq!(tv, tiny_vec![b'f', b'o', b'o']); + + tv.write_all(b"bar").ok(); + assert!(tv.is_heap()); + assert_eq!(tv, tiny_vec![b'f', b'o', b'o', b'b', b'a', b'r']); +} -- cgit v1.2.3 From 430ec0c1e452889b92ae3ce1f7fcb0429433ae3a Mon Sep 17 00:00:00 2001 From: David LeGare Date: Wed, 2 Mar 2022 19:54:33 +0000 Subject: Update TEST_MAPPING Test: cd external/rust/crates && atest --host -c Change-Id: I44576d2105e646b7c203c10d2170e9cd82df9b42 --- TEST_MAPPING | 6 ------ 1 file changed, 6 deletions(-) diff --git a/TEST_MAPPING b/TEST_MAPPING index 45f8bcc..88d573d 100644 --- a/TEST_MAPPING +++ b/TEST_MAPPING @@ -17,9 +17,6 @@ }, { "name": "tinyvec_test_tests_arrayvec" - }, - { - "name": "tinyvec_test_tests_tinyvec" } ], "presubmit-rust": [ @@ -28,9 +25,6 @@ }, { "name": "tinyvec_test_tests_arrayvec" - }, - { - "name": "tinyvec_test_tests_tinyvec" } ] } -- cgit v1.2.3