Skip to content

Commit b0702c8

Browse files
Merge pull request #59 from triblespace/codex/implement-zerocopy-traits-for-section-handles
Implement zerocopy traits for SectionHandle
2 parents ab89139 + af1c3fb commit b0702c8

File tree

3 files changed

+32
-0
lines changed

3 files changed

+32
-0
lines changed

CHANGELOG.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
11
# Changelog
22

33
## Unreleased
4+
- derived zerocopy traits for `SectionHandle` to allow storing handles in `ByteArea` sections
45
- added example demonstrating `ByteArea` with multiple typed sections, concurrent mutations, and freezing or persisting the area
56
- added example combining Python bindings with winnow parsing
67
- added Python example demonstrating structured parsing with winnow's `view`

src/area.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,11 @@ where
241241

242242
/// Handle referencing a [`Section`] within a frozen [`ByteArea`].
243243
#[derive(Clone, Copy, Debug)]
244+
#[repr(C)]
245+
#[cfg_attr(
246+
feature = "zerocopy",
247+
derive(zerocopy::FromBytes, zerocopy::KnownLayout, zerocopy::Immutable,)
248+
)]
244249
pub struct SectionHandle<T> {
245250
/// Absolute byte offset from the start of the area.
246251
pub offset: usize,

tests/area.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -97,3 +97,29 @@ fn handles_reconstruct_sections() {
9797
assert_eq!(handle_a.view(&all).unwrap().as_ref(), &[1]);
9898
assert_eq!(handle_b.view(&all).unwrap().as_ref(), &[2]);
9999
}
100+
101+
#[test]
102+
fn handles_can_be_stored_in_sections() {
103+
use anybytes::area::SectionHandle;
104+
105+
let mut area = ByteArea::new().expect("area");
106+
let mut sections = area.sections();
107+
108+
let mut value = sections.reserve::<u8>(1).expect("reserve value");
109+
value.as_mut_slice()[0] = 3;
110+
let handle_value = value.handle();
111+
value.freeze().expect("freeze value");
112+
113+
let mut handles = sections
114+
.reserve::<SectionHandle<u8>>(1)
115+
.expect("reserve handles");
116+
handles.as_mut_slice()[0] = handle_value;
117+
let handle_handles = handles.handle();
118+
handles.freeze().expect("freeze handles");
119+
120+
drop(sections);
121+
let all = area.freeze().expect("freeze area");
122+
123+
let stored_handle = handle_handles.view(&all).expect("view handles").as_ref()[0];
124+
assert_eq!(stored_handle.view(&all).unwrap().as_ref(), &[3]);
125+
}

0 commit comments

Comments
 (0)