Skip to content

Truly independent web browser

LibJS: Build a ThinSlice in place from an exactly sized iterator

Andreas Kling689e7d7f2339
diff --git a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
index c26646d52d5..e0df2e80e78 100644
--- a/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
+++ b/Libraries/LibJS/Rust/src/gc/interpreter_buffer.rs
@@ -167,6 +167,22 @@ impl<T> ThinSlice<T> {
}
}
+ /// Room for `length` elements, which is not empty, with their length in front of them. The elements are up to the
+ /// caller.
+ fn allocate(length: usize) -> *mut T {
+ let layout = Self::layout_for(length);
+ // SAFETY: The layout has a non-zero size. The allocation has room for the length, aligned for it and for the
+ // elements behind it.
+ unsafe {
+ let allocation = alloc(layout);
+ if allocation.is_null() {
+ handle_alloc_error(layout);
+ }
+ allocation.cast::<usize>().write(length);
+ allocation.add(THIN_SLICE_HEADER_SIZE).cast::<T>()
+ }
+ }
+
pub fn as_slice(&self) -> &[T] {
if self.data.is_null() {
return &[];
@@ -190,26 +206,33 @@ impl<T> From<Vec<T>> for ThinSlice<T> {
if length == 0 {
return Self::empty();
}
- let layout = Self::layout_for(length);
- // SAFETY: The layout has a non-zero size. The allocation has room for the length and for `length` elements,
- // aligned for them, which move out of the vector.
+ let data = Self::allocate(length);
+ // SAFETY: The allocation has room for `length` elements, which move out of the vector.
unsafe {
- let allocation = alloc(layout);
- if allocation.is_null() {
- handle_alloc_error(layout);
- }
- allocation.cast::<usize>().write(length);
- let data = allocation.add(THIN_SLICE_HEADER_SIZE).cast::<T>();
core::ptr::copy_nonoverlapping(elements.as_ptr(), data, length);
elements.set_len(0);
- Self::from_data(data)
}
+ Self::from_data(data)
}
}
impl<T> FromIterator<T> for ThinSlice<T> {
fn from_iter<I: IntoIterator<Item = T>>(iterator: I) -> Self {
- iterator.into_iter().collect::<Vec<T>>().into()
+ let mut iterator = iterator.into_iter();
+ let (length, upper_bound) = iterator.size_hint();
+ if upper_bound != Some(length) {
+ return iterator.collect::<Vec<T>>().into();
+ }
+ if length == 0 {
+ return Self::empty();
+ }
+ let data = Self::allocate(length);
+ for index in 0..length {
+ let element = iterator.next().expect("an iterator yields what its size hint says");
+ // SAFETY: The allocation has room for `length` elements.
+ unsafe { data.add(index).write(element) };
+ }
+ Self::from_data(data)
}
}