Skip to content

Commit 7a41a66

Browse files
committed
new constructors: from_buf_and_len(_unchecked)
Those functions allow to create an inline SmallVec supplying both buf and len arguments, so only a part of the buffer is used. The unchecked variant doesn't check if the length is less or equal than the buffer length.
1 parent 17b68fe commit 7a41a66

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

Diff for: lib.rs

+41
Original file line numberDiff line numberDiff line change
@@ -480,6 +480,47 @@ impl<A: Array> SmallVec<A> {
480480
}
481481
}
482482

483+
/// Constructs a new `SmallVec` on the stack from an `A` without
484+
/// copying elements. Also sets the length, which must be less or
485+
/// equal to the size of `buf`.
486+
///
487+
/// ```rust
488+
/// use smallvec::SmallVec;
489+
///
490+
/// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
491+
/// let small_vec: SmallVec<_> = SmallVec::from_buf_and_len(buf, 5);
492+
///
493+
/// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
494+
/// ```
495+
#[inline]
496+
pub fn from_buf_and_len(buf: A, len: usize) -> SmallVec<A> {
497+
assert!(len <= A::size());
498+
unsafe { SmallVec::from_buf_and_len_unchecked(buf, len) }
499+
}
500+
501+
/// Constructs a new `SmallVec` on the stack from an `A` without
502+
/// copying elements. Also sets the length. The user is responsible
503+
/// for ensuring that `len <= A::size()`.
504+
///
505+
/// ```rust
506+
/// use smallvec::SmallVec;
507+
///
508+
/// let buf = [1, 2, 3, 4, 5, 0, 0, 0];
509+
/// let small_vec: SmallVec<_> = unsafe {
510+
/// SmallVec::from_buf_and_len_unchecked(buf, 5)
511+
/// };
512+
///
513+
/// assert_eq!(&*small_vec, &[1, 2, 3, 4, 5]);
514+
/// ```
515+
#[inline]
516+
pub unsafe fn from_buf_and_len_unchecked(buf: A, len: usize) -> SmallVec<A> {
517+
SmallVec {
518+
capacity: len,
519+
data: SmallVecData::from_inline(buf),
520+
}
521+
}
522+
523+
483524
/// Sets the length of a vector.
484525
///
485526
/// This will explicitly set the size of the vector, without actually

0 commit comments

Comments
 (0)