use super::{Cid, Error, Version};
use integer_encoding::{VarIntReader, VarIntWriter};
use std::convert::TryFrom;
use std::io::Cursor;
#[derive(PartialEq, Eq, Clone, Debug)]
pub struct Prefix {
pub version: Version,
pub codec: u64,
pub mh_type: u64,
pub mh_len: usize,
}
impl Prefix {
pub fn new_from_bytes(data: &[u8]) -> Result<Prefix, Error> {
let mut cur = Cursor::new(data);
let raw_version: u64 = cur.read_varint()?;
let codec = cur.read_varint()?;
let mh_type: u64 = cur.read_varint()?;
let mh_len: usize = cur.read_varint()?;
let version = Version::try_from(raw_version)?;
Ok(Prefix {
version,
codec,
mh_type,
mh_len,
})
}
pub fn to_bytes(&self) -> Vec<u8> {
let mut res = Vec::with_capacity(4);
res.write_varint(u64::from(self.version)).unwrap();
res.write_varint(self.codec).unwrap();
res.write_varint(self.mh_type).unwrap();
res.write_varint(self.mh_len).unwrap();
res
}
}
impl From<Cid> for Prefix {
fn from(cid: Cid) -> Self {
Self {
version: cid.version(),
codec: cid.codec(),
mh_type: cid.hash().code(),
mh_len: cid.hash().size().into(),
}
}
}