Debian Codegraph @

examples/encode_torrent.rs

raw symbols SCIP
1 //! An encoder for torrent files
2 //!
3 //! This example will ...
4 //!
5 //! - serialize a torrent file representing object in bencode format
6 //! - and print the result into stdout.
7 //!
8 //! *Attention*: Please consider to pipe the output into a file of your choice.
9 //!
10 //! # Run the Example
11 //!
12 //! ```
13 //! cargo run --example encode_torrent > example.torrent
14 //! ```
15
16 use std::io::Write;
17
18 use bendy::encoding::{AsString, Error, SingleItemEncoder, ToBencode};
19
20 /// Main struct containing all required information.
21 ///
22 /// Based on: [http://fileformats.wikia.com/wiki/Torrent_file].
23 ///
24 /// # Design Decision
25 ///
26 /// To keep the example simple we won't parse the integers fields
27 /// into a concrete number type as the bencode integer definition
28 /// is actually a `BigNum` and the content may not fit.
29 #[derive(Debug)]
30 struct MetaInfo {
31 pub announce: String,
32 pub info: Info,
33 pub comment: Option<String>, // not official element
34 pub creation_date: Option<String>, // not official element
35 pub http_seeds: Option<Vec<String>>, // not official element
36 }
37
38 /// File related information (Single-file format)
39 #[derive(Debug)]
40 struct Info {
41 pub piece_length: String,
42 pub pieces: Vec<u8>,
43 pub name: String,
44 pub file_length: String,
45 }
46
47 impl ToBencode for MetaInfo {
48 // Adds an additional recursion level -- itself formatted as dictionary --
49 // around the info struct.
50 const MAX_DEPTH: usize = Info::MAX_DEPTH + 1;
51
52 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
53 encoder.emit_dict(|mut e| {
54 e.emit_pair(b"announce", &self.announce)?;
55
56 if let Some(comment) = &self.comment {
57 e.emit_pair(b"comment", comment)?;
58 }
59
60 if let Some(creation_date) = &self.creation_date {
61 e.emit_pair(b"creation date", creation_date)?;
62 }
63
64 if let Some(seeds) = &self.http_seeds {
65 // List is a simple iterable wrapper that allows to encode
66 // any list like container as bencode list object.
67 e.emit_pair(b"httpseeds", seeds)?;
68 }
69
70 e.emit_pair(b"info", &self.info)
71 })?;
72
73 Ok(())
74 }
75 }
76
77 impl ToBencode for Info {
78 // The struct is encoded as dictionary and all of it internals are encoded
79 // as flat values, i.e. strings or integers.
80 const MAX_DEPTH: usize = 1;
81
82 fn encode(&self, encoder: SingleItemEncoder) -> Result<(), Error> {
83 encoder.emit_dict(|mut e| {
84 e.emit_pair(b"length", &self.file_length)?;
85 e.emit_pair(b"name", &self.name)?;
86 e.emit_pair(b"piece length", &self.piece_length)?;
87 e.emit_pair(b"pieces", AsString(&self.pieces))
88 })?;
89 Ok(())
90 }
91 }
92
93 fn main() -> Result<(), Box<dyn std::error::Error>> {
94 let torrent = MetaInfo {
95 announce: "http://bttracker.debian.org:6969/announce".to_owned(),
96 comment: Some("\"Debian CD from cdimage.debian.org\"".to_owned()),
97 creation_date: Some(1_520_682_848.to_string()),
98 http_seeds: Some(vec![
99 "https://cdimage.debian.org/cdimage/release/9.4.0//srv/cdbuilder.debian.org/dst/deb-cd/weekly-builds/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso".to_owned(),
100 "https://cdimage.debian.org/cdimage/archive/9.4.0//srv/cdbuilder.debian.org/dst/deb-cd/weekly-builds/amd64/iso-cd/debian-9.4.0-amd64-netinst.iso".to_owned(),
101 ]),
102 info: Info {
103 piece_length: 262_144.to_string(),
104 pieces: include_bytes!("torrent_files/pieces.iso").to_vec(),
105 name: "debian-9.4.0-amd64-netinst.iso".to_owned(),
106 file_length: 305_135_616.to_string(),
107 },
108 };
109
110 let data = torrent.to_bencode()?;
111 std::io::stdout().write_all(&data)?;
112
113 Ok(())
114 }