Finished Rustlings
This commit is contained in:
parent
05f28181d0
commit
df53b5803e
@ -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<T>(arg: T) -> usize {
|
||||
fn byte_counter<T: AsRef<str>>(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<T>(arg: T) -> usize {
|
||||
fn char_counter<T: AsRef<str>>(arg: T) -> usize {
|
||||
arg.as_ref().chars().count()
|
||||
}
|
||||
|
||||
// Squares a number using as_mut().
|
||||
// TODO: Add the appropriate trait bound.
|
||||
fn num_sq<T>(arg: &mut T) {
|
||||
fn num_sq<T: AsMut<u32>>(arg: &mut T) {
|
||||
// TODO: Implement the function body.
|
||||
???
|
||||
*arg.as_mut() *= *arg.as_mut();
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
|
@ -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<Self, Self::Error> {
|
||||
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<Self, Self::Error> {
|
||||
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<Self, Self::Error> {
|
||||
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,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
|
Loading…
Reference in New Issue
Block a user