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
use std::convert::{From, TryFrom, TryInto};

use async_trait::async_trait;
#[cfg(feature = "async")]
use futures::io::{AsyncRead, AsyncReadExt};

use super::super::varint::VarIntAsyncReader;

use super::compact::{
    collection_u8_to_type, u8_to_type, COMPACT_PROTOCOL_ID, COMPACT_VERSION, COMPACT_VERSION_MASK,
};
use super::{
    TFieldIdentifier, TInputStreamProtocol, TListIdentifier, TMapIdentifier, TMessageIdentifier,
    TMessageType,
};
use super::{TSetIdentifier, TStructIdentifier, TType};
use crate::thrift::{Error, ProtocolError, ProtocolErrorKind, Result};

#[derive(Debug)]
pub struct TCompactInputStreamProtocol<R: Send> {
    // Identifier of the last field deserialized for a struct.
    last_read_field_id: i16,
    // Stack of the last read field ids (a new entry is added each time a nested struct is read).
    read_field_id_stack: Vec<i16>,
    // Boolean value for a field.
    // Saved because boolean fields and their value are encoded in a single byte,
    // and reading the field only occurs after the field id is read.
    pending_read_bool_value: Option<bool>,
    // Underlying reader used for byte-level operations.
    reader: R,
    // remaining bytes that can be read before refusing to read more
    remaining: usize,
}

impl<R: VarIntAsyncReader + AsyncRead + Unpin + Send> TCompactInputStreamProtocol<R> {
    /// Create a `TCompactInputProtocol` that reads bytes from `reader`.
    pub fn new(reader: R, max_bytes: usize) -> Self {
        Self {
            last_read_field_id: 0,
            read_field_id_stack: Vec::new(),
            pending_read_bool_value: None,
            remaining: max_bytes,
            reader,
        }
    }

    fn update_remaining<T>(&mut self, element: usize) -> Result<()> {
        self.remaining = self
            .remaining
            .checked_sub((element).saturating_mul(std::mem::size_of::<T>()))
            .ok_or_else(|| {
                Error::Protocol(ProtocolError {
                    kind: ProtocolErrorKind::SizeLimit,
                    message: "The thrift file would allocate more bytes than allowed".to_string(),
                })
            })?;
        Ok(())
    }

    async fn read_list_set_begin(&mut self) -> Result<(TType, u32)> {
        let header = self.read_byte().await?;
        let element_type = collection_u8_to_type(header & 0x0F)?;

        let possible_element_count = (header & 0xF0) >> 4;
        let element_count = if possible_element_count != 15 {
            // high bits set high if count and type encoded separately
            possible_element_count.into()
        } else {
            self.reader.read_varint_async::<u32>().await?
        };

        self.update_remaining::<usize>(element_count.try_into()?)?;

        Ok((element_type, element_count))
    }
}

