]> git.proxmox.com Git - rustc.git/blame - vendor/measureme/src/serialization.rs
New upstream version 1.41.1+dfsg1
[rustc.git] / vendor / measureme / src / serialization.rs
CommitLineData
48663c56
XL
1use std::error::Error;
2use std::path::Path;
60c5eb7d 3use parking_lot::Mutex;
48663c56
XL
4
5#[derive(Clone, Copy, Eq, PartialEq, Debug)]
6pub struct Addr(pub u32);
7
8impl Addr {
9 pub fn as_usize(self) -> usize {
10 self.0 as usize
11 }
12}
13
60c5eb7d 14pub trait SerializationSink: Sized + Send + Sync + 'static {
48663c56
XL
15 fn from_path(path: &Path) -> Result<Self, Box<dyn Error>>;
16
17 fn write_atomic<W>(&self, num_bytes: usize, write: W) -> Addr
18 where
19 W: FnOnce(&mut [u8]);
20}
21
60c5eb7d
XL
22/// A `SerializationSink` that writes to an internal `Vec<u8>` and can be
23/// converted into this raw `Vec<u8>`. This implementation is only meant to be
24/// used for testing and is not very efficient.
25pub struct ByteVecSink {
26 data: Mutex<Vec<u8>>,
27}
48663c56 28
60c5eb7d
XL
29impl ByteVecSink {
30 pub fn new() -> ByteVecSink {
31 ByteVecSink {
32 data: Mutex::new(Vec::new()),
48663c56 33 }
60c5eb7d 34 }
48663c56 35
60c5eb7d
XL
36 pub fn into_bytes(self) -> Vec<u8> {
37 self.data.into_inner()
48663c56 38 }
60c5eb7d 39}
48663c56 40
60c5eb7d
XL
41impl SerializationSink for ByteVecSink {
42 fn from_path(_path: &Path) -> Result<Self, Box<dyn Error>> {
43 unimplemented!()
44 }
48663c56 45
60c5eb7d
XL
46 fn write_atomic<W>(&self, num_bytes: usize, write: W) -> Addr
47 where
48 W: FnOnce(&mut [u8]),
49 {
50 let mut data = self.data.lock();
48663c56 51
60c5eb7d 52 let start = data.len();
48663c56 53
60c5eb7d 54 data.resize(start + num_bytes, 0);
48663c56 55
60c5eb7d 56 write(&mut data[start..]);
48663c56 57
60c5eb7d 58 Addr(start as u32)
48663c56 59 }
60c5eb7d 60}
48663c56 61
60c5eb7d
XL
62impl std::fmt::Debug for ByteVecSink {
63 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
64 write!(f, "ByteVecSink")
48663c56
XL
65 }
66}