-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbyte_area.rs
More file actions
43 lines (35 loc) · 1.42 KB
/
byte_area.rs
File metadata and controls
43 lines (35 loc) · 1.42 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
use anybytes::{area::ByteArea, Bytes};
use tempfile::tempdir;
fn main() -> std::io::Result<()> {
let mut area = ByteArea::new()?;
let mut sections = area.sections();
// Reserve two sections at once and mutate them independently.
let mut raw = sections.reserve::<u8>(4)?;
let mut nums = sections.reserve::<u32>(2)?;
raw.as_mut_slice().copy_from_slice(b"test");
nums.as_mut_slice().copy_from_slice(&[1, 2]);
// Store handles so we can later extract the sections from the frozen area.
let handle_raw = raw.handle();
let handle_nums = nums.handle();
// Freeze the sections into immutable `Bytes`.
let frozen_raw: Bytes = raw.freeze()?;
let frozen_nums: Bytes = nums.freeze()?;
assert_eq!(frozen_raw.as_ref(), b"test");
assert_eq!(frozen_nums.view::<[u32]>().unwrap().as_ref(), &[1, 2]);
drop(sections);
// Decide whether to keep the area in memory or persist it to disk.
let memory_or_file = true;
if memory_or_file {
// Freeze the whole area into immutable `Bytes`.
let all: Bytes = area.freeze()?;
assert_eq!(handle_raw.bytes(&all).as_ref(), frozen_raw.as_ref());
assert_eq!(handle_nums.view(&all).unwrap().as_ref(), &[1, 2]);
} else {
// Persist the temporary file.
let dir = tempdir()?;
let path = dir.path().join("area.bin");
area.persist(&path)?;
assert!(path.exists());
}
Ok(())
}