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
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
use std::error::Error;
use std::path::Path;
use parking_lot::Mutex;
#[derive(Clone, Copy, Eq, PartialEq, Debug)]
pub struct Addr(pub u32);
impl Addr {
pub fn as_usize(self) -> usize {
self.0 as usize
}
}
pub trait SerializationSink: Sized + Send + Sync + 'static {
fn from_path(path: &Path) -> Result<Self, Box<dyn Error>>;
fn write_atomic<W>(&self, num_bytes: usize, write: W) -> Addr
where
W: FnOnce(&mut [u8]);
}
pub struct ByteVecSink {
data: Mutex<Vec<u8>>,
}
impl ByteVecSink {
pub fn new() -> ByteVecSink {
ByteVecSink {
data: Mutex::new(Vec::new()),
}
}
pub fn into_bytes(self) -> Vec<u8> {
self.data.into_inner()
}
}
impl SerializationSink for ByteVecSink {
fn from_path(_path: &Path) -> Result<Self, Box<dyn Error>> {
unimplemented!()
}
fn write_atomic<W>(&self, num_bytes: usize, write: W) -> Addr
where
W: FnOnce(&mut [u8]),
{
let mut data = self.data.lock();
let start = data.len();
data.resize(start + num_bytes, 0);
write(&mut data[start..]);
Addr(start as u32)
}
}
impl std::fmt::Debug for ByteVecSink {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "ByteVecSink")
}
}