#[async_trait]
impl<R: VarIntAsyncReader + AsyncRead + Unpin + Send> TInputStreamProtocol
    for TCompactInputStreamProtocol<R>
{
    async fn read_message_begin(&mut self) -> Result<TMessageIdentifier> {
        let compact_id = self.read_byte().await?;
        if compact_id != COMPACT_PROTOCOL_ID {
            Err(Error::Protocol(ProtocolError {
                kind: ProtocolErrorKind::BadVersion,
                message: format!("invalid compact protocol header {:?}", compact_id),
            }))
        } else {
            Ok(())
        }?;

        let type_and_byte = self.read_byte().await?;
        let received_version = type_and_byte & COMPACT_VERSION_MASK;
        if received_version != COMPACT_VERSION {
            Err(Error::Protocol(ProtocolError {
                kind: ProtocolErrorKind::BadVersion,
                message: format!(
                    "cannot process compact protocol version {:?}",
                    received_version
                ),
            }))
        } else {
            Ok(())
        }?;

        // NOTE: unsigned right shift will pad with 0s
        let message_type: TMessageType = TMessageType::try_from(type_and_byte >> 5)?;
        let sequence_number = self.reader.read_varint_async::<u32>().await?;
        let service_call_name = self.read_string().await?;

        self.last_read_field_id = 0;

        Ok(TMessageIdentifier::new(
            service_call_name,
            message_type,
            sequence_number,
        ))
    }

    async fn read_message_end(&mut self) -> Result<()> {
        Ok(())
    }

    async fn read_struct_begin(&mut self) -> Result<Option<TStructIdentifier>> {
        self.read_field_id_stack.push(self.last_read_field_id);
        self.last_read_field_id = 0;
        Ok(None)
    }

    async fn read_struct_end(&mut self) -> Result<()> {
        self.last_read_field_id = self
            .read_field_id_stack
            .pop()
            .expect("should have previous field ids");
        Ok(())
    }

    async fn read_field_begin(&mut self) -> Result<TFieldIdentifier> {
        // we can read at least one byte, which is:
        // - the type
        // - the field delta and the type
        let field_type = self.read_byte().await?;
        let field_delta = (field_type & 0xF0) >> 4;
        let field_type = match field_type & 0x0F {
            0x01 => {
                self.pending_read_bool_value = Some(true);
                Ok(TType::Bool)
            }
            0x02 => {
                self.pending_read_bool_value = Some(false);
                Ok(TType::Bool)
            }
            ttu8 => u8_to_type(ttu8),
        }?;

        match field_type {
            TType::Stop => Ok(
                TFieldIdentifier::new::<Option<String>, String, Option<i16>>(
                    None,
                    TType::Stop,
                    None,
                ),
            ),
            _ => {
                if field_delta != 0 {
                    self.last_read_field_id = self
                        .last_read_field_id
                        .checked_add(field_delta as i16)
                        .ok_or(Error::Protocol(ProtocolError {
                            kind: ProtocolErrorKind::DepthLimit,
                            message: String::new(),
                        }))?;
                } else {
                    self.last_read_field_id = self.read_i16().await?;
                };

                Ok(TFieldIdentifier {
                    name: None,
                    field_type,
                    id: Some(self.last_read_field_id),
                })
            }
        }
    }

    async fn read_field_end(&mut self) -> Result<()> {
        Ok(())
    }

    async fn read_bool(&mut self) -> Result<bool> {
        match self.pending_read_bool_value.take() {
            Some(b) => Ok(b),
            None => {
                let b = self.read_byte().await?;
                match b {
                    0x01 => Ok(true),
                    0x02 => Ok(false),
                    unkn => Err(Error::Protocol(ProtocolError {
                        kind: ProtocolErrorKind::InvalidData,
                        message: format!("cannot convert {} into bool", unkn),
                    })),
                }
            }
        }
    }

    async fn read_bytes(&mut self) -> Result<Vec<u8>> {
        let len = self.reader.read_varint_async::<u32>().await?;

        self.update_remaining::<u8>(len.try_into()?)?;

        let mut buf = vec![];
        buf.try_reserve(len.try_into()?)?;
        (&mut self.reader)
            .take(len.try_into()?)
            .read_to_end(&mut buf)
            .await?;
        Ok(buf)
    }

    async fn read_i8(&mut self) -> Result<i8> {
        self.read_byte().await.map(|i| i as i8)
    }

    async fn read_i16(&mut self) -> Result<i16> {
        self.reader
            .read_varint_async::<i16>()
            .await
            .map_err(From::from)
    }

    async fn read_i32(&mut self) -> Result<i32> {
        self.reader
            .read_varint_async::<i32>()
            .await
            .map_err(From::from)
    }

    async fn read_i64(&mut self) -> Result<i64> {
        self.reader
            .read_varint_async::<i64>()
            .await
            .map_err(From::from)
    }

    async fn read_double(&mut self) -> Result<f64> {
        let mut buf = [0; 8];
        self.reader.read_exact(&mut buf).await?;
        let r = f64::from_le_bytes(buf);
        Ok(r)
    }

    async fn read_string(&mut self) -> Result<String> {
        let bytes = self.read_bytes().await?;
        String::from_utf8(bytes).map_err(From::from)
    }

    async fn read_list_begin(&mut self) -> Result<TListIdentifier> {
        let (element_type, element_count) = self.read_list_set_begin().await?;
        Ok(TListIdentifier::new(element_type, element_count))
    }

    async fn read_list_end(&mut self) -> Result<()> {
        Ok(())
    }

    async fn read_set_begin(&mut self) -> Result<TSetIdentifier> {
        let (element_type, element_count) = self.read_list_set_begin().await?;
        Ok(TSetIdentifier::new(element_type, element_count))
    }

    async fn read_set_end(&mut self) -> Result<()> {
        Ok(())
    }

    async fn read_map_begin(&mut self) -> Result<TMapIdentifier> {
        let element_count = self.reader.read_varint_async::<u32>().await?;
        if element_count == 0 {
            Ok(TMapIdentifier::new(None, None, 0))
        } else {
            let type_header = self.read_byte().await?;
            let key_type = collection_u8_to_type((type_header & 0xF0) >> 4)?;
            let val_type = collection_u8_to_type(type_header & 0x0F)?;
            self.update_remaining::<usize>(element_count.try_into()?)?;
            Ok(TMapIdentifier::new(key_type, val_type, element_count))
        }
    }

    async fn read_map_end(&mut self) -> Result<()> {
        Ok(())
    }

    // utility
    //

    async fn read_byte(&mut self) -> Result<u8> {
        let mut buf = [0u8; 1];
        self.reader
            .read_exact(&mut buf)
            .await
            .map_err(From::from)
            .map(|_| buf[0])
    }
}