Skip to content

Commit 191bc11

Browse files
author
bors-servo
authored
Auto merge of #117 - llogiq:from_buf_and_len, r=mbrubeck
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. This allows users to set up a partially used in-band buffer in one step (instead of using `from_buf` and calling `truncate` or `set_len` later). <!-- Reviewable:start --> --- This change is [<img src="https://reviewable.io/review_button.svg" height="34" align="absmiddle" alt="Reviewable"/>](https://reviewable.io/reviews/servo/rust-smallvec/117) <!-- Reviewable:end -->
2 parents 17b68fe + 7a41a66 commit 191bc11

File tree

1 file changed

+41
-0
lines changed

1 file changed

+41
-0
lines changed

lib.rs

Lines changed: 41 additions & 0 deletions
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)