Skip to content

Commit

Permalink
Finished rustlings
Browse files Browse the repository at this point in the history
  • Loading branch information
Clipsey committed Jul 3, 2022
1 parent 42a4095 commit 41575ec
Show file tree
Hide file tree
Showing 18 changed files with 174 additions and 51 deletions.
8 changes: 6 additions & 2 deletions rustlings/exercises/advanced_errors/advanced_errs1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,6 @@
// Make this code compile! Execute `rustlings hint advanced_errs1` for
// hints :)

// I AM NOT DONE

use std::num::ParseIntError;
use std::str::FromStr;

Expand All @@ -24,12 +22,18 @@ impl From<CreationError> for ParsePosNonzeroError {
fn from(e: CreationError) -> Self {
// TODO: complete this implementation so that the `?` operator will
// work for `CreationError`
ParsePosNonzeroError::Creation(e)
}
}

// TODO: implement another instance of the `From` trait here so that the
// `?` operator will work in the other place in the `FromStr`
// implementation below.
impl From<ParseIntError> for ParsePosNonzeroError {
fn from(e: ParseIntError) -> Self {
ParsePosNonzeroError::ParseInt(e)
}
}

// Don't change anything below this line.

Expand Down
16 changes: 14 additions & 2 deletions rustlings/exercises/advanced_errors/advanced_errs2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,6 @@
// 4. Complete the partial implementation of `Display` for
// `ParseClimateError`.

// I AM NOT DONE

use std::error::Error;
use std::fmt::{self, Display, Formatter};
use std::num::{ParseFloatError, ParseIntError};
Expand Down Expand Up @@ -47,11 +45,13 @@ impl From<ParseIntError> for ParseClimateError {
impl From<ParseFloatError> for ParseClimateError {
fn from(e: ParseFloatError) -> Self {
// TODO: Complete this function
ParseClimateError::ParseFloat(e)
}
}

// TODO: Implement a missing trait so that `main()` below will compile. It
// is not necessary to implement any methods inside the missing trait.
impl Error for ParseClimateError {}

// The `Display` trait allows for other code to obtain the error formatted
// as a user-visible string.
Expand All @@ -64,6 +64,9 @@ impl Display for ParseClimateError {
match self {
NoCity => write!(f, "no city name"),
ParseFloat(e) => write!(f, "error parsing temperature: {}", e),
Empty => write!(f, "empty input"),
BadLen => write!(f, "incorrect number of fields"),
ParseInt(e) => write!(f, "error parsing year: {}", e),
}
}
}
Expand All @@ -88,11 +91,20 @@ impl FromStr for Climate {
// TODO: Complete this function by making it handle the missing error
// cases.
fn from_str(s: &str) -> Result<Self, Self::Err> {
if (s.len() == 0) {
return Err(ParseClimateError::Empty);
}
let v: Vec<_> = s.split(',').collect();

let (city, year, temp) = match &v[..] {
[city, year, temp] => (city.to_string(), year, temp),
_ => return Err(ParseClimateError::BadLen),
};

if (city.len() == 0) {
return Err(ParseClimateError::NoCity);
}

let year: u32 = year.parse()?;
let temp: f32 = temp.parse()?;
Ok(Climate { city, year, temp })
Expand Down
4 changes: 1 addition & 3 deletions rustlings/exercises/clippy/clippy1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,10 @@
// check clippy's suggestions from the output to solve the exercise.
// Execute `rustlings hint clippy1` for hints :)

// I AM NOT DONE

use std::f32;

fn main() {
let pi = 3.14f32;
let pi = f32::consts::PI;
let radius = 5.00f32;

let area = pi * f32::powi(radius, 2);
Expand Down
4 changes: 1 addition & 3 deletions rustlings/exercises/clippy/clippy2.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
// clippy2.rs
// Make me compile! Execute `rustlings hint clippy2` for hints :)

// I AM NOT DONE

fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
if let Some(x) = option {
res += x;
}
println!("{}", res);
Expand Down
6 changes: 2 additions & 4 deletions rustlings/exercises/conversions/as_ref_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,15 @@
// Read more about them at https://doc.rust-lang.org/std/convert/trait.AsRef.html
// and https://doc.rust-lang.org/std/convert/trait.AsMut.html, respectively.

// I AM NOT DONE

// Obtain the number of bytes (not characters) in the given argument
// 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
// 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()
}

Expand Down
38 changes: 36 additions & 2 deletions rustlings/exercises/conversions/from_into.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use std::num::ParseIntError;

// The From trait is used for value-to-value conversions.
// If From is implemented correctly for a type, the Into trait should work conversely.
// You can read more about it at https://doc.rust-lang.org/std/convert/trait.From.html
Expand Down Expand Up @@ -33,10 +35,42 @@ impl Default for Person {
// If while parsing the age, something goes wrong, then return the default of Person
// Otherwise, then return an instantiated Person object with the results

// I AM NOT DONE

impl From<&str> for Person {
fn from(s: &str) -> Person {
if s.len() == 0 {
return Person::default();
}
let mut xs = s.split(",");

let name = match xs.next() {
Some(inner_name) => {
if inner_name.len() == 0 {
return Person::default();
}
inner_name
}
None => return Person::default(),
};

let age = match xs.next() {
Some(inner_age) => {
let num = inner_age.parse::<usize>();
match num {
Ok(a) => a,
Err(_e) => return Person::default(),
}
}
None => return Person::default(),
};

if xs.next() != None {
return Person::default();
}

Person {
age,
name: name.to_string(),
}
}
}

Expand Down
33 changes: 31 additions & 2 deletions rustlings/exercises/conversions/from_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,6 @@ enum ParsePersonError {
ParseInt(ParseIntError),
}

// I AM NOT DONE

// Steps:
// 1. If the length of the provided string is 0, an error should be returned
// 2. Split the given string on the commas present in it
Expand All @@ -41,6 +39,37 @@ enum ParsePersonError {
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.len() == 0 {
return Err(ParsePersonError::Empty);
}

let mut xs = s.split(",");
let name = match xs.next() {
Some(inner_name) => {
if inner_name.len() == 0 {
return Err(ParsePersonError::NoName);
}
inner_name
}
None => return Err(ParsePersonError::BadLen),
};

let age = match xs.next() {
Some(inner_age) => match inner_age.parse::<usize>() {
Ok(ia) => ia,
Err(e) => return Err(ParsePersonError::ParseInt(e)),
},
None => return Err(ParsePersonError::BadLen),
};

if let Some(x) = xs.next() {
return Err(ParsePersonError::BadLen);
}

return Ok(Person {
age,
name: name.to_string(),
});
}
}

Expand Down
58 changes: 56 additions & 2 deletions rustlings/exercises/conversions/try_from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,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,
Expand All @@ -36,20 +34,76 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if tuple.0 > 255 || tuple.0 < 0 {
return Err(IntoColorError::IntConversion);
}
if tuple.1 > 255 || tuple.1 < 0 {
return Err(IntoColorError::IntConversion);
}
if tuple.2 > 255 || tuple.2 < 0 {
return Err(IntoColorError::IntConversion);
}

Ok(Color {
red: tuple.0 as u8,
green: tuple.1 as u8,
blue: tuple.2 as u8,
})
}
}

// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
if arr[0] > 255 || arr[0] < 0 {
return Err(IntoColorError::IntConversion);
}
if arr[1] > 255 || arr[1] < 0 {
return Err(IntoColorError::IntConversion);
}
if arr[2] > 255 || arr[2] < 0 {
return Err(IntoColorError::IntConversion);
}

Ok(Color {
red: arr[0] as u8,
green: arr[1] as u8,
blue: arr[2] as u8,
})
}
}

// Slice implementation
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 mut xs = slice.iter();

let red = *xs.next().unwrap();
if red > 255 || red < 0 {
return Err(IntoColorError::IntConversion);
}

let green = *xs.next().unwrap();
if green > 255 || green < 0 {
return Err(IntoColorError::IntConversion);
}

let blue = *xs.next().unwrap();
if blue > 255 || blue < 0 {
return Err(IntoColorError::IntConversion);
}

Ok(Color {
red: red as u8,
green: green as u8,
blue: blue as u8,
})
}
}

Expand Down
4 changes: 1 addition & 3 deletions rustlings/exercises/conversions/using_as.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,9 @@
// The goal is to make sure that the division does not fail to compile
// and returns the proper type.

// I AM NOT DONE

fn average(values: &[f64]) -> f64 {
let total = values.iter().sum::<f64>();
total / values.len()
total / values.len() as f64
}

fn main() {
Expand Down
4 changes: 1 addition & 3 deletions rustlings/exercises/macros/macros1.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// macros1.rs
// Make me compile! Execute `rustlings hint macros1` for hints :)

// I AM NOT DONE

macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}

fn main() {
my_macro();
my_macro!();
}
10 changes: 4 additions & 6 deletions rustlings/exercises/macros/macros2.rs
Original file line number Diff line number Diff line change
@@ -1,14 +1,12 @@
// macros2.rs
// Make me compile! Execute `rustlings hint macros2` for hints :)

// I AM NOT DONE

fn main() {
my_macro!();
}

macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}

fn main() {
my_macro!();
}
5 changes: 3 additions & 2 deletions rustlings/exercises/macros/macros3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,15 @@
// Make me compile, without taking the macro out of the module!
// Execute `rustlings hint macros3` for hints :)

// I AM NOT DONE

#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
println!("Check out my macro!");
};
}

// pub(crate) use my_macro;
}

fn main() {
Expand Down
6 changes: 2 additions & 4 deletions rustlings/exercises/macros/macros4.rs
Original file line number Diff line number Diff line change
@@ -1,15 +1,13 @@
// macros4.rs
// Make me compile! Execute `rustlings hint macros4` for hints :)

// I AM NOT DONE

macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
};
}

fn main() {
Expand Down
Loading

0 comments on commit 41575ec

Please sign in to comment.