| 1 | //! Serde bencode deserialization. |
| 2 | |
| 3 | use crate::serde::common::*; |
| 4 | |
| 5 | /// Deserialize an instance of `T` from bencode |
| 6 | pub fn from_bytes<'a, T>(s: &'a [u8]) -> Result<T> |
| 7 | where |
| 8 | T: Deserialize<'a>, |
| 9 | { |
| 10 | Deserializer::from_bytes(s).deserialize() |
| 11 | } |
| 12 | |
| 13 | /// Bencode deserializer |
| 14 | pub struct Deserializer<'de> { |
| 15 | forbid_trailing_bytes: bool, |
| 16 | tokens: Peekable<Tokens<'de>>, |
| 17 | } |
| 18 | |
| 19 | impl<'de> Deserializer<'de> { |
| 20 | /// Create a new `Deserializer` with the give byte slice |
| 21 | pub fn from_bytes(input: &'de [u8]) -> Self { |
| 22 | Deserializer { |
| 23 | forbid_trailing_bytes: false, |
| 24 | tokens: Decoder::new(input).tokens().peekable(), |
| 25 | } |
| 26 | } |
| 27 | |
| 28 | /// Return an error if trailing bytes remain after deserialization |
| 29 | pub fn with_forbid_trailing_bytes(mut self, forbid_trailing_bytes: bool) -> Self { |
| 30 | self.forbid_trailing_bytes = forbid_trailing_bytes; |
| 31 | self |
| 32 | } |
| 33 | |
| 34 | /// Consume the deserializer, producing an instance of `T` |
| 35 | pub fn deserialize<T>(mut self) -> Result<T, Error> |
| 36 | where |
| 37 | T: Deserialize<'de>, |
| 38 | { |
| 39 | let t = T::deserialize(&mut self)?; |
| 40 | |
| 41 | if self.forbid_trailing_bytes && self.tokens.next().is_some() { |
| 42 | return Err(Error::TrailingBytes); |
| 43 | } |
| 44 | |
| 45 | Ok(t) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | impl<'de> Deserializer<'de> { |
| 50 | fn next_token(&mut self) -> Result<Token<'de>> { |
| 51 | match self.tokens.next() { |
| 52 | Some(result) => Ok(result?), |
| 53 | None => Err(Error::Decode(StructureError::UnexpectedEof.into())), |
| 54 | } |
| 55 | } |
| 56 | |
| 57 | fn next_integer(&mut self) -> Result<&'de str> { |
| 58 | match self.next_token()? { |
| 59 | Token::Num(num) => Ok(num), |
| 60 | other => Err(decoding::Error::unexpected_token("Num", other.name()).into()), |
| 61 | } |
| 62 | } |
| 63 | |
| 64 | fn next_bytes(&mut self) -> Result<&'de [u8]> { |
| 65 | match self.next_token()? { |
| 66 | Token::String(bytes) => Ok(bytes), |
| 67 | other => Err(decoding::Error::unexpected_token("String", other.name()).into()), |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | fn next_string(&mut self) -> Result<&'de str> { |
| 72 | let bytes = self.next_bytes()?; |
| 73 | let string = str::from_utf8(bytes)?; |
| 74 | Ok(string) |
| 75 | } |
| 76 | |
| 77 | fn expect_list_begin(&mut self) -> Result<()> { |
| 78 | match self.next_token()? { |
| 79 | Token::List => Ok(()), |
| 80 | other => Err(decoding::Error::unexpected_token("List", other.name()).into()), |
| 81 | } |
| 82 | } |
| 83 | |
| 84 | fn expect_dict_begin(&mut self) -> Result<()> { |
| 85 | match self.next_token()? { |
| 86 | Token::Dict => Ok(()), |
| 87 | other => Err(decoding::Error::unexpected_token("Dict", other.name()).into()), |
| 88 | } |
| 89 | } |
| 90 | |
| 91 | fn expect_end(&mut self) -> Result<()> { |
| 92 | match self.next_token()? { |
| 93 | Token::End => Ok(()), |
| 94 | other => Err(decoding::Error::unexpected_token("End", other.name()).into()), |
| 95 | } |
| 96 | } |
| 97 | |
| 98 | fn expect_empty_list(&mut self) -> Result<()> { |
| 99 | self.expect_list_begin()?; |
| 100 | self.expect_end()?; |
| 101 | Ok(()) |
| 102 | } |
| 103 | |
| 104 | fn peek_end(&mut self) -> bool { |
| 105 | self.peek() == Some(Token::End) |
| 106 | } |
| 107 | |
| 108 | fn peek(&mut self) -> Option<Token<'de>> { |
| 109 | if let Some(Ok(token)) = self.tokens.peek() { |
| 110 | Some(*token) |
| 111 | } else { |
| 112 | None |
| 113 | } |
| 114 | } |
| 115 | } |
| 116 | |
| 117 | impl<'de, 'a> serde::de::Deserializer<'de> for &'a mut Deserializer<'de> { |
| 118 | type Error = Error; |
| 119 | |
| 120 | fn deserialize_any<V>(self, visitor: V) -> Result<V::Value> |
| 121 | where |
| 122 | V: Visitor<'de>, |
| 123 | { |
| 124 | match self.peek() { |
| 125 | Some(Token::Dict) => self.deserialize_map(visitor), |
| 126 | Some(Token::String(_)) => self.deserialize_bytes(visitor), |
| 127 | Some(Token::List) => self.deserialize_seq(visitor), |
| 128 | Some(Token::Num(_)) => self.deserialize_i64(visitor), |
| 129 | Some(Token::End) => Err(Error::Decode(StructureError::invalid_state("End").into())), |
| 130 | None => Err(Error::Decode(StructureError::UnexpectedEof.into())), |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | fn deserialize_bool<V>(self, visitor: V) -> Result<V::Value> |
| 135 | where |
| 136 | V: Visitor<'de>, |
| 137 | { |
| 138 | match self.next_integer()? { |
| 139 | "0" => visitor.visit_bool(false), |
| 140 | "1" => visitor.visit_bool(true), |
| 141 | other => Err(Error::InvalidBool(other.to_owned())), |
| 142 | } |
| 143 | } |
| 144 | |
| 145 | fn deserialize_i8<V>(self, visitor: V) -> Result<V::Value> |
| 146 | where |
| 147 | V: Visitor<'de>, |
| 148 | { |
| 149 | visitor.visit_i8(self.next_integer()?.parse()?) |
| 150 | } |
| 151 | |
| 152 | fn deserialize_i16<V>(self, visitor: V) -> Result<V::Value> |
| 153 | where |
| 154 | V: Visitor<'de>, |
| 155 | { |
| 156 | visitor.visit_i16(self.next_integer()?.parse()?) |
| 157 | } |
| 158 | |
| 159 | fn deserialize_i32<V>(self, visitor: V) -> Result<V::Value> |
| 160 | where |
| 161 | V: Visitor<'de>, |
| 162 | { |
| 163 | visitor.visit_i32(self.next_integer()?.parse()?) |
| 164 | } |
| 165 | |
| 166 | fn deserialize_i64<V>(self, visitor: V) -> Result<V::Value> |
| 167 | where |
| 168 | V: Visitor<'de>, |
| 169 | { |
| 170 | visitor.visit_i64(self.next_integer()?.parse()?) |
| 171 | } |
| 172 | |
| 173 | fn deserialize_i128<V>(self, visitor: V) -> Result<V::Value> |
| 174 | where |
| 175 | V: Visitor<'de>, |
| 176 | { |
| 177 | visitor.visit_i128(self.next_integer()?.parse()?) |
| 178 | } |
| 179 | |
| 180 | fn deserialize_u8<V>(self, visitor: V) -> Result<V::Value> |
| 181 | where |
| 182 | V: Visitor<'de>, |
| 183 | { |
| 184 | visitor.visit_u8(self.next_integer()?.parse()?) |
| 185 | } |
| 186 | |
| 187 | fn deserialize_u16<V>(self, visitor: V) -> Result<V::Value> |
| 188 | where |
| 189 | V: Visitor<'de>, |
| 190 | { |
| 191 | visitor.visit_u16(self.next_integer()?.parse()?) |
| 192 | } |
| 193 | |
| 194 | fn deserialize_u32<V>(self, visitor: V) -> Result<V::Value> |
| 195 | where |
| 196 | V: Visitor<'de>, |
| 197 | { |
| 198 | visitor.visit_u32(self.next_integer()?.parse()?) |
| 199 | } |
| 200 | |
| 201 | fn deserialize_u64<V>(self, visitor: V) -> Result<V::Value> |
| 202 | where |
| 203 | V: Visitor<'de>, |
| 204 | { |
| 205 | visitor.visit_u64(self.next_integer()?.parse()?) |
| 206 | } |
| 207 | |
| 208 | fn deserialize_u128<V>(self, visitor: V) -> Result<V::Value> |
| 209 | where |
| 210 | V: Visitor<'de>, |
| 211 | { |
| 212 | visitor.visit_u128(self.next_integer()?.parse()?) |
| 213 | } |
| 214 | |
| 215 | fn deserialize_f32<V>(self, visitor: V) -> Result<V::Value> |
| 216 | where |
| 217 | V: Visitor<'de>, |
| 218 | { |
| 219 | let bytes = self.next_bytes()?; |
| 220 | let bits = u32::from_be_bytes( |
| 221 | bytes |
| 222 | .try_into() |
| 223 | .map_err(|_| Error::InvalidF32(bytes.len()))?, |
| 224 | ); |
| 225 | let value = f32::from_bits(bits); |
| 226 | visitor.visit_f32(value) |
| 227 | } |
| 228 | |
| 229 | fn deserialize_f64<V>(self, visitor: V) -> Result<V::Value> |
| 230 | where |
| 231 | V: Visitor<'de>, |
| 232 | { |
| 233 | let bytes = self.next_bytes()?; |
| 234 | let bits = u64::from_be_bytes( |
| 235 | bytes |
| 236 | .try_into() |
| 237 | .map_err(|_| Error::InvalidF64(bytes.len()))?, |
| 238 | ); |
| 239 | let value = f64::from_bits(bits); |
| 240 | visitor.visit_f64(value) |
| 241 | } |
| 242 | |
| 243 | fn deserialize_char<V>(self, visitor: V) -> Result<V::Value> |
| 244 | where |
| 245 | V: Visitor<'de>, |
| 246 | { |
| 247 | let s: &str = self.next_string()?; |
| 248 | let count = s.chars().count(); |
| 249 | if count != 1 { |
| 250 | return Err(Error::InvalidChar(count)); |
| 251 | } |
| 252 | visitor.visit_char(s.chars().next().unwrap()) |
| 253 | } |
| 254 | |
| 255 | fn deserialize_str<V>(self, visitor: V) -> Result<V::Value> |
| 256 | where |
| 257 | V: Visitor<'de>, |
| 258 | { |
| 259 | visitor.visit_borrowed_str(self.next_string()?) |
| 260 | } |
| 261 | |
| 262 | fn deserialize_string<V>(self, visitor: V) -> Result<V::Value> |
| 263 | where |
| 264 | V: Visitor<'de>, |
| 265 | { |
| 266 | self.deserialize_str(visitor) |
| 267 | } |
| 268 | |
| 269 | fn deserialize_bytes<V>(self, visitor: V) -> Result<V::Value> |
| 270 | where |
| 271 | V: Visitor<'de>, |
| 272 | { |
| 273 | visitor.visit_borrowed_bytes(self.next_bytes()?) |
| 274 | } |
| 275 | |
| 276 | fn deserialize_byte_buf<V>(self, visitor: V) -> Result<V::Value> |
| 277 | where |
| 278 | V: Visitor<'de>, |
| 279 | { |
| 280 | self.deserialize_bytes(visitor) |
| 281 | } |
| 282 | |
| 283 | fn deserialize_option<V>(self, visitor: V) -> Result<V::Value> |
| 284 | where |
| 285 | V: Visitor<'de>, |
| 286 | { |
| 287 | self.expect_list_begin()?; |
| 288 | let value = if self.peek_end() { |
| 289 | visitor.visit_none() |
| 290 | } else { |
| 291 | visitor.visit_some(&mut *self) |
| 292 | }; |
| 293 | self.expect_end()?; |
| 294 | value |
| 295 | } |
| 296 | |
| 297 | fn deserialize_unit<V>(self, visitor: V) -> Result<V::Value> |
| 298 | where |
| 299 | V: Visitor<'de>, |
| 300 | { |
| 301 | self.expect_empty_list()?; |
| 302 | visitor.visit_unit() |
| 303 | } |
| 304 | |
| 305 | fn deserialize_unit_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> |
| 306 | where |
| 307 | V: Visitor<'de>, |
| 308 | { |
| 309 | self.deserialize_unit(visitor) |
| 310 | } |
| 311 | |
| 312 | fn deserialize_newtype_struct<V>(self, _name: &'static str, visitor: V) -> Result<V::Value> |
| 313 | where |
| 314 | V: Visitor<'de>, |
| 315 | { |
| 316 | visitor.visit_newtype_struct(self) |
| 317 | } |
| 318 | |
| 319 | fn deserialize_seq<V>(self, visitor: V) -> Result<V::Value> |
| 320 | where |
| 321 | V: Visitor<'de>, |
| 322 | { |
| 323 | self.expect_list_begin()?; |
| 324 | let value = visitor.visit_seq(&mut *self)?; |
| 325 | self.expect_end()?; |
| 326 | Ok(value) |
| 327 | } |
| 328 | |
| 329 | fn deserialize_tuple<V>(self, _len: usize, visitor: V) -> Result<V::Value> |
| 330 | where |
| 331 | V: Visitor<'de>, |
| 332 | { |
| 333 | self.deserialize_seq(visitor) |
| 334 | } |
| 335 | |
| 336 | fn deserialize_tuple_struct<V>( |
| 337 | self, |
| 338 | _name: &'static str, |
| 339 | _len: usize, |
| 340 | visitor: V, |
| 341 | ) -> Result<V::Value> |
| 342 | where |
| 343 | V: Visitor<'de>, |
| 344 | { |
| 345 | self.deserialize_seq(visitor) |
| 346 | } |
| 347 | |
| 348 | fn deserialize_map<V>(self, visitor: V) -> Result<V::Value> |
| 349 | where |
| 350 | V: Visitor<'de>, |
| 351 | { |
| 352 | self.expect_dict_begin()?; |
| 353 | let value = visitor.visit_map(&mut *self)?; |
| 354 | self.expect_end()?; |
| 355 | Ok(value) |
| 356 | } |
| 357 | |
| 358 | fn deserialize_struct<V>( |
| 359 | self, |
| 360 | _name: &'static str, |
| 361 | _fields: &'static [&'static str], |
| 362 | visitor: V, |
| 363 | ) -> Result<V::Value> |
| 364 | where |
| 365 | V: Visitor<'de>, |
| 366 | { |
| 367 | self.expect_dict_begin()?; |
| 368 | let value = visitor.visit_map(&mut *self)?; |
| 369 | self.expect_end()?; |
| 370 | Ok(value) |
| 371 | } |
| 372 | |
| 373 | fn deserialize_enum<V>( |
| 374 | self, |
| 375 | _name: &'static str, |
| 376 | _variants: &'static [&'static str], |
| 377 | visitor: V, |
| 378 | ) -> Result<V::Value> |
| 379 | where |
| 380 | V: Visitor<'de>, |
| 381 | { |
| 382 | if self.peek() == Some(Token::Dict) { |
| 383 | self.expect_dict_begin()?; |
| 384 | visitor.visit_enum(self) |
| 385 | } else { |
| 386 | visitor.visit_enum(self.next_string()?.into_deserializer()) |
| 387 | } |
| 388 | } |
| 389 | |
| 390 | fn deserialize_identifier<V>(self, visitor: V) -> Result<V::Value> |
| 391 | where |
| 392 | V: Visitor<'de>, |
| 393 | { |
| 394 | self.deserialize_str(visitor) |
| 395 | } |
| 396 | |
| 397 | fn deserialize_ignored_any<V>(self, visitor: V) -> Result<V::Value> |
| 398 | where |
| 399 | V: Visitor<'de>, |
| 400 | { |
| 401 | self.deserialize_any(visitor) |
| 402 | } |
| 403 | } |
| 404 | |
| 405 | impl<'de> SeqAccess<'de> for Deserializer<'de> { |
| 406 | type Error = Error; |
| 407 | |
| 408 | fn next_element_seed<T>(&mut self, seed: T) -> Result<Option<T::Value>> |
| 409 | where |
| 410 | T: DeserializeSeed<'de>, |
| 411 | { |
| 412 | if self.peek_end() { |
| 413 | return Ok(None); |
| 414 | } |
| 415 | seed.deserialize(self).map(Some) |
| 416 | } |
| 417 | } |
| 418 | |
| 419 | impl<'de> MapAccess<'de> for Deserializer<'de> { |
| 420 | type Error = Error; |
| 421 | |
| 422 | fn next_key_seed<K>(&mut self, seed: K) -> Result<Option<K::Value>> |
| 423 | where |
| 424 | K: DeserializeSeed<'de>, |
| 425 | { |
| 426 | if self.peek_end() { |
| 427 | return Ok(None); |
| 428 | } |
| 429 | seed.deserialize(self).map(Some) |
| 430 | } |
| 431 | |
| 432 | fn next_value_seed<V>(&mut self, seed: V) -> Result<V::Value> |
| 433 | where |
| 434 | V: DeserializeSeed<'de>, |
| 435 | { |
| 436 | seed.deserialize(self) |
| 437 | } |
| 438 | } |
| 439 | |
| 440 | impl<'de> EnumAccess<'de> for &mut Deserializer<'de> { |
| 441 | type Error = Error; |
| 442 | type Variant = Self; |
| 443 | |
| 444 | fn variant_seed<V>(self, seed: V) -> Result<(V::Value, Self)> |
| 445 | where |
| 446 | V: DeserializeSeed<'de>, |
| 447 | { |
| 448 | Ok((seed.deserialize(&mut *self)?, self)) |
| 449 | } |
| 450 | } |
| 451 | |
| 452 | impl<'de> VariantAccess<'de> for &mut Deserializer<'de> { |
| 453 | type Error = Error; |
| 454 | |
| 455 | fn unit_variant(self) -> Result<()> { |
| 456 | Ok(()) |
| 457 | } |
| 458 | |
| 459 | fn newtype_variant_seed<T>(self, seed: T) -> Result<T::Value> |
| 460 | where |
| 461 | T: DeserializeSeed<'de>, |
| 462 | { |
| 463 | let value = seed.deserialize(&mut *self)?; |
| 464 | self.expect_end()?; |
| 465 | Ok(value) |
| 466 | } |
| 467 | |
| 468 | fn tuple_variant<V>(self, _len: usize, visitor: V) -> Result<V::Value> |
| 469 | where |
| 470 | V: Visitor<'de>, |
| 471 | { |
| 472 | let value = serde::de::Deserializer::deserialize_seq(&mut *self, visitor)?; |
| 473 | self.expect_end()?; |
| 474 | Ok(value) |
| 475 | } |
| 476 | |
| 477 | fn struct_variant<V>(self, _fields: &'static [&'static str], visitor: V) -> Result<V::Value> |
| 478 | where |
| 479 | V: Visitor<'de>, |
| 480 | { |
| 481 | let value = serde::de::Deserializer::deserialize_map(&mut *self, visitor)?; |
| 482 | self.expect_end()?; |
| 483 | Ok(value) |
| 484 | } |
| 485 | } |