sveppa_bencode/error.rs
1use std::{
2 any::type_name,
3 num::ParseIntError,
4 string::FromUtf8Error,
5};
6
7#[derive(Debug)]
8/// Possible error values when parsing a bencode struct into a value, or utf8 bytes into a
9/// bencode struct.
10pub enum BencodeParserError {
11 /// When you call an enum destructuring method on the wrong variant.
12 /// Contains a message with invalid type and which method it was passed to.
13 ///
14 /// eg: calling `as_int()` on `Bencode::List`, or `as_list()` on `Bencode::Dict`, etc.
15 InvalidVariantMethod(String),
16 /// An invalid UTF8 byte sequence was found when calling `as_usize()` or `as_string()`.
17 ///
18 /// eg: some byte outside of the standard ASCII range.
19 InvalidUTF8String(FromUtf8Error),
20 /// An invalid ASCII byte was found when calling `as_usize()`.
21 ///
22 /// See: `ParseIntError` on `usize::from_str_radix()`
23 InvalidASCIIInteger(ParseIntError),
24 /// Indicates an expected 'e' was missing. All bencode types except ByteStr expect an 'e' byte
25 /// after data to indicate the end of the object.
26 MissingSentinel,
27 /// Indicates that the bytes passed to a parse function are not valid ASCII.
28 InvalidASCIIBytes,
29 /// Indicates that bytes passed to a parse function were valid ascii, but could not be parsed to
30 /// an integer. (in cases like bytestr length, or an integer value.)
31 InvalidIntegerString,
32 /// Indicates that the length specified by a bytestring is longer than the remaining number of
33 /// bytes passed into the parse function.
34 ByteStringLengthOverflow,
35 /// Indicates that while parsing a dictionary object, a non bytestring key was found.
36 BadDictionaryKey,
37 /// when a character is encountered by the parse_child function, that is not applicable to any
38 /// of the bencode types.
39 NotAValidBencodeByte,
40 /// Indicates that the first byte of the array passed to a parsing function was not valid.
41 ///
42 /// eg: as_int where first byte is not 'i', as_bstr where the first byte is not [0-9], etc.
43 BadFirstByte,
44}
45
46/// create an InvalidVariantMethod error easily.
47pub(crate) fn invalid_variant_method<T>(method: &'static str, _type_obj: T) -> BencodeParserError {
48 BencodeParserError::InvalidVariantMethod(
49 format!("{} passed to {}", type_name::<T>(), method)
50 )
51}