mkv_element/
io.rs

1use super::*;
2use crate::{base::Header, element::Element, functional::Encode};
3use std::io::{Read, Write};
4
5/// Read a type from a reader.
6/// Can be implemented for types that can be read without knowing their size beforehand.
7pub trait ReadFrom: Sized {
8    /// Read Self from a reader.
9    fn read_from<R: Read>(r: &mut R) -> Result<Self>;
10}
11
12/// implemented for all `Element`s.
13pub trait ReadElement: Sized + Element {
14    /// Read an element from a reader provided the header.
15    fn read_element<R: Read>(header: &Header, r: &mut R) -> Result<Self> {
16        let body = header.read_body(r)?;
17        Self::decode_body(&mut &body[..])
18    }
19}
20impl<T: Element> ReadElement for T {}
21
22/// Read until Self is found
23pub trait ReadUntil: Sized {
24    /// Read until Self is found
25    fn read_until<R: Read>(r: &mut R) -> Result<Self>;
26}
27
28/// Write to a writer.
29pub trait WriteTo {
30    /// Write an element to a writer.
31    fn write_to<W: Write>(&self, w: &mut W) -> Result<()>;
32}
33
34impl<T: Encode> WriteTo for T {
35    fn write_to<W: Write>(&self, w: &mut W) -> Result<()> {
36        //TODO should avoid the extra allocation here
37        let mut buf = vec![];
38        self.encode(&mut buf)?;
39        w.write_all(&buf)?;
40        Ok(())
41    }
42}
43
44/// Extension trait for `std::io::Read` to read primitive types.
45pub trait ReadExt: Read {
46    /// Read a single byte.
47    fn read_u8(&mut self) -> Result<u8> {
48        let mut buf = [0u8; 1];
49        self.read_exact(&mut buf)?;
50        Ok(buf[0])
51    }
52}
53impl<T: Read> ReadExt for T {}