Skip to main content

ferogram_tl_types/
deserialize.rs

1// Copyright (c) Ankit Chaubey <ankitchaubey.dev@gmail.com>
2// SPDX-License-Identifier: MIT OR Apache-2.0
3//
4// ferogram: async Telegram MTProto client in Rust
5// https://github.com/ankit-chaubey/ferogram
6//
7// If you use or modify this code, keep this notice at the top of your file
8// and include the LICENSE-MIT or LICENSE-APACHE file from this repository:
9// https://github.com/ankit-chaubey/ferogram
10
11use std::fmt;
12
13/// Errors that can occur during deserialization.
14#[derive(Clone, Debug, PartialEq)]
15pub enum Error {
16    /// Ran out of bytes before the type was fully read.
17    UnexpectedEof,
18    /// Decoded a constructor ID that doesn't match any known variant.
19    UnexpectedConstructor { id: u32 },
20}
21
22impl fmt::Display for Error {
23    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
24        match self {
25            Self::UnexpectedEof => write!(f, "unexpected end of buffer"),
26            Self::UnexpectedConstructor { id } => {
27                write!(f, "unexpected constructor id: {id:#010x}")
28            }
29        }
30    }
31}
32
33impl std::error::Error for Error {}
34
35/// Specialized `Result` for deserialization.
36pub type Result<T> = std::result::Result<T, Error>;
37
38// Cursor
39
40/// A zero-copy cursor over an in-memory byte slice.
41///
42/// Avoids `std::io::Cursor` and its wide error surface; only the two error
43/// cases above can ever occur during TL deserialization.
44pub struct Cursor<'a> {
45    buf: &'a [u8],
46    pos: usize,
47}
48
49impl<'a> Cursor<'a> {
50    /// Create a cursor positioned at the start of `buf`.
51    pub fn from_slice(buf: &'a [u8]) -> Self {
52        Self { buf, pos: 0 }
53    }
54
55    /// Current byte offset.
56    pub fn pos(&self) -> usize {
57        self.pos
58    }
59
60    /// Remaining bytes.
61    pub fn remaining(&self) -> usize {
62        self.buf.len() - self.pos
63    }
64
65    /// Read a single byte.
66    pub fn read_byte(&mut self) -> Result<u8> {
67        match self.buf.get(self.pos).copied() {
68            Some(b) => {
69                self.pos += 1;
70                Ok(b)
71            }
72            None => Err(Error::UnexpectedEof),
73        }
74    }
75
76    /// Read exactly `buf.len()` bytes.
77    pub fn read_exact(&mut self, out: &mut [u8]) -> Result<()> {
78        let end = self.pos + out.len();
79        if end > self.buf.len() {
80            return Err(Error::UnexpectedEof);
81        }
82        out.copy_from_slice(&self.buf[self.pos..end]);
83        self.pos = end;
84        Ok(())
85    }
86
87    /// Consume all remaining bytes into `out`.
88    pub fn read_to_end(&mut self, out: &mut Vec<u8>) -> usize {
89        let slice = &self.buf[self.pos..];
90        out.extend_from_slice(slice);
91        self.pos = self.buf.len();
92        slice.len()
93    }
94}
95
96/// Alias used by generated code: `crate::deserialize::Buffer<'_, '_>`.
97pub type Buffer<'a, 'b> = &'a mut Cursor<'b>;
98
99// Deserializable
100
101/// Deserialize a value from TL binary format.
102pub trait Deserializable: Sized {
103    /// Read `Self` from `buf`, advancing its position.
104    fn deserialize(buf: Buffer) -> Result<Self>;
105
106    /// Convenience: deserialize from a byte slice.
107    fn from_bytes(bytes: &[u8]) -> Result<Self> {
108        let mut cursor = Cursor::from_slice(bytes);
109        Self::deserialize(&mut cursor)
110    }
111}
112
113// Primitives
114
115impl Deserializable for bool {
116    fn deserialize(buf: Buffer) -> Result<Self> {
117        match u32::deserialize(buf)? {
118            0x997275b5 => Ok(true),
119            0xbc799737 => Ok(false),
120            id => Err(Error::UnexpectedConstructor { id }),
121        }
122    }
123}
124
125impl Deserializable for i32 {
126    fn deserialize(buf: Buffer) -> Result<Self> {
127        let mut b = [0u8; 4];
128        buf.read_exact(&mut b)?;
129        Ok(i32::from_le_bytes(b))
130    }
131}
132
133impl Deserializable for u32 {
134    fn deserialize(buf: Buffer) -> Result<Self> {
135        let mut b = [0u8; 4];
136        buf.read_exact(&mut b)?;
137        Ok(u32::from_le_bytes(b))
138    }
139}
140
141impl Deserializable for i64 {
142    fn deserialize(buf: Buffer) -> Result<Self> {
143        let mut b = [0u8; 8];
144        buf.read_exact(&mut b)?;
145        Ok(i64::from_le_bytes(b))
146    }
147}
148
149impl Deserializable for f64 {
150    fn deserialize(buf: Buffer) -> Result<Self> {
151        let mut b = [0u8; 8];
152        buf.read_exact(&mut b)?;
153        Ok(f64::from_le_bytes(b))
154    }
155}
156
157impl Deserializable for [u8; 16] {
158    fn deserialize(buf: Buffer) -> Result<Self> {
159        let mut b = [0u8; 16];
160        buf.read_exact(&mut b)?;
161        Ok(b)
162    }
163}
164
165impl Deserializable for [u8; 32] {
166    fn deserialize(buf: Buffer) -> Result<Self> {
167        let mut b = [0u8; 32];
168        buf.read_exact(&mut b)?;
169        Ok(b)
170    }
171}
172
173// Bytes / String
174
175impl Deserializable for Vec<u8> {
176    fn deserialize(buf: Buffer) -> Result<Self> {
177        let first = buf.read_byte()?;
178        let (len, header_extra) = if first != 0xfe {
179            (first as usize, 0)
180        } else {
181            let a = buf.read_byte()? as usize;
182            let b = buf.read_byte()? as usize;
183            let c = buf.read_byte()? as usize;
184            (a | (b << 8) | (c << 16), 3)
185        };
186
187        let mut data = vec![0u8; len];
188        buf.read_exact(&mut data)?;
189
190        // Skip alignment padding
191        let total = 1 + header_extra + len;
192        let padding = (4 - (total % 4)) % 4;
193        for _ in 0..padding {
194            buf.read_byte()?;
195        }
196
197        Ok(data)
198    }
199}
200
201impl Deserializable for String {
202    fn deserialize(buf: Buffer) -> Result<Self> {
203        let bytes = Vec::<u8>::deserialize(buf)?;
204        String::from_utf8(bytes).map_err(|_| Error::UnexpectedEof)
205    }
206}
207
208// Vectors
209
210impl<T: Deserializable> Deserializable for Vec<T> {
211    fn deserialize(buf: Buffer) -> Result<Self> {
212        let id = u32::deserialize(buf)?;
213        if id != 0x1cb5c415 {
214            return Err(Error::UnexpectedConstructor { id });
215        }
216        let len = i32::deserialize(buf)? as usize;
217        (0..len).map(|_| T::deserialize(buf)).collect()
218    }
219}
220
221impl<T: Deserializable> Deserializable for crate::RawVec<T> {
222    fn deserialize(buf: Buffer) -> Result<Self> {
223        let len = i32::deserialize(buf)? as usize;
224        let inner = (0..len)
225            .map(|_| T::deserialize(buf))
226            .collect::<Result<_>>()?;
227        Ok(crate::RawVec(inner))
228    }
229}