|
| 1 | +use anybytes::{area::ByteArea, Bytes}; |
| 2 | +use tempfile::tempdir; |
| 3 | + |
| 4 | +fn main() -> std::io::Result<()> { |
| 5 | + let mut area = ByteArea::new()?; |
| 6 | + let mut sections = area.sections(); |
| 7 | + |
| 8 | + // Reserve two sections at once and mutate them independently. |
| 9 | + let mut raw = sections.reserve::<u8>(4)?; |
| 10 | + let mut nums = sections.reserve::<u32>(2)?; |
| 11 | + |
| 12 | + raw.as_mut_slice().copy_from_slice(b"test"); |
| 13 | + nums.as_mut_slice().copy_from_slice(&[1, 2]); |
| 14 | + |
| 15 | + // Freeze the sections into immutable `Bytes`. |
| 16 | + let frozen_raw: Bytes = raw.freeze()?; |
| 17 | + let frozen_nums: Bytes = nums.freeze()?; |
| 18 | + assert_eq!(frozen_raw.as_ref(), b"test"); |
| 19 | + assert_eq!(frozen_nums.view::<[u32]>().unwrap().as_ref(), &[1, 2]); |
| 20 | + |
| 21 | + drop(sections); |
| 22 | + |
| 23 | + // Decide whether to keep the area in memory or persist it to disk. |
| 24 | + let memory_or_file = true; |
| 25 | + if memory_or_file { |
| 26 | + // Freeze the whole area into immutable `Bytes`. |
| 27 | + let all: Bytes = area.freeze()?; |
| 28 | + assert_eq!(&all[..4], b"test"); |
| 29 | + assert_eq!(all.slice(4..).view::<[u32]>().unwrap().as_ref(), &[1, 2]); |
| 30 | + } else { |
| 31 | + // Persist the temporary file. |
| 32 | + let dir = tempdir()?; |
| 33 | + let path = dir.path().join("area.bin"); |
| 34 | + area.persist(&path)?; |
| 35 | + assert!(path.exists()); |
| 36 | + } |
| 37 | + |
| 38 | + Ok(()) |
| 39 | +} |
0 commit comments