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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
use super::types::*;
use itertools::Itertools;
use num_bigint::BigInt;
use std::cmp::Ordering;
use std::collections::BTreeMap;
use std::io;
use std::result::Result;

/// `Encode` is a trait to encode a [Bencodex] value.
///
/// [Bencodex]: https://bencodex.org/
pub trait Encode {
    /// Encode a [Bencodex] value from this type.
    ///
    /// If encoding succeeds, return [`Ok`]. Otherwise, it will pass [`std::io::Error`] occurred in inner logic.
    ///
    /// # Examples
    /// Basic usage with [`BencodexValue::Text`]:
    /// ```
    /// use bencodex::{ Encode, BencodexValue };
    ///
    /// let text = BencodexValue::Text("text".to_string());
    /// let mut vec = Vec::new();
    /// text.encode(&mut vec);
    ///
    /// assert_eq!(vec, vec![b'u', b'4', b':', b't', b'e', b'x', b't']);
    /// ```
    /// [Bencodex]: https://bencodex.org/
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error>;
}

impl Encode for Vec<u8> {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        write!(writer, "{}:", self.len())?;
        writer.write(&self)?;

        Ok(())
    }
}

impl Encode for i64 {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        write!(writer, "i{}e", self)
    }
}

impl Encode for String {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        let bytes = self.into_bytes();
        write!(writer, "u{}:", bytes.len())?;
        writer.write(&bytes)?;

        Ok(())
    }
}

impl Encode for bool {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        writer.write(match self {
            true => &[b't'],
            false => &[b'f'],
        })?;

        Ok(())
    }
}

impl Encode for BigInt {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        writer.write(&[b'i'])?;
        writer.write(&self.to_str_radix(10).into_bytes())?;
        writer.write(&[b'e'])?;

        Ok(())
    }
}

impl Encode for Vec<BencodexValue> {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        writer.write(&[b'l'])?;
        for el in self {
            el.encode(writer)?;
        }
        writer.write(&[b'e'])?;

        Ok(())
    }
}

impl Encode for () {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        writer.write(&[b'n'])?;

        Ok(())
    }
}

impl Encode for BencodexValue {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        // FIXME: rewrite more beautiful.
        match self {
            BencodexValue::Binary(x) => x.encode(writer)?,
            BencodexValue::Text(x) => x.encode(writer)?,
            BencodexValue::Dictionary(x) => x.encode(writer)?,
            BencodexValue::List(x) => x.encode(writer)?,
            BencodexValue::Boolean(x) => x.encode(writer)?,
            BencodexValue::Null(x) => x.encode(writer)?,
            BencodexValue::Number(x) => x.encode(writer)?,
        }

        Ok(())
    }
}

fn compare_vector<T: Ord>(xs: &[T], ys: &[T]) -> Ordering {
    for (x, y) in xs.iter().zip(ys) {
        match x.cmp(&y) {
            Ordering::Equal => continue,
            Ordering::Greater => return Ordering::Greater,
            Ordering::Less => return Ordering::Less,
        };
    }

    xs.len().cmp(&ys.len())
}

fn compare_key(x: &BencodexKey, y: &BencodexKey) -> Ordering {
    match (x, y) {
        (BencodexKey::Text(x), BencodexKey::Text(y)) => compare_vector(x.as_bytes(), y.as_bytes()),
        (BencodexKey::Binary(x), BencodexKey::Binary(y)) => compare_vector(x, y),
        (BencodexKey::Text(_), BencodexKey::Binary(_)) => Ordering::Greater,
        (BencodexKey::Binary(_), BencodexKey::Text(_)) => Ordering::Less,
    }
}

impl Encode for BTreeMap<BencodexKey, BencodexValue> {
    fn encode(self, writer: &mut dyn io::Write) -> Result<(), std::io::Error> {
        let pairs = self
            .into_iter()
            .sorted_by(|(x, _), (y, _)| compare_key(x, y));

        writer.write(&[b'd'])?;
        for (key, value) in pairs {
            let key = match key {
                BencodexKey::Binary(x) => BencodexValue::Binary(x),
                BencodexKey::Text(x) => BencodexValue::Text(x),
            };

            key.encode(writer)?;
            value.encode(writer)?;
        }
        writer.write(&[b'e'])?;

        Ok(())
    }
}

#[cfg(test)]
mod tests {
    mod compare_key {
        use super::super::*;

        #[test]
        fn should_return_equal() {
            assert_eq!(
                Ordering::Equal,
                compare_key(
                    &BencodexKey::Text("foo".to_string()),
                    &BencodexKey::Text("foo".to_string())
                )
            );
            assert_eq!(
                Ordering::Equal,
                compare_key(
                    &BencodexKey::Binary(b"bar".to_vec()),
                    &BencodexKey::Binary(b"bar".to_vec())
                )
            );
        }

        #[test]
        fn should_return_greater() {
            assert_eq!(
                Ordering::Greater,
                compare_key(
                    &BencodexKey::Text("".to_string()),
                    &BencodexKey::Binary(b"".to_vec())
                )
            );
        }

