-
-
Notifications
You must be signed in to change notification settings - Fork 237
Speed up creating and extending packed arrays from iterators up to 63× #1023
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,122 @@ | ||
/* | ||
* Copyright (c) godot-rust; Bromeon and contributors. | ||
* This Source Code Form is subject to the terms of the Mozilla Public | ||
* License, v. 2.0. If a copy of the MPL was not distributed with this | ||
* file, You can obtain one at https://mozilla.org/MPL/2.0/. | ||
*/ | ||
|
||
use std::mem::MaybeUninit; | ||
use std::ptr; | ||
|
||
/// A fixed-size buffer that does not do any allocations, and can hold up to `N` elements of type `T`. | ||
/// | ||
/// This is used to implement `Packed*Array::extend()` in an efficient way, because it forms a middle ground between | ||
/// repeated `push()` calls (slow) and first collecting the entire `Iterator` into a `Vec` (faster, but takes more memory). | ||
/// | ||
/// Note that `N` must not be 0 for the buffer to be useful. This is checked at compile time. | ||
pub struct ExtendBuffer<T, const N: usize> { | ||
buf: [MaybeUninit<T>; N], | ||
len: usize, | ||
} | ||
|
||
impl<T, const N: usize> Default for ExtendBuffer<T, N> { | ||
fn default() -> Self { | ||
Self { | ||
buf: [const { MaybeUninit::uninit() }; N], | ||
len: 0, | ||
} | ||
} | ||
} | ||
|
||
impl<T, const N: usize> ExtendBuffer<T, N> { | ||
/// Appends the given value to the buffer. | ||
/// | ||
/// # Panics | ||
/// If the buffer is full. | ||
pub fn push(&mut self, value: T) { | ||
self.buf[self.len].write(value); | ||
self.len += 1; | ||
} | ||
|
||
/// Returns `true` iff the buffer is full. | ||
pub fn is_full(&self) -> bool { | ||
self.len == N | ||
} | ||
|
||
/// Returns a slice of all initialized elements in the buffer, and sets the length of the buffer back to 0. | ||
/// | ||
/// It is the caller's responsibility to ensure that all elements in the returned slice get dropped! | ||
pub fn drain_as_mut_slice(&mut self) -> &mut [T] { | ||
// Prevent panic in self.buf[0] below. | ||
if N == 0 { | ||
return &mut []; | ||
} | ||
debug_assert!(self.len <= N); | ||
|
||
let len = self.len; | ||
self.len = 0; | ||
|
||
// MaybeUninit::slice_assume_init_ref could be used here instead, but it's experimental. | ||
// | ||
// SAFETY: | ||
// - The pointer is non-null, valid and aligned. | ||
// - `len` elements are always initialized. | ||
// - The memory is not accessed through any other pointer, because we hold a `&mut` reference to `self`. | ||
// - `len * mem::size_of::<T>()` is no larger than `isize::MAX`, otherwise the `buf` slice could not have existed either. | ||
unsafe { std::slice::from_raw_parts_mut(self.buf[0].as_mut_ptr(), len) } | ||
} | ||
} | ||
|
||
impl<T, const N: usize> Drop for ExtendBuffer<T, N> { | ||
fn drop(&mut self) { | ||
// Prevent panic in self.buf[0] below. | ||
if N == 0 { | ||
return; | ||
} | ||
debug_assert!(self.len <= N); | ||
|
||
// SAFETY: `slice_from_raw_parts_mut` by itself is not unsafe, but to make the resulting slice safe to use: | ||
// - `self.buf[0]` is a valid pointer, exactly `self.len` elements are initialized. | ||
// - The pointer is not aliased since we have an exclusive `&mut self`. | ||
let slice = ptr::slice_from_raw_parts_mut(self.buf[0].as_mut_ptr(), self.len); | ||
|
||
// SAFETY: the value is valid because the `slice_from_raw_parts_mut` requirements are met, | ||
// and there is no other way to access the value. | ||
unsafe { | ||
ptr::drop_in_place(slice); | ||
} | ||
} | ||
} | ||
|
||
#[test] | ||
fn test_extend_buffer_drop() { | ||
// We use an `Rc` to test the buffer's `drop` behavior. | ||
use std::rc::Rc; | ||
|
||
let mut buf = ExtendBuffer::<Rc<i32>, 1>::default(); | ||
let value = Rc::new(42); | ||
buf.push(Rc::clone(&value)); | ||
|
||
// The buffer contains one strong reference, this function contains another. | ||
assert_eq!(Rc::strong_count(&value), 2); | ||
|
||
let slice = buf.drain_as_mut_slice(); | ||
|
||
// The strong reference has been returned in the slice, but not dropped. | ||
assert_eq!(Rc::strong_count(&value), 2); | ||
|
||
// SAFETY: | ||
// - The slice returned by `drain_as_mut_slice` is valid, and therefore so is its first element. | ||
// - There is no way to access parts of `slice[0]` while `drop_in_place` is executing. | ||
unsafe { | ||
ptr::drop_in_place(&mut slice[0]); | ||
} | ||
|
||
// The reference held by the slice has now been dropped. | ||
assert_eq!(Rc::strong_count(&value), 1); | ||
|
||
drop(buf); | ||
|
||
// The buffer has not dropped another reference. | ||
assert_eq!(Rc::strong_count(&value), 1); | ||
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -7,6 +7,7 @@ | |
|
||
mod array; | ||
mod dictionary; | ||
mod extend_buffer; | ||
mod packed_array; | ||
|
||
// Re-export in godot::builtin. | ||
|
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.