Skip to content

Commit 58d68a1

Browse files
committed
add: extend_from_slice()
1 parent decaeed commit 58d68a1

File tree

2 files changed

+38
-0
lines changed

2 files changed

+38
-0
lines changed

src/lib.rs

+29
Original file line numberDiff line numberDiff line change
@@ -414,6 +414,13 @@ impl<H, T> HeaderVec<H, T> {
414414
unsafe { (self.ptr as *mut T).add(Self::offset()) }
415415
}
416416

417+
/// Gets the pointer to the end of the slice. This returns a mutable pointer to
418+
/// uninitialized memory behind the last element.
419+
#[inline(always)]
420+
fn end_ptr_mut(&mut self) -> *mut T {
421+
unsafe { self.start_ptr_mut().add(self.len_exact()) }
422+
}
423+
417424
#[inline(always)]
418425
fn header(&self) -> &HeaderVecHeader<H> {
419426
// The beginning of the memory is always the header.
@@ -427,6 +434,28 @@ impl<H, T> HeaderVec<H, T> {
427434
}
428435
}
429436

437+
impl<H, T: Clone> HeaderVec<H, T> {
438+
/// Adds items from a slice to the end of the list.
439+
///
440+
/// Returns `Some(*const ())` if the memory was moved to a new location.
441+
/// In this case, you are responsible for updating the weak nodes.
442+
pub fn extend_from_slice(&mut self, slice: &[T]) -> Option<*const ()> {
443+
let previous_pointer = self.reserve(slice.len());
444+
445+
// copy data
446+
let end_ptr = self.end_ptr_mut();
447+
for (index, item) in slice.iter().enumerate() {
448+
unsafe {
449+
core::ptr::write(end_ptr.add(index), item.clone());
450+
}
451+
}
452+
// correct the len
453+
self.header_mut().len = (self.len_exact() + slice.len()).into();
454+
455+
previous_pointer
456+
}
457+
}
458+
430459
#[cfg(feature = "atomic_append")]
431460
/// The atomic append API is only enabled when the `atomic_append` feature flag is set (which
432461
/// is the default).

tests/simple.rs

+9
Original file line numberDiff line numberDiff line change
@@ -53,3 +53,12 @@ fn test_push() {
5353
hv.push(123);
5454
assert_eq!(hv[0], 123);
5555
}
56+
57+
#[test]
58+
fn test_extend_from_slice() {
59+
let mut hv = HeaderVec::new(());
60+
61+
hv.extend_from_slice(&[0, 1, 2]);
62+
hv.extend_from_slice(&[3, 4, 5]);
63+
assert_eq!(hv.as_slice(), &[0, 1, 2, 3, 4, 5]);
64+
}

0 commit comments

Comments
 (0)