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
use crate::error::{Error::*, *};
use std::collections::HashMap;
#[derive(Eq, PartialEq, Debug)]
pub enum Bencode {
Integer(usize),
ByteStr(Vec<u8>),
List(Vec<Bencode>),
Dict(HashMap<Vec<u8>, Bencode>),
}
impl Bencode {
pub fn from_bytes(bytes: &[u8]) -> Result {
crate::parser::parse_child(bytes)
}
pub fn as_dict(&self) -> GenResult<&HashMap<Vec<u8>, Bencode>> {
match self {
Bencode::Dict(val) => Ok(val),
_ => Err(CannotParseAsDictionary),
}
}
pub fn as_list(&self) -> GenResult<&Vec<Bencode>> {
match self {
Bencode::List(val) => Ok(val),
_ => Err(CannotParseAsList),
}
}
pub fn as_int(&self) -> GenResult<&usize> {
match self {
Bencode::Integer(val) => Ok(val),
_ => Err(CannotParseAsInteger),
}
}
pub fn as_bstr(&self) -> GenResult<&Vec<u8>> {
match self {
Bencode::ByteStr(val) => Ok(val),
_ => Err(CannotParseAsByteString),
}
}
}