From df53b5803e119bb542d8cbd784f16770bf7868d1 Mon Sep 17 00:00:00 2001 From: TriantaTV Date: Thu, 15 Jun 2023 18:37:00 -0500 Subject: [PATCH] Finished Rustlings --- exercises/conversions/as_ref_mut.rs | 9 ++++----- exercises/conversions/try_from_into.rs | 24 ++++++++++++++++++++++-- 2 files changed, 26 insertions(+), 7 deletions(-) diff --git a/exercises/conversions/as_ref_mut.rs b/exercises/conversions/as_ref_mut.rs index e6a9d11..c17f83b 100644 --- a/exercises/conversions/as_ref_mut.rs +++ b/exercises/conversions/as_ref_mut.rs @@ -3,25 +3,24 @@ // and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively. // Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a hint. -// I AM NOT DONE // Obtain the number of bytes (not characters) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn byte_counter(arg: T) -> usize { +fn byte_counter>(arg: T) -> usize { arg.as_ref().as_bytes().len() } // Obtain the number of characters (not bytes) in the given argument. // TODO: Add the AsRef trait appropriately as a trait bound. -fn char_counter(arg: T) -> usize { +fn char_counter>(arg: T) -> usize { arg.as_ref().chars().count() } // Squares a number using as_mut(). // TODO: Add the appropriate trait bound. -fn num_sq(arg: &mut T) { +fn num_sq>(arg: &mut T) { // TODO: Implement the function body. - ??? + *arg.as_mut() *= *arg.as_mut(); } #[cfg(test)] diff --git a/exercises/conversions/try_from_into.rs b/exercises/conversions/try_from_into.rs index c46b14f..1da5f79 100644 --- a/exercises/conversions/try_from_into.rs +++ b/exercises/conversions/try_from_into.rs @@ -23,7 +23,6 @@ enum IntoColorError { IntConversion, } -// I AM NOT DONE // Your task is to complete this implementation // and return an Ok result of inner type Color. @@ -38,6 +37,10 @@ enum IntoColorError { impl TryFrom<(i16, i16, i16)> for Color { type Error = IntoColorError; fn try_from(tuple: (i16, i16, i16)) -> Result { + match tuple { + (0..=255, 0..=255, 0..=255) => (), + _ => { return Err(IntoColorError::IntConversion); } + } Ok(Color { red: tuple.0 as u8, green: tuple.1 as u8, @@ -50,6 +53,12 @@ impl TryFrom<(i16, i16, i16)> for Color { impl TryFrom<[i16; 3]> for Color { type Error = IntoColorError; fn try_from(arr: [i16; 3]) -> Result { + for value in arr { + match value { + 0..=255 => (), + _ => { return Err(IntoColorError::IntConversion); } + } + } Ok(Color { red: arr[0] as u8, green: arr[1] as u8, @@ -62,7 +71,18 @@ impl TryFrom<[i16; 3]> for Color { impl TryFrom<&[i16]> for Color { type Error = IntoColorError; fn try_from(slice: &[i16]) -> Result { - todo!(); + if slice.len() != 3 { return Err(IntoColorError::BadLen); } + for value in slice { + match value { + 0..=255 => (), + _ => { return Err(IntoColorError::IntConversion); } + } + } + Ok(Color { + red: slice[0] as u8, + green: slice[1] as u8, + blue: slice[2] as u8, + }) } }