Skip to content

Commit 4d8c1b2

Browse files
committed
feat: add const_new feature for const ThinVec::new()
This adds a new optional feature `const_new` that makes `ThinVec::new()` a const fn when enabled. The feature requires Rust 1.83 or later.
1 parent 6f3da25 commit 4d8c1b2

File tree

2 files changed

+23
-0
lines changed

2 files changed

+23
-0
lines changed

Cargo.toml

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ rust-version = "1.53"
1414
unstable = []
1515
default = ["std"]
1616
std = []
17+
const_new = []
1718

1819
# Gecko specific features. These features cause thin-vec to have the same layout
1920
# and behaviour as nsTArray, allowing it to be used in C++ FFI. Requires

src/lib.rs

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,14 @@
2222
//! but it could be done if someone cared enough to implement it.
2323
//!
2424
//!
25+
//! # Optional Features
26+
//!
27+
//! ## `const_new`
28+
//!
29+
//! **This feature requires Rust 1.83.**
30+
//!
31+
//! This feature makes `ThinVec::new()` a `const fn`.
32+
//!
2533
//!
2634
//! # Gecko FFI
2735
//!
@@ -516,10 +524,24 @@ impl<T> ThinVec<T> {
516524
/// Creates a new empty ThinVec.
517525
///
518526
/// This will not allocate.
527+
#[cfg(not(feature = "const_new"))]
519528
pub fn new() -> ThinVec<T> {
520529
ThinVec::with_capacity(0)
521530
}
522531

532+
/// Creates a new empty ThinVec.
533+
///
534+
/// This will not allocate.
535+
#[cfg(feature = "const_new")]
536+
pub const fn new() -> ThinVec<T> {
537+
unsafe {
538+
ThinVec {
539+
ptr: NonNull::new_unchecked(&EMPTY_HEADER as *const Header as *mut Header),
540+
boo: PhantomData,
541+
}
542+
}
543+
}
544+
523545
/// Constructs a new, empty `ThinVec<T>` with at least the specified capacity.
524546
///
525547
/// The vector will be able to hold at least `capacity` elements without

0 commit comments

Comments
 (0)