byr/crates/byr-core/src/changelist.rs
2022-10-15 13:48:32 +02:00

48 lines
1.4 KiB
Rust

use core::fmt;
use std::io::{Read, Result as IoResult, Write};
/// Note that the first entry has a special meaning, it is the anchor hash
/// a changelist may also be empty in degraded cases (e.g. in a root snapshot)
#[derive(Clone, Default)]
pub struct ChangeList(pub Vec<crate::ChangeHash>);
impl fmt::Debug for ChangeList {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
use yzb64::{base64, B64_ENGINE};
f.debug_list()
.entries(
self.0
.iter()
.map(|i| format!("{}", base64::display::Base64Display::from(i, &*B64_ENGINE))),
)
.finish()
}
}
impl ChangeList {
pub fn read_from_stream(f: &mut impl Read) -> IoResult<Self> {
let l = {
let mut lbuf = [0u8; 2];
f.read_exact(&mut lbuf)?;
u16::from_be_bytes(lbuf)
};
let lu = usize::from(l);
let mut ret = Vec::with_capacity(lu);
let mut buf = [0u8; 32];
for _ in 0..lu {
f.read_exact(&mut buf)?;
ret.push(buf);
}
Ok(Self(ret))
}
pub fn write_to_stream(&self, f: &mut impl Write) -> IoResult<()> {
let lbuf = u16::try_from(self.0.len())
.map_err(|e| std::io::Error::new(std::io::ErrorKind::InvalidData, e))?
.to_be_bytes();
f.write_all(&lbuf)?;
self.0.iter().try_for_each(|i| f.write_all(i))?;
Ok(())
}
}