Skip to content

Commit

Permalink
fix From<AlignedVec> for AlignedBytes (openzfs#55)
Browse files Browse the repository at this point in the history
When a Vec is converted to Bytes, the excess capacity of the Vec is
dropped, by reallocating the Vec to be smaller and freeing the old
memory. When the Vec of an AlignedVec is converted to Bytes, we don't
want this to happen, becuase the new allocation won't necessarily have
the same alignment as the Vec's old buffer. Also it has a performance
impact of an additional alloc/bcopy/free, which is what we're trying to
avoid with the AlignedVec.

We can avoid this by setting the Vec's size the be the same as its
capacity before conversion. We also verify that it's buffer pointer
doesn't change across these operations.
  • Loading branch information
ahrens authored Dec 9, 2021
1 parent ac7cedc commit a14bc3f
Showing 1 changed file with 17 additions and 3 deletions.
20 changes: 17 additions & 3 deletions cmd/zfs_object_agent/util/src/vec_ext.rs
Original file line number Diff line number Diff line change
Expand Up @@ -63,10 +63,24 @@ impl From<AlignedBytes> for Bytes {
}

impl From<AlignedVec> for AlignedBytes {
fn from(aligned_vec: AlignedVec) -> Self {
fn from(mut aligned_vec: AlignedVec) -> Self {
aligned_vec.verify();
let ptr = aligned_vec.vec.as_ptr();
// resize so that there is no spare capacity, so that converting to Bytes will not reallocate
let raw_len = aligned_vec.vec.len();
aligned_vec.vec.resize(aligned_vec.vec.capacity(), 0);
assert_eq!(aligned_vec.vec.as_ptr(), ptr);
let unaligned_bytes: Bytes = aligned_vec.vec.into();
let bytes = unaligned_bytes.slice(aligned_vec.pad..);
assert_eq!(bytes.as_ptr().align_offset(aligned_vec.alignment), 0);
assert_eq!(unaligned_bytes.as_ptr(), ptr);
let bytes = unaligned_bytes.slice(aligned_vec.pad..raw_len);
assert_eq!(
bytes.as_ptr().align_offset(aligned_vec.alignment),
0,
"pointer {:?}+{} is not {}-aligned",
unaligned_bytes.as_ptr(),
aligned_vec.pad,
aligned_vec.alignment
);
AlignedBytes {
alignment: aligned_vec.alignment,
bytes,
Expand Down

0 comments on commit a14bc3f

Please sign in to comment.