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
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
use bytes::{Buf, BufMut};

use super::{
    parse_error::ParseError,
    prefix_int::{self, Error as IntError},
    prefix_string::{self, Error as StringError},
};

// 4.3. Encoder Instructions
pub enum EncoderInstruction {
    // 4.3.1. Set Dynamic Table Capacity
    // An encoder informs the decoder of a change to the dynamic table capacity.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 | 1 |   Capacity (5+)   |
    // +---+---+---+-------------------+
    DynamicTableSizeUpdate,
    // 4.3.2. Insert With Name Reference
    // An encoder adds an entry to the dynamic table where the field name
    // matches the field name of an entry stored in the static or the dynamic
    // table.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 1 | T |    Name Index (6+)    |
    // +---+---+-----------------------+
    // | H |     Value Length (7+)     |
    // +---+---------------------------+
    // |  Value String (Length bytes)  |
    // +-------------------------------+
    InsertWithNameRef,
    // 4.3.3. Insert With Literal Name
    // An encoder adds an entry to the dynamic table where both the field name
    // and the field value are represented as string literals.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 1 | H | Name Length (5+)  |
    // +---+---+---+-------------------+
    // |  Name String (Length bytes)   |
    // +---+---------------------------+
    // | H |     Value Length (7+)     |
    // +---+---------------------------+
    // |  Value String (Length bytes)  |
    // +-------------------------------+
    InsertWithoutNameRef,
    // 4.3.4. Duplicate
    // An encoder duplicates an existing entry in the dynamic table.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 | 0 |    Index (5+)     |
    // +---+---+---+-------------------+
    Duplicate,
    Unknown,
}

impl EncoderInstruction {
    pub fn decode(first: u8) -> Self {
        if first & 0b1000_0000 != 0 {
            EncoderInstruction::InsertWithNameRef
        } else if first & 0b0100_0000 == 0b0100_0000 {
            EncoderInstruction::InsertWithoutNameRef
        } else if first & 0b1110_0000 == 0 {
            EncoderInstruction::Duplicate
        } else if first & 0b0010_0000 == 0b0010_0000 {
            EncoderInstruction::DynamicTableSizeUpdate
        } else {
            EncoderInstruction::Unknown
        }
    }
}

#[derive(Debug, PartialEq)]
pub enum InsertWithNameRef {
    Static { index: usize, value: Vec<u8> },
    Dynamic { index: usize, value: Vec<u8> },
}

impl InsertWithNameRef {
    pub fn new_static<T: Into<Vec<u8>>>(index: usize, value: T) -> Self {
        InsertWithNameRef::Static {
            index,
            value: value.into(),
        }
    }

    pub fn new_dynamic<T: Into<Vec<u8>>>(index: usize, value: T) -> Self {
        InsertWithNameRef::Dynamic {
            index,
            value: value.into(),
        }
    }

    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let (flags, index) = match prefix_int::decode(6, buf) {
            Ok((f, x)) if f & 0b10 == 0b10 => (f, x),
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };

