finish conversions

This commit is contained in:
horaoen 2024-02-02 11:53:06 +08:00
parent ae1c7a907c
commit 57cbf55b08
2 changed files with 44 additions and 8 deletions

View File

@ -7,25 +7,23 @@
// 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() * *arg.as_mut()
}
#[cfg(test)]

View File

@ -9,6 +9,7 @@
// Execute `rustlings hint try_from_into` or use the `hint` watch subcommand for
// a hint.
use core::slice;
use std::convert::{TryFrom, TryInto};
#[derive(Debug, PartialEq)]
@ -27,8 +28,6 @@ enum IntoColorError {
IntConversion,
}
// I AM NOT DONE
// Your task is to complete this implementation and return an Ok result of inner
// type Color. You need to create an implementation for a tuple of three
// integers, an array of three integers, and a slice of integers.
@ -41,6 +40,16 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let (r, g, b) = tuple;
if r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255 {
Err(IntoColorError::IntConversion)
} else {
Ok(Self {
red: r as u8,
green: g as u8,
blue: b as u8,
})
}
}
}
@ -48,6 +57,19 @@ 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> {
let r = arr[0];
let g = arr[1];
let b = arr[2];
if r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255 {
Err(IntoColorError::IntConversion)
} else {
Ok(Self {
red: r as u8,
green: g as u8,
blue: b as u8,
})
}
}
}
@ -55,6 +77,22 @@ impl TryFrom<[i16; 3]> for Color {
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() != 3 {
return Err(IntoColorError::BadLen);
}
let r = slice[0];
let g = slice[1];
let b = slice[2];
if r < 0 || g < 0 || b < 0 || r > 255 || g > 255 || b > 255 {
Err(IntoColorError::IntConversion)
} else {
Ok(Self {
red: r as u8,
green: g as u8,
blue: b as u8,
})
}
}
}