| 1 | use bendy::{ |
| 2 | decoding::{Error as DecodingError, FromBencode, Object}, |
| 3 | encoding::{Error as EncodingError, SingleItemEncoder, ToBencode}, |
| 4 | }; |
| 5 | |
| 6 | #[derive(PartialEq, Eq, Debug)] |
| 7 | struct Example { |
| 8 | foo: Vec<i64>, |
| 9 | bar: i64, |
| 10 | } |
| 11 | |
| 12 | impl ToBencode for Example { |
| 13 | const MAX_DEPTH: usize = 2; |
| 14 | |
| 15 | fn encode(&self, encoder: SingleItemEncoder) -> Result<(), EncodingError> { |
| 16 | encoder.emit_dict(|mut dict| { |
| 17 | dict.emit_pair(b"bar", &self.bar)?; |
| 18 | dict.emit_pair(b"foo", &self.foo) |
| 19 | }) |
| 20 | } |
| 21 | } |
| 22 | |
| 23 | impl FromBencode for Example { |
| 24 | const EXPECTED_RECURSION_DEPTH: usize = 2; |
| 25 | |
| 26 | fn decode_bencode_object(object: Object) -> Result<Self, DecodingError> |
| 27 | where |
| 28 | Self: Sized, |
| 29 | { |
| 30 | let mut foo = None; |
| 31 | let mut bar = None; |
| 32 | |
| 33 | let mut dict = object.try_into_dictionary()?; |
| 34 | while let Some((key, value)) = dict.next_pair()? { |
| 35 | match key { |
| 36 | b"foo" => { |
| 37 | foo = Vec::decode_bencode_object(value).map(Some)?; |
| 38 | }, |
| 39 | b"bar" => { |
| 40 | bar = i64::decode_bencode_object(value).map(Some)?; |
| 41 | }, |
| 42 | _ => (), // ignore unknown keys |
| 43 | } |
| 44 | } |
| 45 | |
| 46 | Ok(Example { |
| 47 | foo: foo.ok_or_else(|| DecodingError::missing_field("foo"))?, |
| 48 | bar: bar.ok_or_else(|| DecodingError::missing_field("bar"))?, |
| 49 | }) |
| 50 | } |
| 51 | } |
| 52 | |
| 53 | #[test] |
| 54 | fn should_encode_struct() { |
| 55 | let example = Example { |
| 56 | foo: vec![2, 3], |
| 57 | bar: 1, |
| 58 | }; |
| 59 | let encoded = example.to_bencode().expect("example encoding is broken"); |
| 60 | |
| 61 | assert_eq!(encoded, b"d3:bari1e3:fooli2ei3eee".to_vec(),) |
| 62 | } |
| 63 | |
| 64 | #[test] |
| 65 | fn should_decode_struct() { |
| 66 | let encoded = b"d3:bari1e3:fooli2ei3eee".to_vec(); |
| 67 | let example = Example::from_bencode(&encoded).expect("example decoding is broken"); |
| 68 | |
| 69 | assert_eq!( |
| 70 | example, |
| 71 | Example { |
| 72 | foo: vec![2, 3], |
| 73 | bar: 1, |
| 74 | } |
| 75 | ) |
| 76 | } |
| 77 | |
| 78 | #[test] |
| 79 | fn validate_round_trip() { |
| 80 | let example = Example { |
| 81 | foo: vec![2, 3], |
| 82 | bar: 1, |
| 83 | }; |
| 84 | |
| 85 | let encoded = example.to_bencode().expect("example encoding is broken"); |
| 86 | let decoded = Example::from_bencode(&encoded).expect("example decoding is broken"); |
| 87 | |
| 88 | assert_eq!(example, decoded); |
| 89 | } |