        let value = match prefix_string::decode(8, buf) {
            Ok(x) => x,
            Err(StringError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };

        if flags & 0b01 == 0b01 {
            Ok(Some(InsertWithNameRef::new_static(index, value)))
        } else {
            Ok(Some(InsertWithNameRef::new_dynamic(index, value)))
        }
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) -> Result<(), prefix_string::Error> {
        match self {
            InsertWithNameRef::Static { index, value } => {
                prefix_int::encode(6, 0b11, *index, buf);
                prefix_string::encode(8, 0, value, buf)?;
            }
            InsertWithNameRef::Dynamic { index, value } => {
                prefix_int::encode(6, 0b10, *index, buf);
                prefix_string::encode(8, 0, value, buf)?;
            }
        }
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub struct InsertWithoutNameRef {
    pub name: Vec<u8>,
    pub value: Vec<u8>,
}

impl InsertWithoutNameRef {
    pub fn new<T: Into<Vec<u8>>>(name: T, value: T) -> Self {
        Self {
            name: name.into(),
            value: value.into(),
        }
    }

    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let name = match prefix_string::decode(6, buf) {
            Ok(x) => x,
            Err(StringError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        let value = match prefix_string::decode(8, buf) {
            Ok(x) => x,
            Err(StringError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(Self::new(name, value)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) -> Result<(), prefix_string::Error> {
        prefix_string::encode(6, 0b01, &self.name, buf)?;
        prefix_string::encode(8, 0, &self.value, buf)?;
        Ok(())
    }
}

#[derive(Debug, PartialEq)]
pub struct Duplicate(pub usize);

impl Duplicate {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let index = match prefix_int::decode(5, buf) {
            Ok((0, x)) => x,
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(Duplicate(index)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(5, 0, self.0, buf);
    }
}

#[derive(Debug, PartialEq)]
pub struct DynamicTableSizeUpdate(pub usize);

impl DynamicTableSizeUpdate {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let size = match prefix_int::decode(5, buf) {
            Ok((0b001, x)) => x,
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(DynamicTableSizeUpdate(size)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(5, 0b001, self.0, buf);
    }
}

// 4.4. Decoder Instructions
// A decoder sends decoder instructions on the decoder stream to inform the encoder
// about the processing of field sections and table updates to ensure consistency
// of the dynamic table.
#[derive(Debug, PartialEq)]
pub enum DecoderInstruction {
    // 4.4.1. Section Acknowledgement
    // Acknowledge processing of an encoded field section whose declared Required
    // Insert Count is not zero.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 1 |      Stream ID (7+)       |
    // +---+---------------------------+
    HeaderAck,
    // 4.4.2. Stream Cancellation
    // When a stream is reset or reading is abandoned.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 1 |     Stream ID (6+)    |
    // +---+---+-----------------------+
    StreamCancel,
    //  4.4.3. Insert Count Increment
    //  Increases the Known Received Count to the total number of dynamic table
    //  insertions and duplications processed so far.
    //   0   1   2   3   4   5   6   7
    // +---+---+---+---+---+---+---+---+
    // | 0 | 0 |     Increment (6+)    |
    // +---+---+-----------------------+
    InsertCountIncrement,
    Unknown,
}

impl DecoderInstruction {
    pub fn decode(first: u8) -> Self {
        if first & 0b1100_0000 == 0 {
            DecoderInstruction::InsertCountIncrement
        } else if first & 0b1000_0000 != 0 {
            DecoderInstruction::HeaderAck
        } else if first & 0b0100_0000 == 0b0100_0000 {
            DecoderInstruction::StreamCancel
        } else {
            DecoderInstruction::Unknown
        }
    }
}

#[derive(Debug, PartialEq)]
pub struct InsertCountIncrement(pub usize);

impl InsertCountIncrement {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let insert_count = match prefix_int::decode(6, buf) {
            Ok((0b00, x)) => x,
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(InsertCountIncrement(insert_count)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(6, 0b00, self.0, buf);
    }
}

#[derive(Debug, PartialEq)]
pub struct HeaderAck(pub u64);

impl HeaderAck {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let stream_id = match prefix_int::decode(7, buf) {
            Ok((0b1, x)) => x as u64,
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(HeaderAck(stream_id)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(7, 0b1, self.0 as usize, buf);
    }
}

#[derive(Debug, PartialEq)]
pub struct StreamCancel(pub u64);

impl StreamCancel {
    pub fn decode<R: Buf>(buf: &mut R) -> Result<Option<Self>, ParseError> {
        let stream_id = match prefix_int::decode(6, buf) {
            Ok((0b01, x)) => x as u64,
            Ok((f, _)) => return Err(ParseError::InvalidPrefix(f)),
            Err(IntError::UnexpectedEnd) => return Ok(None),
            Err(e) => return Err(e.into()),
        };
        Ok(Some(StreamCancel(stream_id)))
    }

    pub fn encode<W: BufMut>(&self, buf: &mut W) {
        prefix_int::encode(6, 0b01, self.0 as usize, buf);
    }
}

#[cfg(test)]
mod test {
    use super::*;
    use std::io::Cursor;

    #[test]
    fn insert_with_name_ref() {
        let instruction = InsertWithNameRef::new_static(0, "value");
        let mut buf = vec![];
        instruction.encode(&mut buf).unwrap();
        let mut read = Cursor::new(&buf);
        assert_eq!(InsertWithNameRef::decode(&mut read), Ok(Some(instruction)));
    }

    #[test]
    fn insert_without_name_ref() {
        let instruction = InsertWithoutNameRef::new("name", "value");
        let mut buf = vec![];
        instruction.encode(&mut buf).unwrap();
        let mut read = Cursor::new(&buf);
        assert_eq!(
            InsertWithoutNameRef::decode(&mut read),
            Ok(Some(instruction))
        );
    }

    #[test]
    fn insert_duplicate() {
        let instruction = Duplicate(42);
        let mut buf = vec![];
        instruction.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(Duplicate::decode(&mut read), Ok(Some(instruction)));
    }

    #[test]
    fn dynamic_table_size_update() {
        let instruction = DynamicTableSizeUpdate(42);
        let mut buf = vec![];
        instruction.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(
            DynamicTableSizeUpdate::decode(&mut read),
            Ok(Some(instruction))
        );
    }

    #[test]
    fn insert_count_increment() {
        let instruction = InsertCountIncrement(42);
        let mut buf = vec![];
        instruction.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(
            InsertCountIncrement::decode(&mut read),
            Ok(Some(instruction))
        );
    }

    #[test]
    fn header_ack() {
        let instruction = HeaderAck(42);
        let mut buf = vec![];
        instruction.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(HeaderAck::decode(&mut read), Ok(Some(instruction)));
    }

    #[test]
    fn stream_cancel() {
        let instruction = StreamCancel(42);
        let mut buf = vec![];
        instruction.encode(&mut buf);
        let mut read = Cursor::new(&buf);
        assert_eq!(StreamCancel::decode(&mut read), Ok(Some(instruction)));
    }
}