aboutsummaryrefslogtreecommitdiff
path: root/ebml/src/write.rs
blob: f57a5c994231478a5bfaf3dcd33b1edd1f1df2de (plain)
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
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
use anyhow::{bail, Result};
use std::io::Write;

use crate::{matroska::MatroskaTag, size::EbmlSize, Master};

pub struct EbmlWriter {
    inner: Box<dyn Write>,
    position: usize,
}

impl EbmlWriter {
    pub fn new<T: Write + 'static>(inner: T, position: usize) -> Self {
        Self {
            inner: Box::new(inner),
            position,
        }
    }

    pub fn write(&mut self, data: &[u8]) -> Result<()> {
        self.inner.write_all(data)?;
        self.position += data.len();
        Ok(())
    }

    pub fn write_tag(&mut self, tag: &MatroskaTag) -> Result<()> {
        self.write_tag_id(tag.id())?;
        let mut buf = vec![];
        tag.write(&mut buf)?;
        self.write(&buf)?;
        Ok(())
    }

    pub fn write_tag_id(&mut self, id: u64) -> Result<()> {
        for n in id.to_be_bytes().iter().skip_while(|&v| *v == 0u8) {
            self.write(&[*n])?;
        }
        Ok(())
    }

    pub fn write_vint(&mut self, i: u64) -> Result<()> {
        if i > (1 << 56) - 1 {
            bail!("vint does not fit");
        }
        let mut len = 1;
        while len <= 8 {
            if i < (1 << ((7 * len) - 1)) {
                break;
            }
            len += 1;
        }
        let mut bytes = i.to_be_bytes();
        let trunc = &mut bytes[(8 - len)..];
        trunc[0] |= 1 << (8 - len);
        self.write(&trunc)
    }
}

pub trait WriteValue {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<()>;
}

impl WriteValue for i64 {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<()> {
        Ok(match 64 - self.leading_zeros() {
            x if x <= 8 => {
                w.push(0x81);
                w.extend_from_slice(&(*self as i8).to_be_bytes());
            }
            x if x <= 16 => {
                w.push(0x82);
                w.extend_from_slice(&(*self as i16).to_be_bytes());
            }
            x if x <= 32 => {
                w.push(0x84);
                w.extend_from_slice(&(*self as i32).to_be_bytes());
            }
            _ => {
                w.push(0x88);
                w.extend_from_slice(&self.to_be_bytes());
            }
        })
    }
}
impl WriteValue for u64 {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<()> {
        Ok(match 64 - self.leading_zeros() {
            x if x <= 8 => {
                w.push(0x81);
                w.extend_from_slice(&(*self as u8).to_be_bytes());
            }
            x if x <= 16 => {
                w.push(0x82);
                w.extend_from_slice(&(*self as u16).to_be_bytes());
            }
            x if x <= 32 => {
                w.push(0x84);
                w.extend_from_slice(&(*self as u32).to_be_bytes());
            }
            _ => {
                w.push(0x88);
                w.extend_from_slice(&self.to_be_bytes());
            }
        })
    }
}
impl WriteValue for f64 {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<(), anyhow::Error> {
        w.push(0x88);
        w.extend_from_slice(&self.to_be_bytes());
        Ok(())
    }
}
impl WriteValue for Vec<u8> {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<(), anyhow::Error> {
        write_vint(w, self.len() as u64)?;
        w.extend_from_slice(&self);
        Ok(())
    }
}
impl WriteValue for String {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<(), anyhow::Error> {
        let sl = self.as_bytes();
        write_vint(w, sl.len() as u64)?;
        w.extend_from_slice(sl);
        Ok(())
    }
}
impl WriteValue for EbmlSize {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<()> {
        match self {
            EbmlSize::Exact(s) => write_vint(w, *s as u64)?,
            EbmlSize::Unknown => w.extend_from_slice(&(u64::MAX >> 7).to_be_bytes()),
        }
        Ok(())
    }
}

impl WriteValue for Master {
    fn write_to(&self, w: &mut Vec<u8>) -> Result<()> {
        match self {
            Master::Start(size) => size.write_to(w),
            Master::End => Ok(()),
        }
    }
}

pub fn write_vint(w: &mut Vec<u8>, i: u64) -> Result<()> {
    if i > (1 << 56) - 1 {
        bail!("vint does not fit");
    }
    let mut len = 1;
    while len <= 8 {
        if i < (1 << ((7 * len) - 1)) {
            break;
        }
        len += 1;
    }
    let mut bytes = i.to_be_bytes();
    let trunc = &mut bytes[(8 - len)..];
    trunc[0] |= 1 << (8 - len);
    w.extend_from_slice(&trunc);
    Ok(())
}