bendecode 0.1.3

bendecode is a simple bencode parser specifically made for torrent files. It converts the file provided into a format acceptable in rust(structs and enums).
Documentation
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
use std::collections::HashMap;

use crate::{Bencode, Decode, Error, Result};

#[derive(Debug)]
pub struct Torrent {
    pub info: Info,
    pub announce: String,
    pub announce_list: Option<Vec<Vec<String>>>,
    pub creation_date: Option<i64>,
    pub comment: Option<String>,
    pub created_by: Option<String>,
    pub encoding: Option<String>,
}

#[derive(Debug)]
pub struct Info {
    pub name: String,
    pub length: Option<i64>,
    pub md5sum: Option<i64>,
    pub files: Option<Vec<File>>,
    pub piece_length: i64,
    pub pieces: String,
    pub private: bool,
}

#[derive(Debug)]
pub struct File {
    pub length: i64,
    pub path: String,
    pub md5sum: Option<i64>,
}

impl Info {
    fn from(dict: &HashMap<String, Bencode>) -> Result<Self> {
        let name = match dict.get("name") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, false, "info -> name") {
                    Ok(string) => string,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> name",
                });
            }
        };

        let piece_length = match dict.get("piece length") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, false, "info -> piece length") {
                    Ok(integer) => integer,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> piece length",
                });
            }
        };

        let pieces = match dict.get("pieces") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, false, "info -> pieces") {
                    Ok(string) => string,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> pieces",
                });
            }
        };

        let private = match dict.get("private") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, true, "info -> private") {
                    Ok(integer) => Some(integer),
                    Err(e) => return Err(e),
                }
            }
            None => None,
        };

        let (length, md5sum, files) = if dict.keys().any(|key| key == "files") {
            let files = match Self::for_directory(dict) {
                Ok(files) => Some(files),
                Err(e) => return Err(e),
            };

            (None, None, files)
        } else {
            let (length, md5sum) = match Self::for_file(dict) {
                Ok(tup) => tup,
                Err(e) => return Err(e),
            };

            (Some(length), md5sum, None)
        };

        Ok(Self {
            name,
            length,
            md5sum,
            files,
            piece_length,
            pieces,
            private: private.is_some(),
        })
    }

    fn for_file(dict: &HashMap<String, Bencode>) -> Result<(i64, Option<i64>)> {
        let length = match dict.get("length") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, false, "info -> length") {
                    Ok(integer) => integer,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> length",
                });
            }
        };

        let md5sum = match dict.get("md5sum") {
            Some(bencode_int) => match Decode::extract_integer(bencode_int, true, "info -> md5sum")
            {
                Ok(integer) => Some(integer),
                Err(e) => return Err(e),
            },
            None => None,
        };

        Ok((length, md5sum))
    }

    fn for_directory(dict: &HashMap<String, Bencode>) -> Result<Vec<File>> {
        let file_list = match dict.get("file") {
            Some(bencode_list) => match Decode::extract_list(bencode_list, false, "info -> file") {
                Ok(list) => list,
                Err(e) => return Err(e),
            },
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> file",
                });
            }
        };

        let mut files = Vec::<File>::new();

        for bencode_file in file_list {
            let file = match Decode::extract_dictionary(&bencode_file, false, "info -> file") {
                Ok(dictionary) => dictionary,
                Err(e) => return Err(e),
            };

            let final_file = match File::from(&file) {
                Ok(file) => file,
                Err(e) => return Err(e),
            };

            files.push(final_file);
        }

        Ok(files)
    }
}

impl File {
    fn from(dict: &HashMap<String, Bencode>) -> Result<Self> {
        let length = match dict.get("length") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, false, "info -> file -> length") {
                    Ok(integer) => integer,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> file -> length",
                });
            }
        };

        let path = match dict.get("path") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, false, "info -> file -> path") {
                    Ok(string) => string,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound {
                    name: "info -> file -> path",
                });
            }
        };

        let md5sum = match dict.get("md5sum") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, true, "info -> file -> md5sum") {
                    Ok(integer) => Some(integer),
                    Err(e) => return Err(e),
                }
            }
            None => None,
        };

        Ok(Self {
            length,
            path,
            md5sum,
        })
    }
}

impl Torrent {
    /// This function constructs the torrent struct from a string
    ///
    /// # Examples
    /// ```
    /// use bendecode::torrent::Torrent;
    ///
    /// let content = "d8:announce1:a4:infod12:piece lengthi1e6:pieces1:a4:name1:a6:lengthi1eee";
    ///     
    /// let torrent = Torrent::from(content);
    /// ````
    ///
    /// # Errors
    ///
    /// - [``RequiredFieldNotFound``](../enum.Error.html#variant.RequiredFieldNotFound)
    /// - [``Error::InvalidFieldType``](../enum.Error.html#variant.InvalidFieldType)
    pub fn from(content: &str) -> Result<Self> {
        let final_type = match Bencode::decode(content) {
            Ok(t) => t,
            Err(e) => return Err(e),
        };

        let torrent = match Decode::extract_dictionary(&final_type, true, "main_dict") {
            Ok(t) => t,
            Err(e) => return Err(e),
        };
        Self::from_dict(&torrent)
    }

