Skip to content

Commit d8fd7fc

Browse files
author
build
committed
feat:exercises
1 parent 9b7e625 commit d8fd7fc

File tree

2 files changed

+25
-8
lines changed

2 files changed

+25
-8
lines changed

exercises/conversions/as_ref_mut.rs

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -7,25 +7,24 @@
77
// Execute `rustlings hint as_ref_mut` or use the `hint` watch subcommand for a
88
// hint.
99

10-
// I AM NOT DONE
11-
1210
// Obtain the number of bytes (not characters) in the given argument.
1311
// TODO: Add the AsRef trait appropriately as a trait bound.
14-
fn byte_counter<T>(arg: T) -> usize {
12+
fn byte_counter<T: AsRef<str>>(arg: T) -> usize {
1513
arg.as_ref().as_bytes().len()
1614
}
1715

1816
// Obtain the number of characters (not bytes) in the given argument.
1917
// TODO: Add the AsRef trait appropriately as a trait bound.
20-
fn char_counter<T>(arg: T) -> usize {
18+
fn char_counter<T: AsRef<str>>(arg: T) -> usize {
2119
arg.as_ref().chars().count()
2220
}
2321

2422
// Squares a number using as_mut().
2523
// TODO: Add the appropriate trait bound.
26-
fn num_sq<T>(arg: &mut T) {
24+
fn num_sq<T: AsMut<u32>>(arg: &mut T) {
2725
// TODO: Implement the function body.
28-
???
26+
let num = arg.as_mut();
27+
*num = num.pow(2);
2928
}
3029

3130
#[cfg(test)]

exercises/conversions/try_from_into.rs

Lines changed: 20 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -27,8 +27,6 @@ enum IntoColorError {
2727
IntConversion,
2828
}
2929

30-
// I AM NOT DONE
31-
3230
// Your task is to complete this implementation and return an Ok result of inner
3331
// type Color. You need to create an implementation for a tuple of three
3432
// integers, an array of three integers, and a slice of integers.
@@ -41,20 +39,40 @@ enum IntoColorError {
4139
impl TryFrom<(i16, i16, i16)> for Color {
4240
type Error = IntoColorError;
4341
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
42+
let (r, g, b) = tuple;
43+
if (0..=255).contains(&r) && (0..=255).contains(&g) && (0..255).contains(&b) {
44+
return Ok(Color {
45+
red: r as u8,
46+
green: g as u8,
47+
blue: b as u8,
48+
});
49+
} else {
50+
return Err(IntoColorError::IntConversion);
51+
}
4452
}
4553
}
4654

4755
// Array implementation
4856
impl TryFrom<[i16; 3]> for Color {
4957
type Error = IntoColorError;
5058
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
59+
if arr.len() != 3 {
60+
return Err(IntoColorError::BadLen);
61+
}
62+
63+
Color::try_from((arr[0], arr[1], arr[2]))
5164
}
5265
}
5366

5467
// Slice implementation
5568
impl TryFrom<&[i16]> for Color {
5669
type Error = IntoColorError;
5770
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
71+
if slice.len() != 3 {
72+
return Err(IntoColorError::BadLen);
73+
}
74+
75+
Color::try_from((slice[0], slice[1], slice[2]))
5876
}
5977
}
6078

0 commit comments

Comments
 (0)