|
1 |
| -// Solutions will be available before the stable release. Thank you for testing the beta version 🥰 |
| 1 | +// AsRef and AsMut allow for cheap reference-to-reference conversions. Read more |
| 2 | +// about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html and |
| 3 | +// https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. |
| 4 | + |
| 5 | +// Obtain the number of bytes (not characters) in the given argument. |
| 6 | +fn byte_counter<T: AsRef<str>>(arg: T) -> usize { |
| 7 | + arg.as_ref().as_bytes().len() |
| 8 | +} |
| 9 | + |
| 10 | +// Obtain the number of characters (not bytes) in the given argument. |
| 11 | +fn char_counter<T: AsRef<str>>(arg: T) -> usize { |
| 12 | + arg.as_ref().chars().count() |
| 13 | +} |
| 14 | + |
| 15 | +// Squares a number using `as_mut()`. |
| 16 | +fn num_sq<T: AsMut<u32>>(arg: &mut T) { |
| 17 | + let arg = arg.as_mut(); |
| 18 | + *arg = *arg * *arg; |
| 19 | +} |
| 20 | + |
| 21 | +fn main() { |
| 22 | + // You can optionally experiment here. |
| 23 | +} |
| 24 | + |
| 25 | +#[cfg(test)] |
| 26 | +mod tests { |
| 27 | + use super::*; |
| 28 | + |
| 29 | + #[test] |
| 30 | + fn different_counts() { |
| 31 | + let s = "Café au lait"; |
| 32 | + assert_ne!(char_counter(s), byte_counter(s)); |
| 33 | + } |
| 34 | + |
| 35 | + #[test] |
| 36 | + fn same_counts() { |
| 37 | + let s = "Cafe au lait"; |
| 38 | + assert_eq!(char_counter(s), byte_counter(s)); |
| 39 | + } |
| 40 | + |
| 41 | + #[test] |
| 42 | + fn different_counts_using_string() { |
| 43 | + let s = String::from("Café au lait"); |
| 44 | + assert_ne!(char_counter(s.clone()), byte_counter(s)); |
| 45 | + } |
| 46 | + |
| 47 | + #[test] |
| 48 | + fn same_counts_using_string() { |
| 49 | + let s = String::from("Cafe au lait"); |
| 50 | + assert_eq!(char_counter(s.clone()), byte_counter(s)); |
| 51 | + } |
| 52 | + |
| 53 | + #[test] |
| 54 | + fn mut_box() { |
| 55 | + let mut num: Box<u32> = Box::new(3); |
| 56 | + num_sq(&mut num); |
| 57 | + assert_eq!(*num, 9); |
| 58 | + } |
| 59 | +} |
0 commit comments