lots of work on parts 05 and 06
[rust-101.git] / src / part08.rs
1 use std::cmp;
2 use std::ops;
3 use std::fmt;
4 use part05::BigInt;
5
6 impl PartialEq for BigInt {
7     fn eq(&self, other: &BigInt) -> bool {
8         debug_assert!(self.test_invariant() && other.test_invariant());
9         self.data == other.data
10     }
11 }
12
13 fn call_eq() {
14     let b1 = BigInt::new(13);
15     let b2 = BigInt::new(37);
16     println!("b1 == b1: {} ; b1 == b2: {}; b1 != b2: {}", b1 == b1, b1 == b2, b1 != b2);
17 }
18
19
20 impl fmt::Debug for BigInt {
21     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
22         self.data.fmt(f)
23     }
24 }
25
26
27
28 impl BigInt {
29     pub fn inc(&mut self, mut by: u64) {
30         panic!("Not yet implemented.");
31     }
32 }
33
34
35 #[test]
36 fn test_inc() {
37     let mut b = BigInt::new(1337);
38     b.inc(1337);
39     assert!(b == BigInt::new(1337 + 1337));
40
41     b = BigInt::new(0);
42     assert_eq!(b, BigInt::from_vec(vec![0]));
43     b.inc(1 << 63);
44     assert_eq!(b, BigInt::from_vec(vec![1 << 63]));
45     b.inc(1 << 63);
46     assert_eq!(b, BigInt::from_vec(vec![0, 1]));
47     b.inc(1 << 63);
48     assert_eq!(b, BigInt::from_vec(vec![1 << 63, 1]));
49     b.inc(1 << 63);
50     assert_eq!(b, BigInt::from_vec(vec![0, 2]));
51 }
52
53
54 // Add with carry, returning the sum and the carry
55 fn overflowing_add(a: u64, b: u64, carry: bool) -> (u64, bool) {
56     let sum = u64::wrapping_add(a, b);
57     if sum >= a {
58         panic!("First addition did not overflow. Not implemented.");
59     } else {
60         panic!("First addition *did* overflow. Not implemented.");
61     }
62 }
63
64 /*#[test]*/
65 fn test_overflowing_add() {
66     assert_eq!(overflowing_add(10, 100, false), (110, false));
67     assert_eq!(overflowing_add(10, 100, true), (111, false));
68     assert_eq!(overflowing_add(1 << 63, 1 << 63, false), (0, true));
69     assert_eq!(overflowing_add(1 << 63, 1 << 63, true), (1, true));
70     assert_eq!(overflowing_add(1 << 63, (1 << 63) -1 , true), (0, true));
71 }
72
73 impl ops::Add for BigInt {
74     type Output = BigInt;
75     fn add(self, rhs: BigInt) -> Self::Output {
76         let mut result_vec:Vec<u64> = Vec::with_capacity(cmp::max(self.data.len(), rhs.data.len()));
77         panic!("Not yet implemented.");
78     }
79 }