Skip to content

Commit

Permalink
add as_mut_slices to ReadChunk (#100)
Browse files Browse the repository at this point in the history
  • Loading branch information
raftario authored Jul 6, 2023
1 parent 8de9512 commit 2e01e71
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 0 deletions.
19 changes: 19 additions & 0 deletions src/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -643,6 +643,25 @@ impl<T> ReadChunk<'_, T> {
)
}

/// Returns two mutable slices for reading from the requested slots.
///
/// This has the same semantics as [`as_slices()`](ReadChunk::as_slices),
/// except that it returns mutable slices and requires a mutable reference
/// to the chunk.
///
/// In the vast majority of cases, mutable access is not required when
/// reading data and the immutable version should be preferred. However,
/// there are some scenarios where it might be desirable to perform
/// operations on the data in-place without copying it to a separate buffer
/// (e.g. streaming decryption), in which case this version can be used.
#[must_use]
pub fn as_mut_slices(&mut self) -> (&mut [T], &mut [T]) {
(
unsafe { core::slice::from_raw_parts_mut(self.first_ptr, self.first_len) },
unsafe { core::slice::from_raw_parts_mut(self.second_ptr, self.second_len) },
)
}

/// Drops the first `n` slots of the chunk, making the space available for writing again.
///
/// # Panics
Expand Down
35 changes: 35 additions & 0 deletions tests/chunks.rs
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,41 @@ fn zero_capacity() {
}
}

#[test]
fn single_capacity() {
let (mut p, mut c) = RingBuffer::<i32>::new(1);

if let Ok(mut chunk) = p.write_chunk(1) {
assert_eq!(chunk.len(), 1);
assert!(!chunk.is_empty());
let (first, second) = chunk.as_mut_slices();
first[0] = 2;
assert!(second.is_empty());
chunk.commit_all();
} else {
unreachable!();
}

if let Ok(mut chunk) = c.read_chunk(1) {
assert_eq!(chunk.len(), 1);
assert!(!chunk.is_empty());
{
let (first, second) = chunk.as_mut_slices();
assert_eq!(first[0], 2);
first[0] *= 2;
assert!(second.is_empty());
}
{
let (first, second) = chunk.as_slices();
assert_eq!(first[0], 4);
assert!(second.is_empty());
}
chunk.commit_all();
} else {
unreachable!();
}
}

#[test]
fn drop_write_chunk() {
// Static variable to count all drop() invocations
Expand Down

0 comments on commit 2e01e71

Please sign in to comment.