feat(allocator): add Vec::from_value_in method (#23718)

Add `Vec::from_value_in` which creates a `Vec` containing only a single value.

This performs the same role as `AstBuilder::vec1`.

```rust
// These 2 are equivalent
let v = self.ast.vec1(value);
let v = Vec::from_value_in(value, self.ast.allocator);
```

Internally uses `Vec::from_box_in`, introduced in #23717.
This commit is contained in:
overlookmotel committed 2026-06-22 15:01:59 +00:00
1 parent 989ddb7fc4
commit fcbf993df3
1 file changed
+33
+33
View File
@@ -150,6 +150,26 @@ impl<'alloc, T> Vec<'alloc, T> {
Self(vec)
}
/// Create a new [`Vec`] containing only a single value, allocated in the given `allocator`.
///
/// # Examples
/// ```
/// use oxc_allocator::{Allocator, Vec};
///
/// let allocator = Allocator::default();
///
/// let value = 123u32;
/// let vec = Vec::from_value_in(value, &allocator);
/// assert_eq!(vec, [123]);
/// ```
#[inline]
pub fn from_value_in(value: T, allocator: &'alloc Allocator) -> Self {
const { Self::ASSERT_T_IS_NOT_DROP };
let boxed = Box::new_in(value, allocator);
Self::from_box_in(boxed, allocator)
}
/// Create a new [`Vec`] from a fixed-size array, allocated in the given `allocator`.
///
/// This is preferable to `from_iter_in` where source is an array, as size is statically known,
@@ -589,6 +609,19 @@ mod test {
assert!(foos == bars_slice);
}
#[test]
fn vec_from_value_in() {
let allocator = Allocator::default();
let mut v = Vec::from_value_in(123u32, &allocator);
assert_eq!(v, [123]);
assert_eq!(v.len(), 1);
assert_eq!(v.capacity(), 1);
// Growing the `Vec` reallocates into the allocator, preserving the original value
v.push(456);
assert_eq!(v, [123, 456]);
}
#[test]
fn vec_from_box_in() {
let allocator = Allocator::default();