    fn from_dict(dict: &HashMap<String, Bencode>) -> Result<Self> {
        let info_dict = match dict.get("info") {
            Some(bencode_dictionary) => {
                match Decode::extract_dictionary(bencode_dictionary, false, "info") {
                    Ok(dict) => dict,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound { name: "info" });
            }
        };

        let info = match Info::from(&info_dict) {
            Ok(e) => e,
            Err(e) => return Err(e),
        };

        let announce = match dict.get("announce") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, false, "announce") {
                    Ok(string) => string,
                    Err(e) => return Err(e),
                }
            }
            None => {
                return Err(Error::RequiredFieldNotFound { name: "announce" });
            }
        };

        let announce_list = match dict.get("announce-list") {
            Some(bencode_list) => match Decode::extract_list(bencode_list, true, "announce-list") {
                Ok(list) => match Self::find_announce_list(&list) {
                    Ok(final_list) => Some(final_list),
                    Err(e) => return Err(e),
                },
                Err(e) => return Err(e),
            },
            None => None,
        };

        let creation_date = match dict.get("creation date") {
            Some(bencode_int) => {
                match Decode::extract_integer(bencode_int, true, "creation date") {
                    Ok(int) => Some(int),
                    Err(e) => return Err(e),
                }
            }
            None => None,
        };

        let comment = match dict.get("comment") {
            Some(bencode_string) => match Decode::extract_string(bencode_string, true, "comment") {
                Ok(string) => Some(string),
                Err(e) => return Err(e),
            },
            None => None,
        };

        let created_by = match dict.get("created by") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, true, "created by") {
                    Ok(string) => Some(string),
                    Err(e) => return Err(e),
                }
            }
            None => None,
        };

        let encoding = match dict.get("encoding") {
            Some(bencode_string) => {
                match Decode::extract_string(bencode_string, true, "encoding") {
                    Ok(string) => Some(string),
                    Err(e) => return Err(e),
                }
            }
            None => None,
        };

        Ok(Self {
            info,
            announce,
            announce_list,
            creation_date,
            comment,
            created_by,
            encoding,
        })
    }

    fn find_announce_list(list: &Vec<Bencode>) -> Result<Vec<Vec<String>>> {
        let mut announce_list = Vec::<Vec<String>>::new();
        for element in list {
            let mut inner_announce = Vec::<String>::new();
            match Decode::extract_list(element, true, "announce_list") {
                Ok(list) => {
                    for el in list {
                        match Decode::extract_string(&el, true, "announce_list") {
                            Ok(string) => inner_announce.push(string),
                            Err(e) => return Err(e),
                        }
                    }
                }
                Err(e) => return Err(e),
            }

            announce_list.push(inner_announce);
        }

        Ok(announce_list)
    }
}

#[cfg(test)]
mod test {
    use crate::Error;

    use super::Torrent;

    #[test]
    fn test_valid_bencode() {
        let content = "d8:announce1:a4:infod12:piece lengthi1e6:pieces1:a4:name1:a6:lengthi1eee";

        let bencode = Torrent::from(content);

        assert!(bencode.is_ok());
    }

    #[test]
    fn test_invalid_bencode() {
        let required_field_not_found =
            "d7:announc1:a4:infod12:piece lengthi1e6:pieces1:a4:name1:a6:lengthi1eee";

        let required_field_invalid_type =
            "d8:announcei24e4:infod12:piece lengthi1e6:pieces1:a4:name1:a6:lengthi1eee";

        let optional_field_invalid_type = "d8:announce1:a13:creation date4:sep44:infod12:piece lengthi1e6:pieces1:a4:name1:a6:lengthi1eee";

        assert_eq!(
            Torrent::from(required_field_not_found).expect_err("Required field announce not found"),
            Error::RequiredFieldNotFound { name: "announce" }
        );

        assert_eq!(
            Torrent::from(required_field_invalid_type).expect_err("Required field invalid type"),
            Error::InvalidFieldType {
                optional: false,
                name: "announce",
                found: "integer",
                required: "string"
            }
        );

        assert_eq!(
            Torrent::from(optional_field_invalid_type).expect_err("Optional field invalid type"),
            Error::InvalidFieldType {
                optional: true,
                name: "creation date",
                found: "string",
                required: "integer"
            }
        );
    }
}