diff --git a/exercises/allergies/example.rs b/exercises/allergies/example.rs index d2bf3c9f8..d6c795d3d 100644 --- a/exercises/allergies/example.rs +++ b/exercises/allergies/example.rs @@ -1,7 +1,16 @@ pub struct Allergies(pub usize); #[derive(PartialEq, Debug)] -pub enum Allergen { Eggs, Peanuts, Shellfish, Strawberries, Tomatoes, Chocolate, Pollen, Cats } +pub enum Allergen { + Eggs, + Peanuts, + Shellfish, + Strawberries, + Tomatoes, + Chocolate, + Pollen, + Cats, +} impl Allergies { pub fn new(score: usize) -> Allergies { @@ -11,16 +20,27 @@ impl Allergies { pub fn is_allergic_to(&self, allergen: &Allergen) -> bool { let allergens = Allergies::allergens(); let index = allergens.iter().position(|x: &Allergen| x == allergen).unwrap(); - match self.0 & 1 << index { 0 => false, _ => true } + match self.0 & 1 << index { + 0 => false, + _ => true, + } } pub fn allergies(&self) -> Vec { - Allergies::allergens().into_iter().filter(|allergen| self.is_allergic_to(allergen)).collect() + Allergies::allergens() + .into_iter() + .filter(|allergen| self.is_allergic_to(allergen)) + .collect() } fn allergens() -> Vec { - vec![Allergen::Eggs, Allergen::Peanuts, Allergen::Shellfish, - Allergen::Strawberries, Allergen::Tomatoes, Allergen::Chocolate, - Allergen::Pollen, Allergen::Cats] + vec![Allergen::Eggs, + Allergen::Peanuts, + Allergen::Shellfish, + Allergen::Strawberries, + Allergen::Tomatoes, + Allergen::Chocolate, + Allergen::Pollen, + Allergen::Cats] } } diff --git a/exercises/beer-song/example.rs b/exercises/beer-song/example.rs index cb791f1ac..b2365e38d 100644 --- a/exercises/beer-song/example.rs +++ b/exercises/beer-song/example.rs @@ -1,25 +1,33 @@ -pub fn verse(n: i32) -> String { +pub fn verse(n: i32) -> String { match n { - 0 => "No more bottles of beer on the wall, no more bottles of beer.\n\ - Go to the store and buy some more, 99 bottles of beer on the wall.\n".to_string(), - 1 => "1 bottle of beer on the wall, 1 bottle of beer.\n\ - Take it down and pass it around, no more bottles of beer on the wall.\n".to_string(), - 2 => "2 bottles of beer on the wall, 2 bottles of beer.\n\ - Take one down and pass it around, 1 bottle of beer on the wall.\n".to_string(), - n if n > 2 && n <= 99 => - format!( - "{n} bottles of beer on the wall, {n} bottles of beer.\n\ - Take one down and pass it around, {n_minus_1} bottles of beer on the wall.\n", - n=n, - n_minus_1=n - 1), - _ => - panic!(), + 0 => { + "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and \ + buy some more, 99 bottles of beer on the wall.\n" + .to_string() + } + 1 => { + "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no \ + more bottles of beer on the wall.\n" + .to_string() + } + 2 => { + "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, \ + 1 bottle of beer on the wall.\n" + .to_string() + } + n if n > 2 && n <= 99 => { + format!("{n} bottles of beer on the wall, {n} bottles of beer.\nTake one down and \ + pass it around, {n_minus_1} bottles of beer on the wall.\n", + n = n, + n_minus_1 = n - 1) + } + _ => panic!(), } } pub fn sing(start: i32, end: i32) -> String { let mut song = Vec::new(); - for n in (end .. start + 1).rev() { + for n in (end..start + 1).rev() { song.push(verse(n)) } song.join("\n") diff --git a/exercises/beer-song/tests/beer-song.rs b/exercises/beer-song/tests/beer-song.rs index 1fddd3700..2d47cb115 100644 --- a/exercises/beer-song/tests/beer-song.rs +++ b/exercises/beer-song/tests/beer-song.rs @@ -2,35 +2,55 @@ extern crate beer_song as beer; #[test] fn test_verse_0() { - assert_eq!(beer::verse(0), "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"); + assert_eq!(beer::verse(0), + "No more bottles of beer on the wall, no more bottles of beer.\nGo to the store \ + and buy some more, 99 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_1() { - assert_eq!(beer::verse(1), "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n"); + assert_eq!(beer::verse(1), + "1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it \ + around, no more bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_2() { - assert_eq!(beer::verse(2), "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n"); + assert_eq!(beer::verse(2), + "2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it \ + around, 1 bottle of beer on the wall.\n"); } #[test] #[ignore] fn test_verse_8() { - assert_eq!(beer::verse(8), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n"); + assert_eq!(beer::verse(8), + "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it \ + around, 7 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_song_8_6() { - assert_eq!(beer::sing(8, 6), "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and pass it around, 5 bottles of beer on the wall.\n"); + assert_eq!(beer::sing(8, 6), + "8 bottles of beer on the wall, 8 bottles of beer.\nTake one down and pass it \ + around, 7 bottles of beer on the wall.\n\n7 bottles of beer on the wall, 7 \ + bottles of beer.\nTake one down and pass it around, 6 bottles of beer on the \ + wall.\n\n6 bottles of beer on the wall, 6 bottles of beer.\nTake one down and \ + pass it around, 5 bottles of beer on the wall.\n"); } #[test] #[ignore] fn test_song_3_0() { - assert_eq!(beer::sing(3, 0), "3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it around, 2 bottles of beer on the wall.\n\n2 bottles of beer on the wall, 2 bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the wall.\n\n1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on the wall, no more bottles of beer.\nGo to the store and buy some more, 99 bottles of beer on the wall.\n"); + assert_eq!(beer::sing(3, 0), + "3 bottles of beer on the wall, 3 bottles of beer.\nTake one down and pass it \ + around, 2 bottles of beer on the wall.\n\n2 bottles of beer on the wall, 2 \ + bottles of beer.\nTake one down and pass it around, 1 bottle of beer on the \ + wall.\n\n1 bottle of beer on the wall, 1 bottle of beer.\nTake it down and pass \ + it around, no more bottles of beer on the wall.\n\nNo more bottles of beer on \ + the wall, no more bottles of beer.\nGo to the store and buy some more, 99 \ + bottles of beer on the wall.\n"); } diff --git a/exercises/bob/example.rs b/exercises/bob/example.rs index 803b37c12..ec0213aac 100644 --- a/exercises/bob/example.rs +++ b/exercises/bob/example.rs @@ -1,8 +1,13 @@ pub fn reply(message: &str) -> &str { - if is_silence(message) { "Fine. Be that way!" } - else if is_yelling(message) { "Whoa, chill out!" } - else if is_question(message) { "Sure." } - else { "Whatever." } + if is_silence(message) { + "Fine. Be that way!" + } else if is_yelling(message) { + "Whoa, chill out!" + } else if is_question(message) { + "Sure." + } else { + "Whatever." + } } fn is_silence(message: &str) -> bool { diff --git a/exercises/bob/tests/bob.rs b/exercises/bob/tests/bob.rs index 31b7e9306..dba9d8a64 100644 --- a/exercises/bob/tests/bob.rs +++ b/exercises/bob/tests/bob.rs @@ -20,7 +20,8 @@ fn test_exclaiming() { #[test] #[ignore] fn test_asking() { - assert_eq!("Sure.", bob::reply("Does this cryogenic chamber make me look fat?")); + assert_eq!("Sure.", + bob::reply("Does this cryogenic chamber make me look fat?")); } #[test] @@ -32,7 +33,8 @@ fn test_shout_numbers() { #[test] #[ignore] fn test_shout_weird_characters() { - assert_eq!("Whoa, chill out!", bob::reply("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")); + assert_eq!("Whoa, chill out!", + bob::reply("ZOMG THE %^*@#$(*^ ZOMBIES ARE COMING!!11!!1!")); } #[test] @@ -52,4 +54,3 @@ fn test_non_question_with_question_mark() { fn test_silent_treatment() { assert_eq!("Fine. Be that way!", bob::reply("")); } - diff --git a/exercises/circular-buffer/example.rs b/exercises/circular-buffer/example.rs index c25477dbf..517ca9f16 100644 --- a/exercises/circular-buffer/example.rs +++ b/exercises/circular-buffer/example.rs @@ -13,13 +13,13 @@ pub struct CircularBuffer { impl CircularBuffer { // this circular buffer keeps an unallocated slot between the start and the end - // when the buffer is full. + // when the buffer is full. pub fn new(size: usize) -> CircularBuffer { - CircularBuffer { - buffer: vec![T::default(); size + 1], - size: size + 1, - start: 0, - end: 0 + CircularBuffer { + buffer: vec![T::default(); size + 1], + size: size + 1, + start: 0, + end: 0, } } @@ -36,12 +36,12 @@ impl CircularBuffer { pub fn write(&mut self, byte: T) -> Result<(), Error> { if self.is_full() { return Err(Error::FullBuffer); - } - + } + self.buffer[self.end] = byte; self.advance_end(); Ok(()) - + } pub fn overwrite(&mut self, byte: T) { @@ -73,5 +73,4 @@ impl CircularBuffer { fn advance_end(&mut self) { self.end = (self.end + 1) % self.size; } - } diff --git a/exercises/circular-buffer/tests/circular-buffer.rs b/exercises/circular-buffer/tests/circular-buffer.rs index c99dcc27f..fb0eacb37 100644 --- a/exercises/circular-buffer/tests/circular-buffer.rs +++ b/exercises/circular-buffer/tests/circular-buffer.rs @@ -65,7 +65,7 @@ mod tests { buffer.write('2'); assert_eq!(Err(Error::FullBuffer), buffer.write('3')); } - + #[test] #[ignore] fn overwrite_item_in_non_full_buffer() { @@ -94,20 +94,20 @@ mod tests { let mut buffer = CircularBuffer::new(2); buffer.write(1); buffer.write(2); - assert_eq!(1,buffer.read().unwrap()); + assert_eq!(1, buffer.read().unwrap()); buffer.write(-1); - assert_eq!(2,buffer.read().unwrap()); - assert_eq!(-1,buffer.read().unwrap()); + assert_eq!(2, buffer.read().unwrap()); + assert_eq!(-1, buffer.read().unwrap()); assert_eq!(Err(Error::EmptyBuffer), buffer.read()); } - + #[test] #[ignore] fn string_buffer() { let mut buffer = CircularBuffer::new(2); buffer.write("".to_string()); buffer.write("Testing".to_string()); - assert_eq!(0,buffer.read().unwrap().len()); - assert_eq!("Testing",buffer.read().unwrap()); + assert_eq!(0, buffer.read().unwrap().len()); + assert_eq!("Testing", buffer.read().unwrap()); } } diff --git a/exercises/difference-of-squares/example.rs b/exercises/difference-of-squares/example.rs index fab4a9c49..02488fa21 100644 --- a/exercises/difference-of-squares/example.rs +++ b/exercises/difference-of-squares/example.rs @@ -4,7 +4,7 @@ pub fn square_of_sum(n: usize) -> usize { } pub fn sum_of_squares(n: usize) -> usize { - (0..n+1).map(|x| x*x).fold(0, |accum, x| accum + x) + (0..n + 1).map(|x| x * x).fold(0, |accum, x| accum + x) } pub fn difference(n: usize) -> usize { diff --git a/exercises/dominoes/example.rs b/exercises/dominoes/example.rs index d4f951c07..426964dd0 100644 --- a/exercises/dominoes/example.rs +++ b/exercises/dominoes/example.rs @@ -8,7 +8,7 @@ pub type Domino = (usize, usize); /// dots and row dots. Positions are mirrored ((3,4) == (4,3)), except for positions with equal row /// and column numbers. struct AvailabilityTable { - m: Vec + m: Vec, } impl AvailabilityTable { @@ -17,20 +17,19 @@ impl AvailabilityTable { } fn get(&self, x: usize, y: usize) -> usize { - self.m[(x-1) * 6 + (y-1)] + self.m[(x - 1) * 6 + (y - 1)] } fn set(&mut self, x: usize, y: usize, v: usize) { let m = &mut self.m[..]; - m[(x-1) * 6 + (y-1)] = v; + m[(x - 1) * 6 + (y - 1)] = v; } fn add(&mut self, x: usize, y: usize) { if x == y { let n = self.get(x, y); self.set(x, y, n + 1) // Along the diagonal - } - else { + } else { let m = self.get(x, y); self.set(x, y, m + 1); let n = self.get(y, x); @@ -43,25 +42,23 @@ impl AvailabilityTable { if x == y { let n = self.get(x, y); self.set(x, y, n - 1) // Along the diagonal - } - else { + } else { let m = self.get(x, y); self.set(x, y, m - 1); let n = self.get(y, x); self.set(y, x, n - 1); } - } - else { + } else { // For this toy code hard explicit fail is best panic!("remove for 0 stones: ({:?}, {:?})", x, y) } } - + fn pop_first(&mut self, x: usize) -> Option { - for y in 1 .. 7 { + for y in 1..7 { if self.get(x, y) > 0 { self.remove(x, y); - return Some(y) + return Some(y); } } None @@ -70,12 +67,18 @@ impl AvailabilityTable { pub fn chain(dominoes: &Vec) -> Option> { match dominoes.len() { - 0 => Some(vec!()), - 1 => if dominoes[0].0 == dominoes[0].1 { Some(vec![dominoes[0]]) } else { None }, + 0 => Some(vec![]), + 1 => { + if dominoes[0].0 == dominoes[0].1 { + Some(vec![dominoes[0]]) + } else { + None + } + } _ => { // First check if the total number of each amount of dots is even, if not it's not // possible to complete a cycle. This follows from that it's an Eulerian path. - let mut v: Vec = vec!(0, 0, 0, 0, 0, 0); + let mut v: Vec = vec![0, 0, 0, 0, 0, 0]; // Keep the mutable borrow in a small scope here to allow v.iter(). { let vs = &mut v[..]; @@ -86,14 +89,13 @@ pub fn chain(dominoes: &Vec) -> Option> { } for n in v.iter() { if n % 2 != 0 { - return None + return None; } } let chain = chain_worker(dominoes); if chain.len() == dominoes.len() { Some(chain) - } - else { + } else { None } } diff --git a/exercises/dominoes/tests/dominoes.rs b/exercises/dominoes/tests/dominoes.rs index fc2e18c40..08d4b7882 100644 --- a/exercises/dominoes/tests/dominoes.rs +++ b/exercises/dominoes/tests/dominoes.rs @@ -6,10 +6,10 @@ type Domino = (usize, usize); #[derive(Debug)] enum CheckResult { - GotInvalid, // chain returned None + GotInvalid, // chain returned None Correct, - ChainingFailure(Vec), // failure to match the dots at the right side of one domino with - // the one on the left side of the next + ChainingFailure(Vec), /* failure to match the dots at the right side of one domino with + * the one on the left side of the next */ LengthMismatch(Vec), DominoMismatch(Vec), // different dominoes are used in input and output } @@ -17,19 +17,19 @@ enum CheckResult { fn normalize(d: &Domino) -> Domino { match d { &(m, n) if m > n => (n, m), - &(m, n) => (m, n) + &(m, n) => (m, n), } } fn check(input: &Vec) -> CheckResult { let output = match dominoes::chain(input) { None => return GotInvalid, - Some(o) => o + Some(o) => o, }; if input.len() != output.len() { return LengthMismatch(output); - } - else if input.len() == 0 { // and thus output.len() == 0 + } else if input.len() == 0 { + // and thus output.len() == 0 return Correct; } @@ -51,15 +51,14 @@ fn check(input: &Vec) -> CheckResult { for &(first, second) in iter { if n != first { fail = true; - break + break; } n = second } } if fail { ChainingFailure(output) - } - else { + } else { Correct } } @@ -68,22 +67,30 @@ fn assert_correct(input: &Vec) { match check(&input) { Correct => (), GotInvalid => panic!("Unexpectedly got invalid on input {:?}", input), - ChainingFailure(output) => panic!("Chaining failure for input {:?}, output {:?}", input, output), - LengthMismatch(output) => panic!("Length mismatch for input {:?}, output {:?}", input, output), - DominoMismatch(output) => panic!("Domino mismatch for input {:?}, output {:?}", input, output), + ChainingFailure(output) => { + panic!("Chaining failure for input {:?}, output {:?}", + input, + output) + } + LengthMismatch(output) => { + panic!("Length mismatch for input {:?}, output {:?}", input, output) + } + DominoMismatch(output) => { + panic!("Domino mismatch for input {:?}, output {:?}", input, output) + } } } #[test] fn empty_input_empty_output() { - let input = vec!(); - assert_eq!(dominoes::chain(&input), Some(vec!())); + let input = vec![]; + assert_eq!(dominoes::chain(&input), Some(vec![])); } #[test] #[ignore] fn singleton_input_singleton_output() { - let input = vec!((1, 1)); + let input = vec![(1, 1)]; assert_correct(&input); } @@ -97,7 +104,7 @@ fn singleton_that_cant_be_chained() { #[test] #[ignore] fn no_repeat_numbers() { - let input = vec!((1, 2), (3, 1), (2, 3)); + let input = vec![(1, 2), (3, 1), (2, 3)]; assert_correct(&input); } @@ -111,7 +118,7 @@ fn can_reverse_dominoes() { #[test] #[ignore] fn no_chains() { - let input = vec!((1, 2), (4, 1), (2, 3)); + let input = vec![(1, 2), (4, 1), (2, 3)]; assert_eq!(dominoes::chain(&input), None); } @@ -153,6 +160,6 @@ fn separate_loops() { #[test] #[ignore] fn ten_elements() { - let input = vec!((1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6)); + let input = vec![(1, 2), (5, 3), (3, 1), (1, 2), (2, 4), (1, 6), (2, 3), (3, 4), (5, 6)]; assert_correct(&input); } diff --git a/exercises/etl/tests/etl.rs b/exercises/etl/tests/etl.rs index 265db5a8f..e2c7c9537 100644 --- a/exercises/etl/tests/etl.rs +++ b/exercises/etl/tests/etl.rs @@ -4,13 +4,9 @@ use std::collections::BTreeMap; #[test] fn test_transform_one_value() { - let input = input_from(&[ - (1, vec!("WORLD")), - ]); + let input = input_from(&[(1, vec!["WORLD"])]); - let expected = expected_from(&[ - ("world", 1), - ]); + let expected = expected_from(&[("world", 1)]); assert_eq!(expected, etl::transform(&input)); } @@ -18,13 +14,9 @@ fn test_transform_one_value() { #[test] #[ignore] fn test_transform_more_values() { - let input = input_from(&[ - (1, vec!("WORLD", "GSCHOOLERS")), - ]); + let input = input_from(&[(1, vec!["WORLD", "GSCHOOLERS"])]); - let expected = expected_from(&[ - ("world", 1), ("gschoolers", 1), - ]); + let expected = expected_from(&[("world", 1), ("gschoolers", 1)]); assert_eq!(expected, etl::transform(&input)); } @@ -32,15 +24,9 @@ fn test_transform_more_values() { #[test] #[ignore] fn test_more_keys() { - let input = input_from(&[ - (1, vec!("APPLE", "ARTICHOKE")), - (2, vec!("BOAT", "BALLERINA")), - ]); + let input = input_from(&[(1, vec!["APPLE", "ARTICHOKE"]), (2, vec!["BOAT", "BALLERINA"])]); - let expected = expected_from(&[ - ("apple", 1), ("artichoke", 1), - ("boat", 2), ("ballerina", 2), - ]); + let expected = expected_from(&[("apple", 1), ("artichoke", 1), ("boat", 2), ("ballerina", 2)]); assert_eq!(expected, etl::transform(&input)); } @@ -48,25 +34,19 @@ fn test_more_keys() { #[test] #[ignore] fn test_full_dataset() { - let input = input_from(&[ - (1, vec!("A", "E", "I", "O", "U", "L", "N", "R", "S", "T")), - (2, vec!("D", "G")), - (3, vec!("B", "C", "M", "P")), - (4, vec!("F", "H", "V", "W", "Y")), - (5, vec!("K")), - (8, vec!("J", "X")), - (10, vec!("Q", "Z")), - ]); + let input = input_from(&[(1, vec!["A", "E", "I", "O", "U", "L", "N", "R", "S", "T"]), + (2, vec!["D", "G"]), + (3, vec!["B", "C", "M", "P"]), + (4, vec!["F", "H", "V", "W", "Y"]), + (5, vec!["K"]), + (8, vec!["J", "X"]), + (10, vec!["Q", "Z"])]); - let expected = expected_from(&[ - ("a", 1), ("b", 3), ("c", 3), ("d", 2), - ("e", 1), ("f", 4), ("g", 2), ("h", 4), - ("i", 1), ("j", 8), ("k", 5), ("l", 1), - ("m", 3), ("n", 1), ("o", 1), ("p", 3), - ("q", 10), ("r", 1), ("s", 1), ("t", 1), - ("u", 1), ("v", 4), ("w", 4), ("x", 8), - ("y", 4), ("z", 10), - ]); + let expected = expected_from(&[("a", 1), ("b", 3), ("c", 3), ("d", 2), ("e", 1), ("f", 4), + ("g", 2), ("h", 4), ("i", 1), ("j", 8), ("k", 5), ("l", 1), + ("m", 3), ("n", 1), ("o", 1), ("p", 3), ("q", 10), ("r", 1), + ("s", 1), ("t", 1), ("u", 1), ("v", 4), ("w", 4), ("x", 8), + ("y", 4), ("z", 10)]); assert_eq!(expected, etl::transform(&input)); } diff --git a/exercises/forth/example.rs b/exercises/forth/example.rs index f6b96cedb..ed2a301b5 100644 --- a/exercises/forth/example.rs +++ b/exercises/forth/example.rs @@ -42,7 +42,7 @@ impl FromStr for Term { match s { ":" => Ok(StartDefinition), ";" => Ok(EndDefinition), - _ => Err(()) + _ => Err(()), } .or_else(|_| Value::from_str(s).map(Number)) .or_else(|_| Ok(Word(s.to_ascii_lowercase()))) @@ -59,9 +59,7 @@ impl Forth { } pub fn format_stack(&self) -> String { - let mut s = self.stack.iter().fold(String::new(), |s, v| { - s + &v.to_string() + " " - }); + let mut s = self.stack.iter().fold(String::new(), |s, v| s + &v.to_string() + " "); s.pop(); s } @@ -76,7 +74,7 @@ impl Forth { loop { match self.code.pop_front() { Some(term) => try!(self.step_term(term)), - None => break, + None => break, } } @@ -85,15 +83,16 @@ impl Forth { fn step_term(&mut self, term: Term) -> ForthResult { match term { - Number(value) => self.push(value), - Word(word) => self.step_word(word), + Number(value) => self.push(value), + Word(word) => self.step_word(word), StartDefinition => self.store_definition(), - EndDefinition => Err(Error::InvalidWord), + EndDefinition => Err(Error::InvalidWord), } } fn step_word(&mut self, word: String) -> ForthResult { - self.defs.get(&word) + self.defs + .get(&word) .ok_or(Error::UnknownWord) .map(Clone::clone) .map(|mut code| self.code.append(&mut code)) @@ -102,32 +101,17 @@ impl Forth { fn step_built_in(&mut self, word: &String) -> ForthResult { match word.as_ref() { - "+" => - self.bin_op(|(a, b)| Ok(a + b)), - "-" => - self.bin_op(|(a, b)| Ok(a - b)), - "*" => - self.bin_op(|(a, b)| Ok(a * b)), - "/" => - self.bin_op(|(a, b)| { - a.checked_div(b).ok_or(Error::DivisionByZero) - }), - "dup" => - self.pop().and_then(|a| { - self.push(a).and(self.push(a)) - }), - "drop" => - self.pop().and(Forth::ok()), - "swap" => - self.pop_two().and_then(|(a, b)| { - self.push(b).and(self.push(a)) - }), - "over" => - self.pop_two().and_then(|(a, b)| { - self.push(a).and(self.push(b)).and(self.push(a)) - }), - _ => - Err(Error::UnknownWord) + "+" => self.bin_op(|(a, b)| Ok(a + b)), + "-" => self.bin_op(|(a, b)| Ok(a - b)), + "*" => self.bin_op(|(a, b)| Ok(a * b)), + "/" => self.bin_op(|(a, b)| a.checked_div(b).ok_or(Error::DivisionByZero)), + "dup" => self.pop().and_then(|a| self.push(a).and(self.push(a))), + "drop" => self.pop().and(Forth::ok()), + "swap" => self.pop_two().and_then(|(a, b)| self.push(b).and(self.push(a))), + "over" => { + self.pop_two().and_then(|(a, b)| self.push(a).and(self.push(b)).and(self.push(a))) + } + _ => Err(Error::UnknownWord), } } @@ -137,8 +121,8 @@ impl Forth { loop { match self.code.pop_front() { Some(EndDefinition) => break, - Some(term) => def.push_back(term), - None => return Err(Error::InvalidWord), + Some(term) => def.push_back(term), + None => return Err(Error::InvalidWord), } } @@ -155,7 +139,8 @@ impl Forth { } fn pop(&mut self) -> StackResult { - self.stack.pop_back() + self.stack + .pop_back() .ok_or(Error::StackUnderflow) } @@ -168,7 +153,8 @@ impl Forth { } fn bin_op(&mut self, op: F) -> ForthResult - where F: FnOnce((Value, Value)) -> StackResult { + where F: FnOnce((Value, Value)) -> StackResult + { self.pop_two() .and_then(op) .and_then(|value| self.push(value)) @@ -180,13 +166,14 @@ impl Forth { } fn into_code(input: &str) -> LinkedList { - input - .split(|c: char| c.is_whitespace() || c.is_control()) - .map(Term::from_str) - .filter(Result::is_ok) - .map(Result::unwrap) - .collect() + input.split(|c: char| c.is_whitespace() || c.is_control()) + .map(Term::from_str) + .filter(Result::is_ok) + .map(Result::unwrap) + .collect() } - fn ok() -> ForthResult { Ok(()) } + fn ok() -> ForthResult { + Ok(()) + } } diff --git a/exercises/forth/src/lib.rs b/exercises/forth/src/lib.rs index 2b8e59647..3f26f8fc0 100644 --- a/exercises/forth/src/lib.rs +++ b/exercises/forth/src/lib.rs @@ -12,12 +12,9 @@ pub enum Error { } impl Forth { - pub fn new() -> Forth { - } + pub fn new() -> Forth {} - pub fn format_stack(&self) -> String { - } + pub fn format_stack(&self) -> String {} - pub fn eval(&mut self, input: &str) -> ForthResult { - } + pub fn eval(&mut self, input: &str) -> ForthResult {} } diff --git a/exercises/forth/tests/forth.rs b/exercises/forth/tests/forth.rs index 73ee0d9cd..330f5f99c 100644 --- a/exercises/forth/tests/forth.rs +++ b/exercises/forth/tests/forth.rs @@ -46,50 +46,35 @@ fn basic_arithmetic_2() { #[ignore] fn addition_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("+") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("+")); } #[test] #[ignore] fn subtraction_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("-") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("-")); } #[test] #[ignore] fn multiplication_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("*") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("*")); } #[test] #[ignore] fn division_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("/") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("/")); } #[test] #[ignore] fn division_by_zero() { let mut f = Forth::new(); - assert_eq!( - Err(Error::DivisionByZero), - f.eval("4 2 2 - /") - ); + assert_eq!(Err(Error::DivisionByZero), f.eval("4 2 2 - /")); } #[test] @@ -112,10 +97,7 @@ fn dup_case_insensitive() { #[ignore] fn dup_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("dup") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("dup")); } #[test] @@ -138,10 +120,7 @@ fn drop_with_two() { #[ignore] fn drop_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("drop") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("drop")); } #[test] @@ -164,14 +143,8 @@ fn swap_with_three() { #[ignore] fn swap_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("1 swap") - ); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("swap") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("1 swap")); + assert_eq!(Err(Error::StackUnderflow), f.eval("swap")); } #[test] @@ -194,14 +167,8 @@ fn over_with_three() { #[ignore] fn over_error() { let mut f = Forth::new(); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("1 over") - ); - assert_eq!( - Err(Error::StackUnderflow), - f.eval("over") - ); + assert_eq!(Err(Error::StackUnderflow), f.eval("1 over")); + assert_eq!(Err(Error::StackUnderflow), f.eval("over")); } #[test] @@ -244,36 +211,21 @@ fn defining_words_with_odd_characters() { #[ignore] fn defining_a_number() { let mut f = Forth::new(); - assert_eq!( - Err(Error::InvalidWord), - f.eval(": 1 2 ;") - ); + assert_eq!(Err(Error::InvalidWord), f.eval(": 1 2 ;")); } #[test] #[ignore] fn malformed_word_definition() { let mut f = Forth::new(); - assert_eq!( - Err(Error::InvalidWord), - f.eval(":") - ); - assert_eq!( - Err(Error::InvalidWord), - f.eval(": foo") - ); - assert_eq!( - Err(Error::InvalidWord), - f.eval(": foo 1") - ); + assert_eq!(Err(Error::InvalidWord), f.eval(":")); + assert_eq!(Err(Error::InvalidWord), f.eval(": foo")); + assert_eq!(Err(Error::InvalidWord), f.eval(": foo 1")); } #[test] #[ignore] fn calling_non_existing_word() { let mut f = Forth::new(); - assert_eq!( - Err(Error::UnknownWord), - f.eval("1 foo") - ); + assert_eq!(Err(Error::UnknownWord), f.eval("1 foo")); } diff --git a/exercises/gigasecond/tests/gigasecond.rs b/exercises/gigasecond/tests/gigasecond.rs index 92ebd1125..8e77002a6 100644 --- a/exercises/gigasecond/tests/gigasecond.rs +++ b/exercises/gigasecond/tests/gigasecond.rs @@ -1,50 +1,54 @@ extern crate gigasecond; -/* - * Students, - * - * Rust does not currently have a library for handling Time. To solve this exercise - * you'll need to use the Chrono 'crate' (which is Rust's term for an external library). - * - * The first time you run `cargo test`, the Chrono crate will automatically be downloaded - * and installed. More information on crates can be found at - * https://doc.rust-lang.org/book/guessing-game.html#generating-a-secret-number - * - * In order to use the crate, your solution will need to start with the two following lines -*/ +// Students, +// +// Rust does not currently have a library for handling Time. To solve this exercise +// you'll need to use the Chrono 'crate' (which is Rust's term for an external library). +// +// The first time you run `cargo test`, the Chrono crate will automatically be downloaded +// and installed. More information on crates can be found at +// https://doc.rust-lang.org/book/guessing-game.html#generating-a-secret-number +// +// In order to use the crate, your solution will need to start with the two following lines +// extern crate chrono; use chrono::*; #[test] fn test_date() { - let start_date = UTC.ymd(2011, 4, 25).and_hms(0,0,0); - assert_eq!(gigasecond::after(start_date), UTC.ymd(2043, 1, 1).and_hms(1,46,40)); + let start_date = UTC.ymd(2011, 4, 25).and_hms(0, 0, 0); + assert_eq!(gigasecond::after(start_date), + UTC.ymd(2043, 1, 1).and_hms(1, 46, 40)); } #[test] #[ignore] fn test_another_date() { - let start_date = UTC.ymd(1977, 6, 13).and_hms(0,0,0); - assert_eq!(gigasecond::after(start_date), UTC.ymd(2009, 2, 19).and_hms(1,46,40)); + let start_date = UTC.ymd(1977, 6, 13).and_hms(0, 0, 0); + assert_eq!(gigasecond::after(start_date), + UTC.ymd(2009, 2, 19).and_hms(1, 46, 40)); } #[test] #[ignore] fn test_third_date() { - let start_date = UTC.ymd(1959, 7, 19).and_hms(0,0,0); - assert_eq!(gigasecond::after(start_date), UTC.ymd(1991, 3, 27).and_hms(1,46,40)); + let start_date = UTC.ymd(1959, 7, 19).and_hms(0, 0, 0); + assert_eq!(gigasecond::after(start_date), + UTC.ymd(1991, 3, 27).and_hms(1, 46, 40)); } #[test] #[ignore] fn test_datetime() { - let start_date = UTC.ymd(2015, 1, 24).and_hms(22,0,0); - assert_eq!(gigasecond::after(start_date), UTC.ymd(2046, 10, 2).and_hms(23,46,40)); + let start_date = UTC.ymd(2015, 1, 24).and_hms(22, 0, 0); + assert_eq!(gigasecond::after(start_date), + UTC.ymd(2046, 10, 2).and_hms(23, 46, 40)); } #[test] #[ignore] fn test_another_datetime() { - let start_date = UTC.ymd(2015, 1, 24).and_hms(23,59,59); - assert_eq!(gigasecond::after(start_date), UTC.ymd(2046, 10, 3).and_hms(1,46,39)); + let start_date = UTC.ymd(2015, 1, 24).and_hms(23, 59, 59); + assert_eq!(gigasecond::after(start_date), + UTC.ymd(2046, 10, 3).and_hms(1, 46, 39)); } diff --git a/exercises/grade-school/example.rs b/exercises/grade-school/example.rs index 5e3811cc9..5924f2fb6 100644 --- a/exercises/grade-school/example.rs +++ b/exercises/grade-school/example.rs @@ -2,7 +2,7 @@ use std::collections::HashMap; use std::collections::hash_map::Entry; pub struct School { - grades: HashMap> + grades: HashMap>, } impl School { @@ -12,15 +12,17 @@ impl School { pub fn add(&mut self, grade: u32, student: &str) { match self.grades.entry(grade) { - Entry::Vacant(view) => { view.insert(vec![student.to_string()]); } + Entry::Vacant(view) => { + view.insert(vec![student.to_string()]); + } Entry::Occupied(mut view) => { let l = view.get_mut(); l.push(student.to_string()); l.sort(); - }, + } }; } - + pub fn grades(&self) -> Vec { let mut s = self.grades.keys().map(|k| k.clone()).collect::>(); s.sort(); diff --git a/exercises/grade-school/tests/grade-school.rs b/exercises/grade-school/tests/grade-school.rs index 3342df3df..a6355b55c 100644 --- a/exercises/grade-school/tests/grade-school.rs +++ b/exercises/grade-school/tests/grade-school.rs @@ -15,7 +15,7 @@ fn test_grades_for_empty_school() { fn test_grades_for_one_student() { let mut s = school::School::new(); s.add(2, "Aimee"); - assert_eq!(s.grades(), vec!(2)); + assert_eq!(s.grades(), vec![2]); } #[test] @@ -25,7 +25,7 @@ fn test_grades_for_several_students_are_sorted() { s.add(2, "Aimee"); s.add(7, "Logan"); s.add(4, "Blair"); - assert_eq!(s.grades(), vec!(2, 4, 7)); + assert_eq!(s.grades(), vec![2, 4, 7]); } #[test] @@ -35,7 +35,7 @@ fn test_grades_when_several_students_have_the_same_grade() { s.add(2, "Aimee"); s.add(2, "Logan"); s.add(2, "Blair"); - assert_eq!(s.grades(), vec!(2)); + assert_eq!(s.grades(), vec![2]); } #[test] @@ -59,7 +59,7 @@ fn test_grade_for_one_student() { let mut s = school::School::new(); s.add(2, "Aimee"); assert_eq!(s.grade(2).map(|v| stringvec_to_strvec(v)), - Some(vec!("Aimee"))) + Some(vec!["Aimee"])) } #[test] @@ -70,7 +70,7 @@ fn test_grade_returns_students_sorted_by_name() { s.add(2, "Blair"); s.add(2, "Paul"); assert_eq!(s.grade(2).map(|v| stringvec_to_strvec(v)), - Some(vec!("Blair", "James", "Paul"))); + Some(vec!["Blair", "James", "Paul"])); } #[test] @@ -79,9 +79,9 @@ fn test_add_students_to_different_grades() { let mut s = school::School::new(); s.add(3, "Chelsea"); s.add(7, "Logan"); - assert_eq!(s.grades(), vec!(3, 7)); + assert_eq!(s.grades(), vec![3, 7]); assert_eq!(s.grade(3).map(|v| stringvec_to_strvec(v)), - Some(vec!("Chelsea"))); + Some(vec!["Chelsea"])); assert_eq!(s.grade(7).map(|v| stringvec_to_strvec(v)), - Some(vec!("Logan"))); + Some(vec!["Logan"])); } diff --git a/exercises/hamming/example.rs b/exercises/hamming/example.rs index 28f8efd38..c09f2047f 100644 --- a/exercises/hamming/example.rs +++ b/exercises/hamming/example.rs @@ -1,7 +1,7 @@ -pub fn hamming_distance(a : &str, b: &str) -> Result { +pub fn hamming_distance(a: &str, b: &str) -> Result { if a.len() != b.len() { return Result::Err("inputs of different length"); } - + Result::Ok(a.chars().zip(b.chars()).filter(|&(a, b)| a != b).count()) } diff --git a/exercises/hamming/tests/hamming.rs b/exercises/hamming/tests/hamming.rs index d0dd74a2b..22a69bb3e 100644 --- a/exercises/hamming/tests/hamming.rs +++ b/exercises/hamming/tests/hamming.rs @@ -32,11 +32,13 @@ fn test_larger_distance() { #[test] #[ignore] fn test_first_string_is_longer() { - assert_eq!(dna::hamming_distance("AAA", "AA"), Result::Err("inputs of different length")); + assert_eq!(dna::hamming_distance("AAA", "AA"), + Result::Err("inputs of different length")); } #[test] #[ignore] fn test_second_string_is_longer() { - assert_eq!(dna::hamming_distance("A", "AA"), Result::Err("inputs of different length")); + assert_eq!(dna::hamming_distance("A", "AA"), + Result::Err("inputs of different length")); } diff --git a/exercises/hexadecimal/example.rs b/exercises/hexadecimal/example.rs index 2e8d8f45c..35c53f9be 100644 --- a/exercises/hexadecimal/example.rs +++ b/exercises/hexadecimal/example.rs @@ -16,21 +16,18 @@ fn parse_hex_digit(c: char) -> Option { 'd' => Some(13), 'e' => Some(14), 'f' => Some(15), - _ => None, + _ => None, } } pub fn hex_to_int(string: &str) -> Option { let base: i64 = 16; - let positions = 0 .. string.len() as u32; + let positions = 0..string.len() as u32; - string - .chars() - .rev() - .zip(positions) - .fold(Some(0), |acc, (c, pos)| { - parse_hex_digit(c).and_then(|n| { - acc.map(|acc| acc + n * base.pow(pos)) - }) - }) + string.chars() + .rev() + .zip(positions) + .fold(Some(0), |acc, (c, pos)| { + parse_hex_digit(c).and_then(|n| acc.map(|acc| acc + n * base.pow(pos))) + }) } diff --git a/exercises/minesweeper/example.rs b/exercises/minesweeper/example.rs index 96ec17b4d..b50f50f60 100644 --- a/exercises/minesweeper/example.rs +++ b/exercises/minesweeper/example.rs @@ -1,7 +1,7 @@ struct Board { pieces: Vec>, num_rows: usize, - num_cols: usize + num_cols: usize, } impl Board { @@ -11,10 +11,16 @@ impl Board { fn annotated_row(&self, y: usize) -> String { self.pieces[y] - .iter() - .enumerate() - .map(|(x,&c)| if c == ' ' {self.count_neighbouring_mines_char(x, y)} else {c}) - .collect::() + .iter() + .enumerate() + .map(|(x, &c)| { + if c == ' ' { + self.count_neighbouring_mines_char(x, y) + } else { + c + } + }) + .collect::() } fn count_neighbouring_mines_char(&self, x: usize, y: usize) -> char { @@ -37,16 +43,21 @@ impl Board { pub fn annotate(pieces: &[&str]) -> Vec { let pieces_vec = pieces.iter().map(|&r| r.chars().collect()).collect(); - Board {pieces: pieces_vec, num_rows: pieces.len(), num_cols: pieces[0].len()}.annotated() + Board { + pieces: pieces_vec, + num_rows: pieces.len(), + num_cols: pieces[0].len(), + } + .annotated() } fn neighbouring_points(x: usize, limit: usize) -> Vec { let mut offsets = vec![x]; if x >= 1 { - offsets.push(x-1); + offsets.push(x - 1); } - if x+2 <= limit { - offsets.push(x+1); + if x + 2 <= limit { + offsets.push(x + 1); } offsets } diff --git a/exercises/minesweeper/tests/minesweeper.rs b/exercises/minesweeper/tests/minesweeper.rs index 198b7c9ac..2c619993a 100644 --- a/exercises/minesweeper/tests/minesweeper.rs +++ b/exercises/minesweeper/tests/minesweeper.rs @@ -7,10 +7,14 @@ fn remove_annotations(board: &[&str]) -> Vec { } fn remove_annotations_in_row(row: &str) -> String { - row.chars().map(|ch| match ch { - '*' => '*', - _ => ' ' - }).collect() + row.chars() + .map(|ch| { + match ch { + '*' => '*', + _ => ' ', + } + }) + .collect() } fn run_test(test_case: &[&str]) { @@ -22,121 +26,71 @@ fn run_test(test_case: &[&str]) { #[test] fn empty_board_has_no_annotations() { - run_test(&[ - " ", - " ", - " " - ]); + run_test(&[" ", " ", " "]); } #[test] #[ignore] fn board_full_of_mines_has_no_annotations() { - run_test(&[ - "***", - "***", - "***" - ]); + run_test(&["***", "***", "***"]); } #[test] #[ignore] fn one_horizontal_row_with_one_mine() { - run_test(&[ - " 1*1 " - ]); + run_test(&[" 1*1 "]); } #[test] #[ignore] fn one_horizontal_row_with_two_mines() { - run_test(&[ - " 1*2*1 " - ]); + run_test(&[" 1*2*1 "]); } #[test] #[ignore] fn one_horizontal_row_with_one_mine_at_the_left_end() { - run_test(&[ - "*1 " - ]); + run_test(&["*1 "]); } #[test] #[ignore] fn one_horizontal_row_with_one_mine_at_the_right_end() { - run_test(&[ - " 1*" - ]); + run_test(&[" 1*"]); } #[test] #[ignore] fn one_vertical_row_with_one_mine() { - run_test(&[ - " ", - "1", - "*", - "1", - " ", - ]); + run_test(&[" ", "1", "*", "1", " "]); } #[test] #[ignore] fn one_vertical_row_with_two_mines() { - run_test(&[ - " ", - "1", - "*", - "2", - "*", - "1", - " ", - ]); + run_test(&[" ", "1", "*", "2", "*", "1", " "]); } #[test] #[ignore] fn one_vertical_row_with_one_mine_at_the_top() { - run_test(&[ - "*", - "1", - " ", - " ", - ]); + run_test(&["*", "1", " ", " "]); } #[test] #[ignore] fn one_vertical_row_with_one_mine_at_the_bottom() { - run_test(&[ - " ", - " ", - "1", - "*", - ]); + run_test(&[" ", " ", "1", "*"]); } #[test] #[ignore] fn one_mine_in_the_middle() { - run_test(&[ - "***", - "*8*", - "***" - ]); + run_test(&["***", "*8*", "***"]); } #[test] #[ignore] fn complex_case() { - run_test(&[ - " 2*2 ", - "25*52", - "*****", - "25*52", - " 2*2 ", - ]); -} \ No newline at end of file + run_test(&[" 2*2 ", "25*52", "*****", "25*52", " 2*2 "]); +} diff --git a/exercises/nucleotide-codons/example.rs b/exercises/nucleotide-codons/example.rs index 029d332db..97b800f59 100644 --- a/exercises/nucleotide-codons/example.rs +++ b/exercises/nucleotide-codons/example.rs @@ -1,17 +1,17 @@ use std::collections::HashMap; pub struct CodonInfo<'a> { - actual_codons: HashMap<&'a str, &'a str> + actual_codons: HashMap<&'a str, &'a str>, } pub fn parse<'a>(pairs: Vec<(&'a str, &'a str)>) -> CodonInfo<'a> { - let mut info = CodonInfo{ + let mut info = CodonInfo { // Allocate once for the worst case, shrink later. - actual_codons: HashMap::with_capacity(pairs.len()) + actual_codons: HashMap::with_capacity(pairs.len()), }; for (codon, name) in pairs.into_iter() { info.actual_codons.insert(codon, name); - }; + } info.actual_codons.shrink_to_fit(); info } @@ -19,24 +19,30 @@ pub fn parse<'a>(pairs: Vec<(&'a str, &'a str)>) -> CodonInfo<'a> { impl<'a> CodonInfo<'a> { pub fn name_for(&self, codon: &str) -> Result<&'a str, &'static str> { if codon.len() != 3 { - return Err("invalid length") + return Err("invalid length"); } let mut valid = true; - let lookup: String = codon.chars().map(|l| { - // Get an example of a "letter" represented by the possibly encoded letter. - // Since every codon represented by the compressed notation has to be of - // the desired amino acid just picking one at random will do. - match l { - 'A' | 'W' | 'M' | 'R' | 'D' | 'H' | 'V' | 'N' => 'A', - 'C' | 'S' | 'Y' | 'B' => 'C', - 'G' | 'K' => 'G', - 'T' => 'T', - _ => { valid = false; ' ' } - } - }).collect(); + let lookup: String = + codon.chars() + .map(|l| { + // Get an example of a "letter" represented by the possibly encoded letter. + // Since every codon represented by the compressed notation has to be of + // the desired amino acid just picking one at random will do. + match l { + 'A' | 'W' | 'M' | 'R' | 'D' | 'H' | 'V' | 'N' => 'A', + 'C' | 'S' | 'Y' | 'B' => 'C', + 'G' | 'K' => 'G', + 'T' => 'T', + _ => { + valid = false; + ' ' + } + } + }) + .collect(); if !valid { - return Err("invalid char") + return Err("invalid char"); } // If the input table is correct (which it is) every valid codon is in it diff --git a/exercises/nucleotide-codons/tests/codons.rs b/exercises/nucleotide-codons/tests/codons.rs index c2998e1cb..5b0c2d473 100644 --- a/exercises/nucleotide-codons/tests/codons.rs +++ b/exercises/nucleotide-codons/tests/codons.rs @@ -15,7 +15,8 @@ fn test_cysteine_tgt() { #[test] #[ignore] -fn test_cysteine_tgy() { // "compressed" name for TGT and TGC +fn test_cysteine_tgy() { + // "compressed" name for TGT and TGC let info = codons::parse(make_pairs()); assert_eq!(info.name_for("TGY"), Ok("cysteine")); } @@ -64,34 +65,33 @@ fn test_invalid() { // The input data constructor. Returns a list of codon, name pairs. fn make_pairs() -> Vec<(&'static str, &'static str)> { - let grouped = vec![ - ("isoleucine", vec!["ATT", "ATC", "ATA"]), - ("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]), - ("valine", vec!["GTT", "GTC", "GTA", "GTG"]), - ("phenylalanine", vec!["TTT", "TTC"]), - ("methionine", vec!["ATG"]), - ("cysteine", vec!["TGT", "TGC"]), - ("alanine", vec!["GCT", "GCC", "GCA", "GCG"]), - ("glycine", vec!["GGT", "GGC", "GGA", "GGG"]), - ("proline", vec!["CCT", "CCC", "CCA", "CCG"]), - ("threonine", vec!["ACT", "ACC", "ACA", "ACG"]), - ("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]), - ("tyrosine", vec!["TAT", "TAC"]), - ("tryptophan", vec!["TGG"]), - ("glutamine", vec!["CAA", "CAG"]), - ("asparagine", vec!["AAT", "AAC"]), - ("histidine", vec!["CAT", "CAC"]), - ("glutamic acid", vec!["GAA", "GAG"]), - ("aspartic acid", vec!["GAT", "GAC"]), - ("lysine", vec!["AAA", "AAG"]), - ("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]), - ("stop codon", vec!["TAA", "TAG", "TGA"])]; + let grouped = vec![("isoleucine", vec!["ATT", "ATC", "ATA"]), + ("leucine", vec!["CTT", "CTC", "CTA", "CTG", "TTA", "TTG"]), + ("valine", vec!["GTT", "GTC", "GTA", "GTG"]), + ("phenylalanine", vec!["TTT", "TTC"]), + ("methionine", vec!["ATG"]), + ("cysteine", vec!["TGT", "TGC"]), + ("alanine", vec!["GCT", "GCC", "GCA", "GCG"]), + ("glycine", vec!["GGT", "GGC", "GGA", "GGG"]), + ("proline", vec!["CCT", "CCC", "CCA", "CCG"]), + ("threonine", vec!["ACT", "ACC", "ACA", "ACG"]), + ("serine", vec!["TCT", "TCC", "TCA", "TCG", "AGT", "AGC"]), + ("tyrosine", vec!["TAT", "TAC"]), + ("tryptophan", vec!["TGG"]), + ("glutamine", vec!["CAA", "CAG"]), + ("asparagine", vec!["AAT", "AAC"]), + ("histidine", vec!["CAT", "CAC"]), + ("glutamic acid", vec!["GAA", "GAG"]), + ("aspartic acid", vec!["GAT", "GAC"]), + ("lysine", vec!["AAA", "AAG"]), + ("arginine", vec!["CGT", "CGC", "CGA", "CGG", "AGA", "AGG"]), + ("stop codon", vec!["TAA", "TAG", "TGA"])]; let mut pairs = Vec::<(&'static str, &'static str)>::new(); for (name, codons) in grouped.into_iter() { for codon in codons { pairs.push((codon, name)); } - }; + } pairs.sort_by(|&(_, a), &(_, b)| a.cmp(b)); - return pairs + return pairs; } diff --git a/exercises/nucleotide-count/tests/nucleotide-count.rs b/exercises/nucleotide-count/tests/nucleotide-count.rs index 32640dabb..18a0999ff 100644 --- a/exercises/nucleotide-count/tests/nucleotide-count.rs +++ b/exercises/nucleotide-count/tests/nucleotide-count.rs @@ -12,7 +12,7 @@ fn check_dna(s: &str, pairs: &[(char, usize)]) { assert_eq!((k, m.remove(&k).unwrap()), (k, v)); } // may fail with a message that clearly shows all extra pairs in the map - assert_eq!(m.iter().collect::>(), vec!()); + assert_eq!(m.iter().collect::>(), vec![]); } #[test] @@ -35,24 +35,18 @@ fn test_count_only_thymine() { #[test] #[ignore] fn test_nucleotide_count_empty() { - check_dna( - "", - &[('A', 0), ('T', 0), ('C', 0), ('G', 0)]); + check_dna("", &[('A', 0), ('T', 0), ('C', 0), ('G', 0)]); } #[test] #[ignore] fn test_nucleotide_count_only_guanine() { - check_dna( - "GGGGGGGG", - &[('A', 0), ('T', 0), ('C', 0), ('G', 8)]); + check_dna("GGGGGGGG", &[('A', 0), ('T', 0), ('C', 0), ('G', 8)]); } #[test] #[ignore] fn test_nucleotide_count_counts_all() { - check_dna( - "AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAA\ - GAGTGTCTGATAGCAGC", - &[('A', 20), ('T', 21), ('C', 12), ('G', 17)]); + check_dna("AGCTTTTCATTCTGACTGCAACGGGCAATATGTCTCTGTGTGGATTAAAAAAAGAGTGTCTGATAGCAGC", + &[('A', 20), ('T', 21), ('C', 12), ('G', 17)]); } diff --git a/exercises/parallel-letter-frequency/example.rs b/exercises/parallel-letter-frequency/example.rs index d0dbdbeda..3c769304d 100644 --- a/exercises/parallel-letter-frequency/example.rs +++ b/exercises/parallel-letter-frequency/example.rs @@ -10,9 +10,13 @@ pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap { assert!(num_workers > 0); let part_size_floor = texts.len() / num_workers; let rem = texts.len() % num_workers; - let part_size = if rem > 0 { part_size_floor + 1 } else { part_size_floor }; + let part_size = if rem > 0 { + part_size_floor + 1 + } else { + part_size_floor + }; let mut parts: Vec> = Vec::with_capacity(part_size); - for _ in 0 .. num_workers { + for _ in 0..num_workers { parts.push(Vec::with_capacity(part_size)); } let mut i = 0; @@ -27,7 +31,7 @@ pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap { for part in parts { let tx = tx.clone(); - thread::spawn(move || { + thread::spawn(move || { tx.send(count(part)).unwrap(); }); } @@ -37,7 +41,9 @@ pub fn frequency(texts: &[&str], num_workers: usize) -> HashMap { let part_results = rx.recv().unwrap(); for (c, n) in part_results.into_iter() { match results.entry(c) { - Entry::Vacant(view) => { view.insert(n); }, + Entry::Vacant(view) => { + view.insert(n); + } Entry::Occupied(mut view) => { *view.get_mut() += n; } @@ -53,7 +59,9 @@ fn count(lines: Vec) -> HashMap { for c in line.chars() { if c.is_alphabetic() { match results.entry(c.to_lowercase().next().unwrap()) { - Entry::Vacant(view) => { view.insert(1); }, + Entry::Vacant(view) => { + view.insert(1); + } Entry::Occupied(mut view) => { *view.get_mut() += 1; } diff --git a/exercises/parallel-letter-frequency/tests/parallel-letter-frequency.rs b/exercises/parallel-letter-frequency/tests/parallel-letter-frequency.rs index 87cb7827f..ad6bcb0b8 100644 --- a/exercises/parallel-letter-frequency/tests/parallel-letter-frequency.rs +++ b/exercises/parallel-letter-frequency/tests/parallel-letter-frequency.rs @@ -3,37 +3,40 @@ use std::collections::HashMap; extern crate parallel_letter_frequency as frequency; // Poem by Friedrich Schiller. The corresponding music is the European Anthem. -const ODE_AN_DIE_FREUDE: [&'static str; 8] = [ - "Freude schöner Götterfunken", - "Tochter aus Elysium,", - "Wir betreten feuertrunken,", - "Himmlische, dein Heiligtum!", - "Deine Zauber binden wieder", - "Was die Mode streng geteilt;", - "Alle Menschen werden Brüder,", - "Wo dein sanfter Flügel weilt."]; +const ODE_AN_DIE_FREUDE: [&'static str; 8] = ["Freude schöner Götterfunken", + "Tochter aus Elysium,", + "Wir betreten feuertrunken,", + "Himmlische, dein Heiligtum!", + "Deine Zauber binden wieder", + "Was die Mode streng geteilt;", + "Alle Menschen werden Brüder,", + "Wo dein sanfter Flügel weilt."]; // Dutch national anthem -const WILHELMUS: [&'static str; 8] = [ - "Wilhelmus van Nassouwe", - "ben ik, van Duitsen bloed,", - "den vaderland getrouwe", - "blijf ik tot in den dood.", - "Een Prinse van Oranje", - "ben ik, vrij, onverveerd,", - "den Koning van Hispanje", - "heb ik altijd geëerd."]; +const WILHELMUS: [&'static str; 8] = ["Wilhelmus van Nassouwe", + "ben ik, van Duitsen bloed,", + "den vaderland getrouwe", + "blijf ik tot in den dood.", + "Een Prinse van Oranje", + "ben ik, vrij, onverveerd,", + "den Koning van Hispanje", + "heb ik altijd geëerd."]; // American national anthem -const STAR_SPANGLED_BANNER: [&'static str; 8] = [ - "O say can you see by the dawn's early light,", - "What so proudly we hailed at the twilight's last gleaming,", - "Whose broad stripes and bright stars through the perilous fight,", - "O'er the ramparts we watched, were so gallantly streaming?", - "And the rockets' red glare, the bombs bursting in air,", - "Gave proof through the night that our flag was still there;", - "O say does that star-spangled banner yet wave,", - "O'er the land of the free and the home of the brave?"]; +const STAR_SPANGLED_BANNER: [&'static str; 8] = ["O say can you see by the dawn's early light,", + "What so proudly we hailed at the twilight's \ + last gleaming,", + "Whose broad stripes and bright stars through \ + the perilous fight,", + "O'er the ramparts we watched, were so \ + gallantly streaming?", + "And the rockets' red glare, the bombs bursting \ + in air,", + "Gave proof through the night that our flag was \ + still there;", + "O say does that star-spangled banner yet wave,", + "O'er the land of the free and the home of the \ + brave?"]; #[test] fn test_no_texts() { diff --git a/exercises/phone-number/example.rs b/exercises/phone-number/example.rs index f006fca2a..84410f344 100644 --- a/exercises/phone-number/example.rs +++ b/exercises/phone-number/example.rs @@ -1,15 +1,16 @@ pub fn number(s: &str) -> Option { - let digits: String = s - .chars() - .filter(|&c| c.is_digit(10)) - .collect(); + let digits: String = s.chars() + .filter(|&c| c.is_digit(10)) + .collect(); match digits.len() { 10 => Some(digits), - 11 => match digits.chars().nth(0) { - Some('1') => Some(digits[1..].to_string()), - _ => None - }, - _ => None + 11 => { + match digits.chars().nth(0) { + Some('1') => Some(digits[1..].to_string()), + _ => None, + } + } + _ => None, } } @@ -18,10 +19,12 @@ pub fn area_code(s: &str) -> Option { } pub fn pretty_print(s: &str) -> String { - number(s).map(|n| - format!("({area}) {prefix}-{exchange}", - area=&n[..3], - prefix=&n[3..6], - exchange=&n[6..]) - ).unwrap_or("invalid".to_string()) + number(s) + .map(|n| { + format!("({area}) {prefix}-{exchange}", + area = &n[..3], + prefix = &n[3..6], + exchange = &n[6..]) + }) + .unwrap_or("invalid".to_string()) } diff --git a/exercises/phone-number/tests/phone-number.rs b/exercises/phone-number/tests/phone-number.rs index 4bd8b38b0..1ba3ddb07 100644 --- a/exercises/phone-number/tests/phone-number.rs +++ b/exercises/phone-number/tests/phone-number.rs @@ -6,7 +6,8 @@ fn to_some_string(s: &str) -> Option { #[test] fn test_number_cleans() { - assert_eq!(phone::number("(123) 456-7890"), to_some_string("1234567890")); + assert_eq!(phone::number("(123) 456-7890"), + to_some_string("1234567890")); } #[test] @@ -48,13 +49,15 @@ fn test_invalid_when_no_digits_present() { #[test] #[ignore] fn test_valid_with_leading_characters() { - assert_eq!(phone::number("my number is 123 456 7890"), to_some_string("1234567890")); + assert_eq!(phone::number("my number is 123 456 7890"), + to_some_string("1234567890")); } #[test] #[ignore] fn test_valid_with_trailing_characters() { - assert_eq!(phone::number("123 456 7890 - bob"), to_some_string("1234567890")); + assert_eq!(phone::number("123 456 7890 - bob"), + to_some_string("1234567890")); } #[test] diff --git a/exercises/raindrops/tests/raindrops.rs b/exercises/raindrops/tests/raindrops.rs index 881cea7c6..46a396afc 100644 --- a/exercises/raindrops/tests/raindrops.rs +++ b/exercises/raindrops/tests/raindrops.rs @@ -1,64 +1,96 @@ extern crate raindrops; #[test] -fn test_1() { assert_eq!("1", raindrops::raindrops(1)); } +fn test_1() { + assert_eq!("1", raindrops::raindrops(1)); +} #[test] #[ignore] -fn test_3() { assert_eq!("Pling", raindrops::raindrops(3)); } +fn test_3() { + assert_eq!("Pling", raindrops::raindrops(3)); +} #[test] #[ignore] -fn test_5() { assert_eq!("Plang", raindrops::raindrops(5)); } +fn test_5() { + assert_eq!("Plang", raindrops::raindrops(5)); +} #[test] #[ignore] -fn test_7() { assert_eq!("Plong", raindrops::raindrops(7)); } +fn test_7() { + assert_eq!("Plong", raindrops::raindrops(7)); +} #[test] #[ignore] -fn test_6() { assert_eq!("Pling", raindrops::raindrops(6)); } +fn test_6() { + assert_eq!("Pling", raindrops::raindrops(6)); +} #[test] #[ignore] -fn test_9() { assert_eq!("Pling", raindrops::raindrops(9)); } +fn test_9() { + assert_eq!("Pling", raindrops::raindrops(9)); +} #[test] #[ignore] -fn test_10() { assert_eq!("Plang", raindrops::raindrops(10)); } +fn test_10() { + assert_eq!("Plang", raindrops::raindrops(10)); +} #[test] #[ignore] -fn test_14() { assert_eq!("Plong", raindrops::raindrops(14)); } +fn test_14() { + assert_eq!("Plong", raindrops::raindrops(14)); +} #[test] #[ignore] -fn test_15() { assert_eq!("PlingPlang", raindrops::raindrops(15)); } +fn test_15() { + assert_eq!("PlingPlang", raindrops::raindrops(15)); +} #[test] #[ignore] -fn test_21() { assert_eq!("PlingPlong", raindrops::raindrops(21)); } +fn test_21() { + assert_eq!("PlingPlong", raindrops::raindrops(21)); +} #[test] #[ignore] -fn test_25() { assert_eq!("Plang", raindrops::raindrops(25)); } +fn test_25() { + assert_eq!("Plang", raindrops::raindrops(25)); +} #[test] #[ignore] -fn test_35() { assert_eq!("PlangPlong", raindrops::raindrops(35)); } +fn test_35() { + assert_eq!("PlangPlong", raindrops::raindrops(35)); +} #[test] #[ignore] -fn test_49() { assert_eq!("Plong", raindrops::raindrops(49)); } +fn test_49() { + assert_eq!("Plong", raindrops::raindrops(49)); +} #[test] #[ignore] -fn test_52() { assert_eq!("52", raindrops::raindrops(52)); } +fn test_52() { + assert_eq!("52", raindrops::raindrops(52)); +} #[test] #[ignore] -fn test_105() { assert_eq!("PlingPlangPlong", raindrops::raindrops(105)); } +fn test_105() { + assert_eq!("PlingPlangPlong", raindrops::raindrops(105)); +} #[test] #[ignore] -fn test_12121() { assert_eq!("12121", raindrops::raindrops(12121)); } +fn test_12121() { + assert_eq!("12121", raindrops::raindrops(12121)); +} diff --git a/exercises/rectangles/example.rs b/exercises/rectangles/example.rs index 8144500d9..7b7652026 100644 --- a/exercises/rectangles/example.rs +++ b/exercises/rectangles/example.rs @@ -19,7 +19,7 @@ const CONN_DOWN: u8 = 0x8; #[derive(PartialEq, Eq, Hash)] struct Point { x: usize, - y: usize + y: usize, } #[derive(PartialEq, Eq, Hash)] @@ -27,21 +27,21 @@ struct Line { x1: usize, y1: usize, x2: usize, - y2: usize + y2: usize, } #[derive(PartialEq, Eq, Clone, Copy)] enum Symbol { Corner, // '+' Connect, // '|' or '-' depending on direction - Other // ' ', or anything really + Other, // ' ', or anything really } // The input area. struct RealArea { width: usize, height: usize, - chars: Vec> + chars: Vec>, } trait Area { @@ -52,13 +52,17 @@ trait Area { // For horizontal scanning impl Area for RealArea { - fn width(&self) -> usize { self.width } - fn height(&self) -> usize { self.height } + fn width(&self) -> usize { + self.width + } + fn height(&self) -> usize { + self.height + } fn symbol_at(&self, x: usize, y: usize) -> Symbol { match self.chars[y][x] { '+' => Symbol::Corner, '-' => Symbol::Connect, - _ => Symbol::Other + _ => Symbol::Other, } } } @@ -67,13 +71,17 @@ struct TransposedArea<'a>(&'a RealArea); // For vertical scanning impl<'a> Area for TransposedArea<'a> { - fn width(&self) -> usize { self.0.height } - fn height(&self) -> usize { self.0.width } + fn width(&self) -> usize { + self.0.height + } + fn height(&self) -> usize { + self.0.width + } fn symbol_at(&self, x: usize, y: usize) -> Symbol { match self.0.chars[x][y] { '+' => Symbol::Corner, '|' => Symbol::Connect, - _ => Symbol::Other + _ => Symbol::Other, } } } @@ -81,19 +89,19 @@ impl<'a> Area for TransposedArea<'a> { // Information about connections. struct Connections { lines: HashSet, - points: HashMap + points: HashMap, } pub fn count(lines: &Vec<&str>) -> usize { if lines.len() == 0 { - return 0 + return 0; } else if lines[0].len() == 0 { - return 0 + return 0; } let area = RealArea { width: lines[0].len(), height: lines.len(), - chars: lines.iter().map(|line| line.chars().collect()).collect() + chars: lines.iter().map(|line| line.chars().collect()).collect(), }; let area_transposed = TransposedArea(&area); let mut conns = scan_connected(&area); @@ -102,29 +110,54 @@ pub fn count(lines: &Vec<&str>) -> usize { // The transposed connections have their coordinate system wrong, // correct this. for l in conns_transposed.lines { - conns.lines.insert(Line{x1: l.y1, y1: l.x1, x2: l.y2, y2: l.x2}); + conns.lines.insert(Line { + x1: l.y1, + y1: l.x1, + x2: l.y2, + y2: l.x2, + }); } for (p, tcf) in conns_transposed.points { - let cf = conns.points.entry(Point{x: p.y, y: p.x}).or_insert(0); + let cf = conns.points.entry(Point { x: p.y, y: p.x }).or_insert(0); *cf = *cf | (tcf << 2) } let mut total = 0; - for (tl_p, tl_cf) in conns.points.iter() { // top left point and connection flags - if tl_cf & (CONN_RIGHT|CONN_DOWN) == CONN_RIGHT|CONN_DOWN { + for (tl_p, tl_cf) in conns.points.iter() { + // top left point and connection flags + if tl_cf & (CONN_RIGHT | CONN_DOWN) == CONN_RIGHT | CONN_DOWN { for (br_p, br_cf) in conns.points.iter() { // left, right, top, bottom of potential rectangle let l = tl_p.x; let r = br_p.x; let t = tl_p.y; let b = br_p.y; - let is_rect = - br_cf & (CONN_LEFT|CONN_UP) == CONN_LEFT|CONN_UP && - r > l && b > t && - conns.lines.contains(&Line{x1: l, y1: t, x2: l, y2: b}) && - conns.lines.contains(&Line{x1: l, y1: t, x2: r, y2: t}) && - conns.lines.contains(&Line{x1: l, y1: b, x2: r, y2: b}) && - conns.lines.contains(&Line{x1: r, y1: t, x2: r, y2: b}); + let is_rect = br_cf & (CONN_LEFT | CONN_UP) == CONN_LEFT | CONN_UP && r > l && + b > t && + conns.lines.contains(&Line { + x1: l, + y1: t, + x2: l, + y2: b, + }) && + conns.lines.contains(&Line { + x1: l, + y1: t, + x2: r, + y2: t, + }) && + conns.lines.contains(&Line { + x1: l, + y1: b, + x2: r, + y2: b, + }) && + conns.lines.contains(&Line { + x1: r, + y1: t, + x2: r, + y2: b, + }); if is_rect { total += 1 } @@ -135,9 +168,9 @@ pub fn count(lines: &Vec<&str>) -> usize { } fn scan_connected(area: &Area) -> Connections { - let mut conns = Connections{ + let mut conns = Connections { lines: HashSet::new(), - points: HashMap::new() + points: HashMap::new(), }; let mut connected: Vec = vec![]; for y in 0..area.height() { @@ -146,13 +179,23 @@ fn scan_connected(area: &Area) -> Connections { let sym = area.symbol_at(x, y); if sym == Symbol::Corner { for prev in connected.iter() { - conns.lines.insert(Line{x1: prev.clone(), y1: y, x2: x, y2: y}); + conns.lines.insert(Line { + x1: prev.clone(), + y1: y, + x2: x, + y2: y, + }); } if let Some(last) = connected.last() { - let cf = conns.points.get_mut(&Point{x: last.clone(), y: y}).unwrap(); + let cf = conns.points + .get_mut(&Point { + x: last.clone(), + y: y, + }) + .unwrap(); *cf = *cf | CONN_RIGHT; } - let cf = conns.points.entry(Point{x: x, y: y}).or_insert(0); + let cf = conns.points.entry(Point { x: x, y: y }).or_insert(0); if connected.len() > 0 { *cf = *cf | CONN_LEFT; } diff --git a/exercises/rectangles/tests/rectangles.rs b/exercises/rectangles/tests/rectangles.rs index afa8866e1..9e336881a 100644 --- a/exercises/rectangles/tests/rectangles.rs +++ b/exercises/rectangles/tests/rectangles.rs @@ -36,64 +36,42 @@ fn test_one_rectangle() { #[test] #[ignore] fn test_two_rectangles_no_shared_parts() { - let lines = vec![ - " +-+", - " | |", - "+-+-+", - "| | ", - "+-+ " - ]; + let lines = vec![" +-+", " | |", "+-+-+", "| | ", "+-+ "]; assert_eq!(2, count(&lines)) } #[test] #[ignore] fn test_five_rectangles_three_regions() { - let lines = vec![ - " +-+", - " | |", - "+-+-+", - "| | |", - "+-+-+" - ]; + let lines = vec![" +-+", " | |", "+-+-+", "| | |", "+-+-+"]; assert_eq!(5, count(&lines)) } #[test] #[ignore] fn test_incomplete_rectangles() { - let lines = vec![ - " +-+", - " |", - "+-+-+", - "| | -", - "+-+-+" - ]; + let lines = vec![" +-+", " |", "+-+-+", "| | -", "+-+-+"]; assert_eq!(1, count(&lines)) } #[test] #[ignore] fn test_complicated() { - let lines = vec![ - "+------+----+", - "| | |", - "+---+--+ |", - "| | |", - "+---+-------+" - ]; + let lines = vec!["+------+----+", + "| | |", + "+---+--+ |", + "| | |", + "+---+-------+"]; assert_eq!(3, count(&lines)) } #[test] #[ignore] fn test_not_so_complicated() { - let lines = vec![ - "+------+----+", - "| | |", - "+------+ |", - "| | |", - "+---+-------+" - ]; + let lines = vec!["+------+----+", + "| | |", + "+------+ |", + "| | |", + "+---+-------+"]; assert_eq!(2, count(&lines)) } diff --git a/exercises/rna-transcription/example.rs b/exercises/rna-transcription/example.rs index c9ddca4a3..f1b50db1c 100644 --- a/exercises/rna-transcription/example.rs +++ b/exercises/rna-transcription/example.rs @@ -1,6 +1,6 @@ #[derive(PartialEq, Eq, Debug)] pub struct RibonucleicAcid { - nucleotides: String + nucleotides: String, } impl RibonucleicAcid { @@ -11,7 +11,7 @@ impl RibonucleicAcid { #[derive(PartialEq, Eq, Debug)] pub struct DeoxyribonucleicAcid { - nucleotides: String + nucleotides: String, } fn transcribe_dna_rna(c: char) -> char { @@ -20,7 +20,7 @@ fn transcribe_dna_rna(c: char) -> char { 'G' => 'C', 'A' => 'U', 'T' => 'A', - _ => c + _ => c, } } diff --git a/exercises/rna-transcription/tests/rna-transcription.rs b/exercises/rna-transcription/tests/rna-transcription.rs index 99be89f46..d0363783d 100644 --- a/exercises/rna-transcription/tests/rna-transcription.rs +++ b/exercises/rna-transcription/tests/rna-transcription.rs @@ -2,36 +2,42 @@ extern crate rna_transcription as dna; #[test] fn test_acid_equals_acid() { - assert_eq!(dna::RibonucleicAcid::new("CGA"), dna::RibonucleicAcid::new("CGA")); + assert_eq!(dna::RibonucleicAcid::new("CGA"), + dna::RibonucleicAcid::new("CGA")); assert!(dna::RibonucleicAcid::new("CGA") != dna::RibonucleicAcid::new("AGC")); } #[test] #[ignore] fn test_transcribes_cytosine_guanine() { - assert_eq!(dna::RibonucleicAcid::new("G"), dna::DeoxyribonucleicAcid::new("C").to_rna()); + assert_eq!(dna::RibonucleicAcid::new("G"), + dna::DeoxyribonucleicAcid::new("C").to_rna()); } #[test] #[ignore] fn test_transcribes_guanine_cytosine() { - assert_eq!(dna::RibonucleicAcid::new("C"), dna::DeoxyribonucleicAcid::new("G").to_rna()); + assert_eq!(dna::RibonucleicAcid::new("C"), + dna::DeoxyribonucleicAcid::new("G").to_rna()); } #[test] #[ignore] fn test_transcribes_adenine_uracil() { - assert_eq!(dna::RibonucleicAcid::new("U"), dna::DeoxyribonucleicAcid::new("A").to_rna()); + assert_eq!(dna::RibonucleicAcid::new("U"), + dna::DeoxyribonucleicAcid::new("A").to_rna()); } #[test] #[ignore] fn test_transcribes_thymine_to_adenine() { - assert_eq!(dna::RibonucleicAcid::new("A"), dna::DeoxyribonucleicAcid::new("T").to_rna()); + assert_eq!(dna::RibonucleicAcid::new("A"), + dna::DeoxyribonucleicAcid::new("T").to_rna()); } #[test] #[ignore] fn test_transcribes_all_dna_to_rna() { - assert_eq!(dna::RibonucleicAcid::new("UGCACCAGAAUU"), dna::DeoxyribonucleicAcid::new("ACGTGGTCTTAA").to_rna()) + assert_eq!(dna::RibonucleicAcid::new("UGCACCAGAAUU"), + dna::DeoxyribonucleicAcid::new("ACGTGGTCTTAA").to_rna()) } diff --git a/exercises/robot-name/example.rs b/exercises/robot-name/example.rs index 703e57f5a..57ca5932b 100644 --- a/exercises/robot-name/example.rs +++ b/exercises/robot-name/example.rs @@ -2,7 +2,7 @@ extern crate rand; use rand::{thread_rng, Rng}; pub struct Robot { - name: String + name: String, } fn generate_name() -> String { @@ -30,5 +30,4 @@ impl Robot { pub fn reset_name(&mut self) { self.name = generate_name(); } - } diff --git a/exercises/robot-name/tests/robot-name.rs b/exercises/robot-name/tests/robot-name.rs index 4521110ff..913b53c0b 100644 --- a/exercises/robot-name/tests/robot-name.rs +++ b/exercises/robot-name/tests/robot-name.rs @@ -1,19 +1,20 @@ extern crate robot_name as robot; -/* -These are the expected signatures: - -impl Robot { - pub fn new() -> Robot { ... } - pub fn name<'a>(&'a self) -> &'a str { ... } - pub fn reset_name(&mut self) { ... } -} -*/ +// These are the expected signatures: +// +// impl Robot { +// pub fn new() -> Robot { ... } +// pub fn name<'a>(&'a self) -> &'a str { ... } +// pub fn reset_name(&mut self) { ... } +// } +// fn assert_name_matches_pattern(n: &str) { assert!(n.len() == 5, "name is exactly 5 characters long"); - assert!(n[0..2].chars().all(|c| c >= 'A' && c <= 'Z'), "name starts with 2 uppercase letters"); - assert!(n[2..].chars().all(|c| c >= '0' && c <= '9'), "name ends with 3 numbers"); + assert!(n[0..2].chars().all(|c| c >= 'A' && c <= 'Z'), + "name starts with 2 uppercase letters"); + assert!(n[2..].chars().all(|c| c >= '0' && c <= '9'), + "name ends with 3 numbers"); } fn assert_name_is_persistent(r: &robot::Robot) { diff --git a/exercises/sublist/tests/sublist.rs b/exercises/sublist/tests/sublist.rs index 317710fd5..93d9d44ab 100644 --- a/exercises/sublist/tests/sublist.rs +++ b/exercises/sublist/tests/sublist.rs @@ -6,37 +6,25 @@ use sublist::{sublist, Comparison}; fn empty_equals_empty() { let v: &[u32] = &[]; - assert_eq!( - Comparison::Equal, - sublist(&v, &v) - ); + assert_eq!(Comparison::Equal, sublist(&v, &v)); } #[test] #[ignore] fn test_empty_is_a_sublist_of_anything() { - assert_eq!( - Comparison::Sublist, - sublist(&[], &['a', 's', 'd', 'f']) - ); + assert_eq!(Comparison::Sublist, sublist(&[], &['a', 's', 'd', 'f'])); } #[test] #[ignore] fn test_anything_is_a_superlist_of_empty() { - assert_eq!( - Comparison::Superlist, - sublist(&['a', 's', 'd', 'f'], &[]) - ); + assert_eq!(Comparison::Superlist, sublist(&['a', 's', 'd', 'f'], &[])); } #[test] #[ignore] fn test_1_is_not_2() { - assert_eq!( - Comparison::Unequal, - sublist(&[1], &[2]) - ); + assert_eq!(Comparison::Unequal, sublist(&[1], &[2])); } #[test] @@ -46,46 +34,31 @@ fn test_compare_larger_equal_lists() { let v: Vec = repeat('x').take(1000).collect(); - assert_eq!( - Comparison::Equal, - sublist(&v, &v) - ); + assert_eq!(Comparison::Equal, sublist(&v, &v)); } #[test] #[ignore] fn test_sublist_at_start() { - assert_eq!( - Comparison::Sublist, - sublist(&[1, 2, 3], &[1, 2, 3, 4, 5]) - ); + assert_eq!(Comparison::Sublist, sublist(&[1, 2, 3], &[1, 2, 3, 4, 5])); } #[test] #[ignore] fn sublist_in_middle() { - assert_eq!( - Comparison::Sublist, - sublist(&[4, 3, 2], &[5, 4, 3, 2, 1]) - ); + assert_eq!(Comparison::Sublist, sublist(&[4, 3, 2], &[5, 4, 3, 2, 1])); } #[test] #[ignore] fn sublist_at_end() { - assert_eq!( - Comparison::Sublist, - sublist(&[3, 4, 5], &[1, 2, 3, 4, 5]) - ); + assert_eq!(Comparison::Sublist, sublist(&[3, 4, 5], &[1, 2, 3, 4, 5])); } #[test] #[ignore] fn partially_matching_sublist_at_start() { - assert_eq!( - Comparison::Sublist, - sublist(&[1, 1, 2], &[1, 1, 1, 2]) - ); + assert_eq!(Comparison::Sublist, sublist(&[1, 1, 2], &[1, 1, 1, 2])); } #[test] @@ -93,10 +66,7 @@ fn partially_matching_sublist_at_start() { fn sublist_early_in_huge_list() { let huge: Vec = (1..1000000).collect(); - assert_eq!( - Comparison::Sublist, - sublist(&[3, 4, 5], &huge) - ); + assert_eq!(Comparison::Sublist, sublist(&[3, 4, 5], &huge)); } #[test] @@ -105,37 +75,25 @@ fn huge_sublist_not_in_huge_list() { let v1: Vec = (10..1000001).collect(); let v2: Vec = (1..1000000).collect(); - assert_eq!( - Comparison::Unequal, - sublist(&v1, &v2) - ); + assert_eq!(Comparison::Unequal, sublist(&v1, &v2)); } #[test] #[ignore] fn superlist_at_start() { - assert_eq!( - Comparison::Superlist, - sublist(&[1, 2, 3, 4, 5], &[1, 2, 3]) - ); + assert_eq!(Comparison::Superlist, sublist(&[1, 2, 3, 4, 5], &[1, 2, 3])); } #[test] #[ignore] fn superlist_in_middle() { - assert_eq!( - Comparison::Superlist, - sublist(&[5, 4, 3, 2, 1], &[4, 3, 2]) - ); + assert_eq!(Comparison::Superlist, sublist(&[5, 4, 3, 2, 1], &[4, 3, 2])); } #[test] #[ignore] fn superlist_at_end() { - assert_eq!( - Comparison::Superlist, - sublist(&[1, 2, 3, 4, 5], &[3, 4, 5]) - ); + assert_eq!(Comparison::Superlist, sublist(&[1, 2, 3, 4, 5], &[3, 4, 5])); } #[test] @@ -143,32 +101,19 @@ fn superlist_at_end() { fn superlist_early_in_huge_list() { let huge: Vec = (1..1000000).collect(); - assert_eq!( - Comparison::Superlist, - sublist(&huge, &[3, 4, 5]) - ); + assert_eq!(Comparison::Superlist, sublist(&huge, &[3, 4, 5])); } #[test] #[ignore] fn recurring_values_sublist() { - assert_eq!( - Comparison::Sublist, - sublist( - &[1, 2, 1, 2, 3], - &[1, 2, 3, 1, 2, 1, 2, 3, 2, 1] - ) - ); + assert_eq!(Comparison::Sublist, + sublist(&[1, 2, 1, 2, 3], &[1, 2, 3, 1, 2, 1, 2, 3, 2, 1])); } #[test] #[ignore] fn recurring_values_unequal() { - assert_eq!( - Comparison::Unequal, - sublist( - &[1, 2, 1, 2, 3], - &[1, 2, 3, 1, 2, 3, 2, 3, 2, 1] - ) - ); + assert_eq!(Comparison::Unequal, + sublist(&[1, 2, 1, 2, 3], &[1, 2, 3, 1, 2, 3, 2, 3, 2, 1])); } diff --git a/exercises/tournament/example.rs b/exercises/tournament/example.rs index 8d741007c..f9f2a687f 100644 --- a/exercises/tournament/example.rs +++ b/exercises/tournament/example.rs @@ -8,7 +8,7 @@ use std::path::Path; enum GameResult { Win, Draw, - Loss + Loss, } struct TeamResult { @@ -19,7 +19,11 @@ struct TeamResult { impl TeamResult { fn new() -> TeamResult { - TeamResult { wins: 0, draws: 0, losses: 0 } + TeamResult { + wins: 0, + draws: 0, + losses: 0, + } } fn add_game_result(&mut self, result: GameResult) { match result { @@ -34,10 +38,12 @@ pub fn tally(input_filename: &Path, output_filename: &Path) -> Result { let reader = BufReader::with_capacity(2048, File::open(input_filename).unwrap()); let mut count = 0; let mut results: HashMap = HashMap::new(); - for line in reader.lines() { + for line in reader.lines() { let line = line.unwrap(); - let parts: Vec<&str> = line.trim_right().split(';').collect(); - if parts.len() != 3 { continue; } + let parts: Vec<&str> = line.trim_right().split(';').collect(); + if parts.len() != 3 { + continue; + } let team1 = parts[0]; let team2 = parts[1]; let outcome = parts[2]; @@ -46,18 +52,18 @@ pub fn tally(input_filename: &Path, output_filename: &Path) -> Result { add_game_result(&mut results, team1.to_string(), GameResult::Win); add_game_result(&mut results, team2.to_string(), GameResult::Loss); count += 1; - }, + } "draw" => { add_game_result(&mut results, team1.to_string(), GameResult::Draw); add_game_result(&mut results, team2.to_string(), GameResult::Draw); count += 1; - }, + } "loss" => { add_game_result(&mut results, team1.to_string(), GameResult::Loss); add_game_result(&mut results, team2.to_string(), GameResult::Win); count += 1; - }, - _ => () // Ignore bad lines + } + _ => (), // Ignore bad lines } } try!(write_tally(&results, output_filename)); @@ -72,16 +78,23 @@ fn write_tally(results: &HashMap, output_filename: &Path) -> v.push((team, games, r, points)); } // Sort by points, then games played, in reverse order. - v.sort_by(|a, b| - match a.3.cmp(&(b.3)).reverse() { - Equal => a.1.cmp(&(b.1)).reverse(), - other => other - }); + v.sort_by(|a, b| { + match a.3.cmp(&(b.3)).reverse() { + Equal => a.1.cmp(&(b.1)).reverse(), + other => other, + } + }); let mut f = try!(File::create(output_filename)); try!(writeln!(&mut f, "{:30} | MP | W | D | L | P", "Team")); for &(ref team, games, r, points) in v.iter() { - try!(writeln!(&mut f, "{:30} | {:2} | {:2} | {:2} | {:2} | {:2}", - team, games, r.wins, r.draws, r.losses, points)); + try!(writeln!(&mut f, + "{:30} | {:2} | {:2} | {:2} | {:2} | {:2}", + team, + games, + r.wins, + r.draws, + r.losses, + points)); } Ok(()) } diff --git a/exercises/tournament/tests/tournament.rs b/exercises/tournament/tests/tournament.rs index 88b39cfd6..dfa7515a8 100644 --- a/exercises/tournament/tests/tournament.rs +++ b/exercises/tournament/tests/tournament.rs @@ -11,7 +11,7 @@ fn file_equal(output_file: &str, expected_file: &str) { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", output_file, e), - Ok(_) => buf + Ok(_) => buf, } } }; @@ -21,31 +21,41 @@ fn file_equal(output_file: &str, expected_file: &str) { let mut buf = String::new(); match f.read_to_string(&mut buf) { Err(e) => panic!("Couldn't read {}: {}", expected_file, e), - Ok(_) => buf + Ok(_) => buf, } } }; - assert_eq!("\n".to_string() + output.as_ref(), "\n".to_string() + expected.as_ref()); - + assert_eq!("\n".to_string() + output.as_ref(), + "\n".to_string() + expected.as_ref()); + } #[test] fn test_good() { - assert_eq!(tournament::tally(&Path::new("tests/input1.txt"), &Path::new("tests/output1.txt")).unwrap(), 6); + assert_eq!(tournament::tally(&Path::new("tests/input1.txt"), + &Path::new("tests/output1.txt")) + .unwrap(), + 6); file_equal("tests/output1.txt", "tests/expected1.txt"); } #[test] #[ignore] fn test_ignore_bad_lines() { - assert_eq!(tournament::tally(&Path::new("tests/input2.txt"), &Path::new("tests/output2.txt")).unwrap(), 6); + assert_eq!(tournament::tally(&Path::new("tests/input2.txt"), + &Path::new("tests/output2.txt")) + .unwrap(), + 6); file_equal("tests/output2.txt", "tests/expected2.txt"); } #[test] #[ignore] fn test_incomplete_competition() { - assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), &Path::new("tests/output3.txt")).unwrap(), 4); + assert_eq!(tournament::tally(&Path::new("tests/input3.txt"), + &Path::new("tests/output3.txt")) + .unwrap(), + 4); file_equal("tests/output3.txt", "tests/expected3.txt"); } diff --git a/exercises/word-count/example.rs b/exercises/word-count/example.rs index 787c8fc3e..f4836af21 100644 --- a/exercises/word-count/example.rs +++ b/exercises/word-count/example.rs @@ -17,7 +17,9 @@ pub fn word_count(input: &str) -> HashMap { let slice: &str = lower.as_ref(); for word in slice.split(|c: char| !c.is_alphanumeric()).filter(|s| !s.is_empty()) { match map.entry(word.to_string()) { - Entry::Vacant(entry) => { entry.insert(1); }, + Entry::Vacant(entry) => { + entry.insert(1); + } Entry::Occupied(mut entry) => { *entry.get_mut() += 1; } diff --git a/exercises/word-count/tests/word-count.rs b/exercises/word-count/tests/word-count.rs index 203ada2ce..fd777aa7a 100644 --- a/exercises/word-count/tests/word-count.rs +++ b/exercises/word-count/tests/word-count.rs @@ -12,7 +12,7 @@ fn check_word_count(s: &str, pairs: Vec<(&str, u32)>) { assert_eq!((k, m.remove(&k.to_string()).unwrap_or(0)), (k, v)); } // may fail with a message that clearly shows all extra pairs in the map - assert_eq!(m.iter().collect::>(), vec!()); + assert_eq!(m.iter().collect::>(), vec![]); } #[test] @@ -30,73 +30,46 @@ fn test_count_one_word() { #[test] #[ignore] fn test_count_one_of_each() { - check_word_count( - "one of each", - vec![("one", 1), - ("of", 1), - ("each", 1)]); + check_word_count("one of each", vec![("one", 1), ("of", 1), ("each", 1)]); } #[test] #[ignore] fn test_count_multiple_occurrences() { - check_word_count( - "one fish two fish red fish blue fish", - vec![("one", 1), - ("fish", 4), - ("two", 1), - ("red", 1), - ("blue", 1)]); + check_word_count("one fish two fish red fish blue fish", + vec![("one", 1), ("fish", 4), ("two", 1), ("red", 1), ("blue", 1)]); } #[test] #[ignore] fn test_ignore_punctuation() { - check_word_count( - "car : carpet as java : javascript!!&@$%^&", - vec![("car", 1), - ("carpet", 1), - ("as", 1), - ("java", 1), - ("javascript", 1)]); + check_word_count("car : carpet as java : javascript!!&@$%^&", + vec![("car", 1), ("carpet", 1), ("as", 1), ("java", 1), ("javascript", 1)]); } #[test] #[ignore] fn test_include_numbers() { - check_word_count( - "testing, 1, 2 testing", - vec![("testing", 2), - ("1", 1), - ("2", 1)]); + check_word_count("testing, 1, 2 testing", + vec![("testing", 2), ("1", 1), ("2", 1)]); } #[test] #[ignore] fn test_normalize_case() { - check_word_count( - "go Go GO", - vec![("go", 3)]); + check_word_count("go Go GO", vec![("go", 3)]); } #[test] #[ignore] fn test_prefix_punctuation() { - check_word_count( - "!%%#testing, 1, 2 testing", - vec![("testing", 2), - ("1", 1), - ("2", 1)]); + check_word_count("!%%#testing, 1, 2 testing", + vec![("testing", 2), ("1", 1), ("2", 1)]); } #[test] #[ignore] fn test_symbols_are_separators() { - check_word_count( - "hey,my_spacebar_is_broken.", - vec![("hey", 1), - ("my", 1), - ("spacebar", 1), - ("is", 1), - ("broken", 1)]); + check_word_count("hey,my_spacebar_is_broken.", + vec![("hey", 1), ("my", 1), ("spacebar", 1), ("is", 1), ("broken", 1)]); }