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
use std::fs::OpenOptions;
use std::io::Write;
use std::path::Path;

use crate::BencodeResult;
use crate::protocol::encode;
use crate::types::Type;

pub struct Encoder;

impl Encoder {
    pub fn encode(t: &Type) -> BencodeResult<Vec<u8>> {
        Ok(encode(t))
    }

    pub fn encode_to<P>(t: &Type, path: P) -> BencodeResult<()>
    where
        P: AsRef<Path>
    {
        let mut bytes = encode(t);
        let mut file = OpenOptions::new()
            .write(true)
            .create_new(true)
            .open(path)?;
        
        file.write_all(&mut bytes)?;

        Ok(())
    }
}