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;

/// The object structure of a bencode file.
#[derive(Eq, PartialEq, Debug)]
pub enum Bencode {
    /// an integer value. in the format "i{VALUE}e"
    Integer(usize),
    /// a byte string value. in the format "{LENGTH}:{DATA}"
    ByteStr(Vec<u8>),
    /// a list of any Bencode type. in the format "l{BENCODE_OBJECTS}e"
    List(Vec<Bencode>),
    /// a list (Bencode::ByteString, Bencode). in the format "d{PAIRS}e"
    Dict(HashMap<Vec<u8>, Bencode>),
}

impl Bencode {
    /// parse a byte array into a bencode tree.
    pub fn from_bytes(bytes: &[u8]) -> Result {
        crate::parser::parse_child(bytes)
    }
    /// destructure a Bencode::Dict into a HashMap.
    pub fn as_dict(&self) -> GenResult<&HashMap<Vec<u8>, Bencode>> {
        match self {
            Bencode::Dict(val) => Ok(val),
            _ => Err(CannotParseAsDictionary),
        }
    }
    /// destructure a Bencode::List into a Vec.
    pub fn as_list(&self) -> GenResult<&Vec<Bencode>> {
        match self {
            Bencode::List(val) => Ok(val),
            _ => Err(CannotParseAsList),
        }
    }
    /// destructure a Bencode::Integer into a usize.
    pub fn as_int(&self) -> GenResult<&usize> {
        match self {
            Bencode::Integer(val) => Ok(val),
            _ => Err(CannotParseAsInteger),
        }
    }
    /// destructure a Bencode::ByteStr into a Vec<u8>.
    pub fn as_bstr(&self) -> GenResult<&Vec<u8>> {
        match self {
            Bencode::ByteStr(val) => Ok(val),
            _ => Err(CannotParseAsByteString),
        }
    }
}