        #[test]
        fn should_return_less() {
            assert_eq!(
                Ordering::Less,
                compare_key(
                    &BencodexKey::Binary(b"".to_vec()),
                    &BencodexKey::Text("".to_string())
                )
            );
        }
    }

    mod compare_vector {
        use super::super::*;

        #[test]
        fn should_return_equal() {
            assert_eq!(
                Ordering::Equal,
                compare_vector(&Vec::<u8>::new(), &Vec::<u8>::new())
            );
            assert_eq!(
                Ordering::Equal,
                compare_vector(&vec![1, 2, 3], &vec![1, 2, 3])
            );
        }

        #[test]
        fn should_return_less() {
            assert_eq!(Ordering::Less, compare_vector(&vec![], &vec![3]));
            assert_eq!(Ordering::Less, compare_vector(&vec![0], &vec![1, 2, 3]));
            assert_eq!(Ordering::Less, compare_vector(&vec![1], &vec![9, 1, 1]));
            assert_eq!(Ordering::Less, compare_vector(&vec![1, 2], &vec![1, 2, 3]));
            assert_eq!(
                Ordering::Less,
                compare_vector(&vec![1, 9, 9], &vec![9, 1, 1])
            );
        }

        #[test]
        fn should_return_greater() {
            assert_eq!(Ordering::Greater, compare_vector(&vec![9], &vec![]));
            assert_eq!(Ordering::Greater, compare_vector(&vec![9], &vec![1, 2, 3]));
            assert_eq!(
                Ordering::Greater,
                compare_vector(&vec![1, 9, 2], &vec![1, 2, 2])
            );
        }
    }

    mod encode {
        struct ConditionFailWriter {
            throw_counts: Vec<u64>,
            call_count: u64,
        }

        impl ConditionFailWriter {
            fn new(throw_counts: Vec<u64>) -> ConditionFailWriter {
                ConditionFailWriter {
                    throw_counts: throw_counts,
                    call_count: 0,
                }
            }
        }

        #[cfg(not(tarpaulin_include))]
        impl std::io::Write for ConditionFailWriter {
            fn write(&mut self, bytes: &[u8]) -> std::result::Result<usize, std::io::Error> {
                self.call_count += 1;
                if self.throw_counts.contains(&self.call_count) {
                    Err(std::io::Error::new(std::io::ErrorKind::Other, ""))
                } else {
                    Ok(bytes.len())
                }
            }

            fn flush(&mut self) -> std::result::Result<(), std::io::Error> {
                Ok(())
            }
        }

        mod null {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue = ();

                // write 'n'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod vec_u8 {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue = Vec::<u8>::new();

                // write length
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'e'
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write bytes
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod btree_map {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_order_keys() {
                let mut bvalue: BTreeMap<BencodexKey, BencodexValue> = BTreeMap::new();
                bvalue.insert(BencodexKey::Text("ua".to_string()), BencodexValue::Null(()));
                bvalue.insert(BencodexKey::Binary(vec![b'a']), BencodexValue::Null(()));
                bvalue.insert(BencodexKey::Text("ub".to_string()), BencodexValue::Null(()));
                bvalue.insert(BencodexKey::Binary(vec![b'b']), BencodexValue::Null(()));

                let mut writer = Vec::new();
                assert!(bvalue.to_owned().encode(&mut writer).is_ok());
                assert_eq!(b"d1:an1:bnu2:uanu2:ubne".to_vec(), writer);
            }

            #[test]
            fn should_pass_error() {
                let mut bvalue: BTreeMap<BencodexKey, BencodexValue> = BTreeMap::new();
                bvalue.insert(BencodexKey::Text("".to_string()), BencodexValue::Null(()));

                // write 'd'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'u' key prefix
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write '{}' key bytes length
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write ":" key delimeter
                let mut writer = ConditionFailWriter::new(vec![4]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write "" key bytes
                let mut writer = ConditionFailWriter::new(vec![5]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write value
                let mut writer = ConditionFailWriter::new(vec![6]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'e'
                let mut writer = ConditionFailWriter::new(vec![7]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod vec_bvalue {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue: &mut Vec<BencodexValue> = &mut Vec::new();
                bvalue.push(BencodexValue::Null(()));

                // write 'l'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write value
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'e'
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod string {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue: String = String::new();

                // write 'u'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write length
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write ':'
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write text
                let mut writer = ConditionFailWriter::new(vec![4]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod bool {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue = true;

                // write 't'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod big_int {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue = BigInt::from(0);

                // write 'i'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write number
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'e'
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.to_owned().encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }

        mod i64 {
            use super::super::super::*;
            use super::*;

            #[test]
            fn should_pass_error() {
                let bvalue: i64 = 0;
                // write 'i'
                let mut writer = ConditionFailWriter::new(vec![1]);
                let err = bvalue.encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write number
                let mut writer = ConditionFailWriter::new(vec![2]);
                let err = bvalue.encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());

                // write 'e'
                let mut writer = ConditionFailWriter::new(vec![3]);
                let err = bvalue.encode(&mut writer).unwrap_err();
                assert_eq!(std::io::ErrorKind::Other, err.kind());
                assert_eq!("", err.to_string());
            }
        }
    }
}