From b6838f3720de43b7723acfc039ca0689073d4c99 Mon Sep 17 00:00:00 2001 From: cooronx <2197083441@qq.com> Date: Fri, 9 Oct 2026 22:55:14 +0800 Subject: [PATCH] feat: hide allocator functions when unusable --- src/lib.rs | 51 +++++++++++++++++++++++++++++++++------------------ src/macros.rs | 21 +++++++++++++++++++++ 2 files changed, 54 insertions(+), 18 deletions(-) diff --git a/src/lib.rs b/src/lib.rs index b829e233..0e8f5fd9 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -30,6 +30,7 @@ pub use iterators::{ splice::Splice }; mod locatedlength; +#[macro_use] mod macros; #[cfg(feature = "malloc_size_of")] mod mallocsizeof; @@ -1342,32 +1343,46 @@ impl SmallVec { self.length.add(length); } } +} - pub const fn new_in(allocator: Heap) -> SmallVec { - Self { - length: LocatedLength::new(0, false), - raw: RawSmallVec::new(), - allocator +impl SmallVec { + public! { + #[cfg(feature = "allocator-api")] + const fn new_in(allocator: Heap) -> SmallVec { + Self { + length: LocatedLength::new(0, false), + raw: RawSmallVec::new(), + allocator + } } } - pub fn try_with_capacity_in(capacity: usize, allocator: Heap) -> Result { - let mut this = Self::new_in(allocator); - if capacity > Self::inline_size() && !Self::IS_ZST { - // SAFETY: we checked all the preconditions - unsafe { - this.raw - .try_grow_raw(LocatedLength::new(0, false), capacity, &this.allocator) - }?; + public! { + #[cfg(feature = "allocator-api")] + fn try_with_capacity_in( + capacity: usize, + allocator: Heap + ) -> Result { + let mut this = Self::new_in(allocator); + if capacity > Self::inline_size() && !Self::IS_ZST { + // SAFETY: we checked all the preconditions + unsafe { + this.raw + .try_grow_raw(LocatedLength::new(0, false), capacity, &this.allocator) + }?; - // SAFETY: the allocation succeeded, so self.raw.heap is now active - this.length.set_location::(); + // SAFETY: the allocation succeeded, so self.raw.heap is now active + this.length.set_location::(); + } + Ok(this) } - Ok(this) } - pub fn with_capacity_in(capacity: usize, allocator: Heap) -> Self { - Self::try_with_capacity_in(capacity, allocator).unwrap_or_else(SmallVecError::handle) + public! { + #[cfg(feature = "allocator-api")] + fn with_capacity_in(capacity: usize, allocator: Heap) -> Self { + Self::try_with_capacity_in(capacity, allocator).unwrap_or_else(SmallVecError::handle) + } } } diff --git a/src/macros.rs b/src/macros.rs index b7da06c6..1e9cee0c 100644 --- a/src/macros.rs +++ b/src/macros.rs @@ -19,3 +19,24 @@ macro_rules! smallvec_inline { $crate::SmallVec::from_buf([$($($x),+)?]) }); } + +macro_rules! public { + (#[cfg($($cond:tt)*)] $(#[$attr:meta])* const fn $($rest:tt)*) => { + #[cfg($($cond)*)] + $(#[$attr])* + pub const fn $($rest)* + + #[cfg(not($($cond)*))] + $(#[$attr])* + const fn $($rest)* + }; + (#[cfg($($cond:tt)*)] $(#[$attr:meta])* fn $($rest:tt)*) => { + #[cfg($($cond)*)] + $(#[$attr])* + pub fn $($rest)* + + #[cfg(not($($cond)*))] + $(#[$attr])* + fn $($rest)* + }; +}