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
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
pub const MAGIC_NUM: u32 = 0xFD2F_B528;
pub const MIN_WINDOW_SIZE: u64 = 1024;
pub const MAX_WINDOW_SIZE: u64 = (1 << 41) + 7 * (1 << 38);

pub struct Frame {
    magic_num: u32,
    pub header: FrameHeader,
}

pub struct FrameHeader {
    pub descriptor: FrameDescriptor,
    window_descriptor: u8,
    dict_id: Vec<u8>,
    frame_content_size: Vec<u8>,
}

pub struct FrameDescriptor(u8);

impl FrameDescriptor {
    pub fn frame_content_size_flag(&self) -> u8 {
        self.0 >> 6
    }

    pub fn reserved_flag(&self) -> bool {
        ((self.0 >> 3) & 0x1) == 1
    }

    pub fn single_segment_flag(&self) -> bool {
        ((self.0 >> 5) & 0x1) == 1
    }

    pub fn content_checksum_flag(&self) -> bool {
        ((self.0 >> 2) & 0x1) == 1
    }

    pub fn dict_id_flag(&self) -> u8 {
        self.0 & 0x3
    }

    // Deriving info from the flags
    pub fn frame_content_size_bytes(&self) -> Result<u8, String> {
        match self.frame_content_size_flag() {
            0 => {
                if self.single_segment_flag() {
                    Ok(1)
                } else {
                    Ok(0)
                }
            }
            1 => Ok(2),
            2 => Ok(4),
            3 => Ok(8),
            _ => Err(format!(
                "Invalid Frame_Content_Size_Flag Is: {} Should be one of: 0,1,2,3",
                self.frame_content_size_flag()
            )),
        }
    }

    pub fn dictionary_id_bytes(&self) -> Result<u8, String> {
        match self.dict_id_flag() {
            0 => Ok(0),
            1 => Ok(1),
            2 => Ok(2),
            3 => Ok(4),
            _ => Err(format!(
                "Invalid Frame_Content_Size_Flag Is: {} Should be one of: 0,1,2,3",
                self.frame_content_size_flag()
            )),
        }
    }
}
impl FrameHeader {
    pub fn window_size(&self) -> Result<u64, String> {
        if self.descriptor.single_segment_flag() {
            match self.frame_content_size() {
                Ok(x) => Ok(x),
                Err(m) => Err(m),
            }
        } else {
            let exp = self.window_descriptor >> 3;
            let mantissa = self.window_descriptor & 0x7;

            let window_log = 10 + (exp as u64);
            let window_base = 1 << (window_log as u64);
            let window_add = (window_base / 8) * (mantissa as u64);

            let window_size = window_base + window_add;

            if window_size >= MIN_WINDOW_SIZE {
                if window_size < MAX_WINDOW_SIZE {
                    Ok(window_size)
                } else {
                    Err(format!(
                        "window_size bigger than allowed maximum. Is: {}, Should be lower than: {}",
                        window_size, MAX_WINDOW_SIZE
                    ))
                }
            } else {
                Err(format!(
                    "window_size smaller than allowed minimum. Is: {}, Should be greater than: {}",
                    window_size, MIN_WINDOW_SIZE
                ))
            }
        }
    }

    pub fn dictiornary_id(&self) -> Result<Option<u32>, String> {
        if self.descriptor.dict_id_flag() == 0 {
            Ok(None)
        } else {
            match self.descriptor.dictionary_id_bytes() {
                Err(m) => Err(m),
                Ok(bytes) => {
                    if self.dict_id.len() != bytes as usize {
                        Err(format!(
                            "Not enough bytes in dict_id. Is: {}, Should be: {}",
                            self.dict_id.len(),
                            bytes
                        ))
                    } else {
                        let mut value: u32 = 0;
                        let mut shift = 0;
                        for x in &self.dict_id {
                            value |= (*x as u32) << shift;
                            shift += 8;
                        }

                        Ok(Some(value))
                    }
                }
            }
        }
    }

