| 1 | //! Port of https://github.com/jamesleonis/bencode-cljc/blob/master/test/bencode_cljc/core_test.cljc |
| 2 | //! |
| 3 | //! Should only use #![no_std] compatible features but still requires the |
| 4 | //! `std` feature flag to avoid that we need to define a global allocator. |
| 5 | |
| 6 | extern crate alloc; |
| 7 | use alloc::collections::BTreeMap; |
| 8 | |
| 9 | use bendy::{ |
| 10 | decoding::{Error as DecodingError, FromBencode, Object}, |
| 11 | encoding::{Error as EncodingError, SingleItemEncoder, ToBencode}, |
| 12 | }; |
| 13 | |
| 14 | // ----------------------------------------------------------------------------- |
| 15 | // Macros |
| 16 | // ----------------------------------------------------------------------------- |
| 17 | |
| 18 | macro_rules! list( |
| 19 | {} => { Vec::<Something>::new() }; |
| 20 | { $($value:expr),+ } => { |
| 21 | { |
| 22 | let mut list = Vec::new(); |
| 23 | $( list.push(Something::from($value)); )+ |
| 24 | |
| 25 | list |
| 26 | } |
| 27 | }; |
| 28 | ); |
| 29 | |
| 30 | macro_rules! map( |
| 31 | { $($key:expr => $value:expr),+ } => { |
| 32 | { |
| 33 | let mut map = BTreeMap::new(); |
| 34 | $( map.insert($key.to_owned(), Something::from($value)); )+ |
| 35 | |
| 36 | map |
| 37 | } |
| 38 | }; |
| 39 | ); |
| 40 | |
| 41 | // ----------------------------------------------------------------------------- |
| 42 | // Tests |
| 43 | // ----------------------------------------------------------------------------- |
| 44 | |
| 45 | #[test] |
| 46 | fn string_test_pairs() -> Result<(), Error> { |
| 47 | let pairs = [ |
| 48 | ("", "0:"), |
| 49 | ("hello", "5:hello"), |
| 50 | ("goodbye", "7:goodbye"), |
| 51 | ("hello world", "11:hello world"), |
| 52 | ("1-5%3~]+=\\| []>.,`??", "20:1-5%3~]+=\\| []>.,`??"), |
| 53 | ]; |
| 54 | |
| 55 | for (original, expected_encoding) in &pairs { |
| 56 | let encoded = original.to_bencode()?; |
| 57 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 58 | |
| 59 | let decoded = String::from_bencode(&encoded)?; |
| 60 | assert_eq!(original, &decoded); |
| 61 | } |
| 62 | |
| 63 | Ok(()) |
| 64 | } |
| 65 | |
| 66 | #[test] |
| 67 | fn integer_test_pairs() -> Result<(), Error> { |
| 68 | let pairs = [ |
| 69 | (0, "i0e"), |
| 70 | (5, "i5e"), |
| 71 | (-5, "i-5e"), |
| 72 | (005, "i5e"), |
| 73 | (-005, "i-5e"), |
| 74 | (1234567890, "i1234567890e"), |
| 75 | (-1234567890, "i-1234567890e"), |
| 76 | (i64::max_value(), "i9223372036854775807e"), |
| 77 | (i64::min_value(), "i-9223372036854775808e"), |
| 78 | ]; |
| 79 | // Bendy currently doesn't contain a big number implementation.. |
| 80 | // |
| 81 | // ( |
| 82 | // 123456789012345678901234567890123456789012345678901234567890, |
| 83 | // "i123456789012345678901234567890123456789012345678901234567890e" |
| 84 | // ), |
| 85 | // ( |
| 86 | // -123456789012345678901234567890123456789012345678901234567890, |
| 87 | // "i-123456789012345678901234567890123456789012345678901234567890e" |
| 88 | // ) |
| 89 | |
| 90 | for (original, expected_encoding) in &pairs { |
| 91 | let encoded = original.to_bencode()?; |
| 92 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 93 | |
| 94 | let decoded = i64::from_bencode(&encoded)?; |
| 95 | assert_eq!(original, &decoded); |
| 96 | } |
| 97 | |
| 98 | Ok(()) |
| 99 | } |
| 100 | |
| 101 | #[test] |
| 102 | fn list_test_pairs() -> Result<(), Error> { |
| 103 | let pairs = [ |
| 104 | (list![], "le"), |
| 105 | (list!["abra", "cadabra"], "l4:abra7:cadabrae"), |
| 106 | (list!["spam", "eggs"], "l4:spam4:eggse"), |
| 107 | ( |
| 108 | list![vec!["list", "of", "lists"], vec!["like", "omygawd!"]], |
| 109 | "ll4:list2:of5:listsel4:like8:omygawd!ee", |
| 110 | ), |
| 111 | ]; |
| 112 | |
| 113 | for (original, expected_encoding) in &pairs { |
| 114 | let encoded = original.to_bencode()?; |
| 115 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 116 | |
| 117 | let decoded = Vec::<Something>::from_bencode(&encoded)?; |
| 118 | assert_eq!(original, &decoded); |
| 119 | } |
| 120 | |
| 121 | Ok(()) |
| 122 | } |
| 123 | |
| 124 | #[test] |
| 125 | fn map_test_pairs() -> Result<(), Error> { |
| 126 | let pairs = [ |
| 127 | (BTreeMap::new(), "de"), |
| 128 | ( |
| 129 | map! {"cow" => "moo", "spam" => "eggs"}, |
| 130 | "d3:cow3:moo4:spam4:eggse", |
| 131 | ), |
| 132 | ( |
| 133 | map! {"cow" => "moo", "dog" => "bark"}, |
| 134 | "d3:cow3:moo3:dog4:barke", |
| 135 | ), |
| 136 | ( |
| 137 | map! {"dog" => "bark", "cow" => "moo"}, |
| 138 | "d3:cow3:moo3:dog4:barke", |
| 139 | ), |
| 140 | ( |
| 141 | map! {"first" => "first", "2ace" => "second", "3ace" => "third"}, |
| 142 | "d4:2ace6:second4:3ace5:third5:first5:firste", |
| 143 | ), |
| 144 | ( |
| 145 | map! {"Goodbye" => map! {"maps" => "that don't work", "number" => 100}}, |
| 146 | "d7:Goodbyed4:maps15:that don't work6:numberi100eee", |
| 147 | ), |
| 148 | ( |
| 149 | map! { |
| 150 | "publisher" => "bob", "publisher-webpage" => "www.example.com", |
| 151 | "publisher.location" => "home" |
| 152 | }, |
| 153 | "d9:publisher3:bob17:publisher-webpage15:www.example.com18:publisher.location4:homee", |
| 154 | ), |
| 155 | ]; |
| 156 | |
| 157 | for (original, expected_encoding) in &pairs { |
| 158 | let encoded = original.to_bencode()?; |
| 159 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 160 | |
| 161 | let decoded = BTreeMap::<String, Something>::from_bencode(&encoded)?; |
| 162 | assert_eq!(original, &decoded); |
| 163 | } |
| 164 | |
| 165 | Ok(()) |
| 166 | } |
| 167 | |
| 168 | #[test] |
| 169 | fn mixed_use_list_pairs() -> Result<(), Error> { |
| 170 | let pairs = [( |
| 171 | list![0, "heterogeneous", -5, "lists", 10, map! {"map" => "well"}], |
| 172 | "li0e13:heterogeneousi-5e5:listsi10ed3:map4:wellee", |
| 173 | )]; |
| 174 | |
| 175 | for (original, expected_encoding) in &pairs { |
| 176 | let encoded = original.to_bencode()?; |
| 177 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 178 | |
| 179 | let decoded = Vec::<Something>::from_bencode(&encoded)?; |
| 180 | assert_eq!(original, &decoded); |
| 181 | } |
| 182 | |
| 183 | Ok(()) |
| 184 | } |
| 185 | |
| 186 | #[test] |
| 187 | fn mixed_use_dict_pairs() -> Result<(), Error> { |
| 188 | let pairs = [ |
| 189 | ( |
| 190 | map! { |
| 191 | "hello" => list!["world!", "gaia!", "mother earth!"], |
| 192 | "Goodbye" => map! {"maps" => "that don't work", "number" => 100} |
| 193 | }, |
| 194 | "d7:Goodbyed4:maps15:that don't work6:numberi100ee5:hellol6:world!5:gaia!13:mother earth!ee", |
| 195 | ), |
| 196 | ( |
| 197 | map! {"hello" => list!["world!", "gaia!", "mother earth!"]}, |
| 198 | "d5:hellol6:world!5:gaia!13:mother earth!ee", |
| 199 | ), |
| 200 | (map! {"spam" => list!["a", "b"]}, "d4:spaml1:a1:bee"), |
| 201 | ( |
| 202 | map! { |
| 203 | "t" => "aa", "y" => "q", "q" => "ping", |
| 204 | "a" => map! { "id" => "abcdefghij0123456789" } |
| 205 | }, |
| 206 | "d1:ad2:id20:abcdefghij0123456789e1:q4:ping1:t2:aa1:y1:qe", |
| 207 | ), |
| 208 | ( |
| 209 | map! { |
| 210 | "t" => "aa", "y" => "q", "q" => "find_node", |
| 211 | "a" => map! { "id" => "abcdefghij0123456789", "target" => "mnopqrstuvwxyz123456" } |
| 212 | }, |
| 213 | "d1:ad2:id20:abcdefghij01234567896:target20:mnopqrstuvwxyz123456e1:q9:find_node1:t2:aa1:y1:qe", |
| 214 | ), |
| 215 | ( |
| 216 | map! { |
| 217 | "t" => "aa", "y" => "q", "q" => "get_peers", |
| 218 | "a" => map! { "id" => "abcdefghij0123456789", "info_hash" => "mnopqrstuvwxyz123456" } |
| 219 | }, |
| 220 | "d1:ad2:id20:abcdefghij01234567899:info_hash20:mnopqrstuvwxyz123456e1:q9:get_peers1:t2:aa1:y1:qe", |
| 221 | ), |
| 222 | ( |
| 223 | map! { |
| 224 | "t" => "aa", |
| 225 | "y" => "r", |
| 226 | "r" => map! { |
| 227 | "id" => "abcdefghij0123456789", |
| 228 | "token" => "aoeusnth", "values" => vec!["axje.u", "idhtnm"] |
| 229 | } |
| 230 | }, |
| 231 | "d1:rd2:id20:abcdefghij01234567895:token8:aoeusnth6:valuesl6:axje.u6:idhtnmee1:t2:aa1:y1:re", |
| 232 | ), |
| 233 | ]; |
| 234 | |
| 235 | for (original, expected_encoding) in &pairs { |
| 236 | let encoded = original.to_bencode()?; |
| 237 | assert_eq!(expected_encoding.as_bytes(), encoded.as_slice()); |
| 238 | |
| 239 | let decoded = BTreeMap::<String, Something>::from_bencode(&encoded)?; |
| 240 | assert_eq!(original, &decoded); |
| 241 | } |
| 242 | |
| 243 | Ok(()) |
| 244 | } |
| 245 | |
| 246 | #[test] |
| 247 | fn illegal_integer_encodings() { |
| 248 | let values = [ |
| 249 | "i-0e", "i09e", "i-09e", "i-0123e", "i-00123e", "i0123e", "i00123e", "i12-345", "i-12-345", |
| 250 | "i-1", "i1", |
| 251 | ]; |
| 252 | // Bendy currently doesn't fail if it encounters unused tokens |
| 253 | // |
| 254 | // "i12345ei10e5:eoeoee", |
| 255 | // "i-12345ei10e5:eoeoee" |
| 256 | |
| 257 | for value in &values { |
| 258 | let error = i64::from_bencode(value.as_bytes()).unwrap_err(); |
| 259 | assert!(error.to_string().contains("encoding corrupted")); |
| 260 | } |
| 261 | } |
| 262 | |
| 263 | #[test] |
| 264 | fn illegal_string_encodings() { |
| 265 | let values = [":hello", "-5:hello", "-5:", "5:", "10:hello"]; |
| 266 | // Bendy currently doesn't fail if it encounters unused tokens |
| 267 | // |
| 268 | // "5:hello5:hello", |
| 269 | // "5:helloi10e", |
| 270 | // 10:hello5:hello", |
| 271 | // "10:helloi0e", |
| 272 | // "10:helloi123456789e" |
| 273 | |
| 274 | for value in &values { |
| 275 | let error = String::from_bencode(value.as_bytes()).unwrap_err(); |
| 276 | assert!(error.to_string().contains("encoding corrupted")); |
| 277 | } |
| 278 | } |
| 279 | |
| 280 | #[test] |
| 281 | fn illegal_list_encodings() { |
| 282 | let values = [ |
| 283 | "l", |
| 284 | "lsde", |
| 285 | "li10e5hello", |
| 286 | "l10:helloi123456789ee", |
| 287 | "l10:helloi123456789e5:helloe", |
| 288 | "l5:helloi123456789e10:helloe", |
| 289 | ]; |
| 290 | // Bendy currently doesn't fail if it encounters unused tokens |
| 291 | // |
| 292 | // "l5:hello5:worldei10e", |
| 293 | |
| 294 | for value in &values { |
| 295 | let error = Vec::<Something>::from_bencode(value.as_bytes()).unwrap_err(); |
| 296 | assert!(error.to_string().contains("encoding corrupted")); |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | #[test] |
| 301 | fn illegal_dictionary_encodings() { |
| 302 | let values = [ |
| 303 | "d", |
| 304 | "duuuuure", |
| 305 | "d5:hello5:world", |
| 306 | "d10:helloi123456789ee", |
| 307 | "d5:helloi123456789e5:helloe", |
| 308 | "di10e5:hello5:worldi10ee", |
| 309 | "d5:worldi10ei10e5:helloe", |
| 310 | "dle5:hello5:worldi10ee", |
| 311 | "dli10ei11ee5:hello5:worldi10ee", |
| 312 | "dde5:hello5:worldi10ee", |
| 313 | "dd8:innermapi11ee5:hello5:worldi10ee", |
| 314 | ]; |
| 315 | // Bendy currently doesn't fail if it encounters unused tokens |
| 316 | // |
| 317 | // "d5:hello5:worldei10e", |
| 318 | |
| 319 | for value in &values { |
| 320 | let error = BTreeMap::<String, Something>::from_bencode(value.as_bytes()).unwrap_err(); |
| 321 | assert!(error.to_string().contains("encoding corrupted")); |
| 322 | } |
| 323 | } |
| 324 | |
| 325 | // ----------------------------------------------------------------------------- |
| 326 | // Dynamic Typing Utility |
| 327 | // ----------------------------------------------------------------------------- |
| 328 | |
| 329 | #[derive(Debug, PartialEq)] |
| 330 | enum Something { |
| 331 | Bytes(String), |
| 332 | Dict(BTreeMap<String, Something>), |
| 333 | Integer(i64), |
| 334 | List(Vec<Something>), |
| 335 | } |
| 336 | |
| 337 | impl From<&str> for Something { |
| 338 | fn from(content: &str) -> Self { |
| 339 | Something::Bytes(content.to_owned()) |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | impl<ContentT> From<BTreeMap<String, ContentT>> for Something |
| 344 | where |
| 345 | Something: From<ContentT>, |
| 346 | { |
| 347 | fn from(content: BTreeMap<String, ContentT>) -> Self { |
| 348 | let content = content |
| 349 | .into_iter() |
| 350 | .map(|(key, value)| (key, value.into())) |
| 351 | .collect(); |
| 352 | |
| 353 | Something::Dict(content) |
| 354 | } |
| 355 | } |
| 356 | |
| 357 | impl From<i64> for Something { |
| 358 | fn from(content: i64) -> Self { |
| 359 | Something::Integer(content) |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | impl<ContentT> From<Vec<ContentT>> for Something |
| 364 | where |
| 365 | Something: From<ContentT>, |
| 366 | { |
| 367 | fn from(content: Vec<ContentT>) -> Self { |
| 368 | let content = content.into_iter().map(Into::into).collect(); |
| 369 | Something::List(content) |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | impl FromBencode for Something { |
| 374 | fn decode_bencode_object(object: Object) -> Result<Self, DecodingError> |
| 375 | where |
| 376 | Self: Sized, |
| 377 | { |
| 378 | let something = match object { |
| 379 | Object::Bytes(content) => { |
| 380 | Something::Bytes(String::from_utf8_lossy(content).to_string()) |
| 381 | }, |
| 382 | Object::Integer(number) => Something::Integer(number.parse().unwrap()), |
| 383 | object @ Object::Dict(_) => { |
| 384 | Something::Dict(BTreeMap::decode_bencode_object(object).unwrap()) |
| 385 | }, |
| 386 | object @ Object::List(_) => { |
| 387 | Something::List(Vec::decode_bencode_object(object).unwrap()) |
| 388 | }, |
| 389 | }; |
| 390 | |
| 391 | Ok(something) |
| 392 | } |
| 393 | } |
| 394 | |
| 395 | impl ToBencode for Something { |
| 396 | const MAX_DEPTH: usize = 999; |
| 397 | |
| 398 | fn encode(&self, encoder: SingleItemEncoder) -> Result<(), EncodingError> { |
| 399 | match self { |
| 400 | Something::Bytes(content) => encoder.emit(content), |
| 401 | Something::Dict(content) => encoder.emit(content), |
| 402 | Something::Integer(content) => encoder.emit(content), |
| 403 | Something::List(content) => encoder.emit(content), |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | // ----------------------------------------------------------------------------- |
| 409 | // Error |
| 410 | // ----------------------------------------------------------------------------- |
| 411 | |
| 412 | #[allow(dead_code)] |
| 413 | #[derive(Debug)] |
| 414 | enum Error { |
| 415 | DecodingError(DecodingError), |
| 416 | EncodingError(EncodingError), |
| 417 | } |
| 418 | |
| 419 | impl From<DecodingError> for Error { |
| 420 | fn from(error: DecodingError) -> Self { |
| 421 | Error::DecodingError(error) |
| 422 | } |
| 423 | } |
| 424 | |
| 425 | impl From<EncodingError> for Error { |
| 426 | fn from(error: EncodingError) -> Self { |
| 427 | Error::EncodingError(error) |
| 428 | } |
| 429 | } |