    pub fn frame_content_size(&self) -> Result<u64, String> {
        match self.descriptor.frame_content_size_bytes() {
            Err(m) => Err(m),
            Ok(bytes) => match bytes {
                0 => Err("Bytes was zero".to_owned()),
                1 => {
                    if self.frame_content_size.len() == 1 {
                        Ok(u64::from(self.frame_content_size[0]))
                    } else {
                        Err(format!(
                            "frame_content_size not long enough. Is: {}, Should be: {}",
                            self.frame_content_size.len(),
                            bytes
                        ))
                    }
                }
                2 => {
                    if self.frame_content_size.len() == 2 {
                        let val = (u64::from(self.frame_content_size[1]) << 8)
                            + (u64::from(self.frame_content_size[0]));
                        Ok(val + 256) //this weird offset is from the documentation. Only if bytes == 2
                    } else {
                        Err(format!(
                            "frame_content_size not long enough. Is: {}, Should be: {}",
                            self.frame_content_size.len(),
                            bytes
                        ))
                    }
                }
                4 => {
                    if self.frame_content_size.len() == 4 {
                        let val = crate::decoding::little_endian::read_little_endian_u32(
                            self.frame_content_size.as_slice(),
                        );
                        Ok(u64::from(val))
                    } else {
                        Err(format!(
                            "frame_content_size not long enough. Is: {}, Should be: {}",
                            self.frame_content_size.len(),
                            bytes
                        ))
                    }
                }
                8 => {
                    if self.frame_content_size.len() == 8 {
                        let val = crate::decoding::little_endian::read_little_endian_u64(
                            &self.frame_content_size,
                        );
                        Ok(val)
                    } else {
                        Err(format!(
                            "frame_content_size not long enough. Is: {}, Should be: {}",
                            self.frame_content_size.len(),
                            bytes
                        ))
                    }
                }
                _ => Err(format!(
                    "Invalid amount of bytes'. Is: {}, Should be one of 1,2,4,8",
                    self.frame_content_size.len()
                )),
            },
        }
    }
}

impl Frame {
    pub fn check_valid(&self) -> Result<(), String> {
        if self.magic_num != MAGIC_NUM {
            Err(format!(
                "magic_num wrong. Is: {}. Should be: {}",
                self.magic_num, MAGIC_NUM
            ))
        } else if self.header.descriptor.reserved_flag() {
            Err("Reserved Flag set. Must be zero".to_string())
        } else {
            match self.header.dictiornary_id() {
                Ok(_) => match self.header.window_size() {
                    Ok(_) => {
                        if self.header.descriptor.single_segment_flag() {
                            match self.header.frame_content_size() {
                                Ok(_) => Ok(()),
                                Err(m) => Err(m),
                            }
                        } else {
                            Ok(())
                        }
                    }
                    Err(m) => Err(m),
                },
                Err(m) => Err(m),
            }
        }
    }
}

use std::io::Read;
pub fn read_frame_header(r: &mut dyn Read) -> Result<(Frame, u8), String> {
    let mut buf = [0u8; 4];
    let magic_num: u32 = match r.read_exact(&mut buf[0..4]) {
        Ok(_) => crate::decoding::little_endian::read_little_endian_u32(&buf[..]),
        Err(_) => return Err("Error while reading magic number".to_owned()),
    };

    let mut bytes_read = 4;

    let desc: FrameDescriptor = match r.read_exact(&mut buf[0..1]) {
        Ok(_) => FrameDescriptor(buf[0]),
        Err(_) => return Err("Error while reading frame descriptor".to_owned()),
    };

    bytes_read += 1;

    let mut frame_header = FrameHeader {
        descriptor: FrameDescriptor(desc.0),
        dict_id: match desc.dictionary_id_bytes() {
            Ok(bytes) => {
                let mut v = Vec::with_capacity(bytes as usize);
                for _ in 0..bytes {
                    v.push(0);
                }
                v
            }
            Err(m) => return Err(m),
        },
        frame_content_size: match desc.frame_content_size_bytes() {
            Ok(bytes) => {
                let mut v = Vec::with_capacity(bytes as usize);
                for _ in 0..bytes {
                    v.push(0);
                }
                v
            }
            Err(m) => return Err(m),
        },
        window_descriptor: 0,
    };

    if !desc.single_segment_flag() {
        match r.read_exact(&mut buf[0..1]) {
            Ok(_) => frame_header.window_descriptor = buf[0],
            Err(_) => return Err("Error while reading window descriptor".to_owned()),
        }
        bytes_read += 1;
    }

    if !frame_header.dict_id.is_empty() {
        match r.read_exact(&mut frame_header.dict_id.as_mut_slice()) {
            Ok(_) => {}
            Err(_) => return Err("Error while reading dcitionary id".to_owned()),
        }
        bytes_read += frame_header.dict_id.len();
    }

    if !frame_header.frame_content_size.is_empty() {
        match r.read_exact(&mut frame_header.frame_content_size.as_mut_slice()) {
            Ok(_) => {}
            Err(_) => return Err("Error while reading frame content size".to_owned()),
        }
        bytes_read += frame_header.frame_content_size.len();
    }

    let frame: Frame = Frame {
        magic_num,
        header: frame_header,
    };

    Ok((frame, bytes_read as u8))
}