Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Rendu TP 1: Rustlings - TEXIER - Antonin - AL1 #35

Open
wants to merge 18 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 1 addition & 2 deletions exercises/clippy/clippy1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,11 @@
// check clippy's suggestions from the output to solve the exercise.
// Execute `rustlings hint clippy1` for hints :)

// I AM NOT DONE

fn main() {
let x = 1.2331f64;
let y = 1.2332f64;
if y != x {
if (y - x).abs() > f64::EPSILON {
println!("Success!");
}
}
3 changes: 1 addition & 2 deletions exercises/clippy/clippy2.rs
Original file line number Diff line number Diff line change
@@ -1,12 +1,11 @@
// 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
7 changes: 3 additions & 4 deletions exercises/collections/hashmap1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,16 @@
// Execute the command `rustlings hint collections3` if you need
// hints.

// I AM NOT DONE

use std::collections::HashMap;

fn fruit_basket() -> HashMap<String, u32> {
let mut basket = // TODO: declare your hash map here.
let mut basket = HashMap::new();

// Two bananas are already given for you :)
basket.insert(String::from("banana"), 2);

// TODO: Put more fruits in your basket here.
basket.insert(String::from("apple"), 1);
basket.insert(String::from("mango"), 3);

basket
}
Expand Down
3 changes: 2 additions & 1 deletion exercises/collections/hashmap2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@
// Execute the command `rustlings hint collections4` if you need
// hints.

// I AM NOT DONE

use std::collections::HashMap;

Expand Down Expand Up @@ -50,6 +49,8 @@ mod tests {
basket.insert(Fruit::Apple, 4);
basket.insert(Fruit::Mango, 2);
basket.insert(Fruit::Lichi, 5);
basket.insert(Fruit::Pineapple, 6);
basket.insert(Fruit::Banana, 7);

basket
}
Expand Down
5 changes: 3 additions & 2 deletions exercises/collections/vec1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,12 @@
// Make me compile and pass the test!
// Execute the command `rustlings hint collections1` if you need hints.

// I AM NOT DONE

fn array_and_vec() -> ([i32; 4], Vec<i32>) {
let a = [10, 20, 30, 40]; // a plain array
let v = // TODO: declare your vector here with the macro for vectors
let mut v = Vec::new();

v.extend(&a);

(a, v)
}
Expand Down
4 changes: 1 addition & 3 deletions exercises/collections/vec2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,12 +7,10 @@
// Execute the command `rustlings hint collections2` if you need
// hints.

// I AM NOT DONE

fn vec_loop(mut v: Vec<i32>) -> Vec<i32> {
for i in v.iter_mut() {
// TODO: Fill this up so that each element in the Vec `v` is
// multiplied by 2.
*i *= 2;
}

// At this point, `v` should be equal to [4, 8, 12, 16, 20].
Expand Down
5 changes: 2 additions & 3 deletions exercises/conversions/as_ref_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,17 +2,16 @@
// 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
21 changes: 20 additions & 1 deletion exercises/conversions/from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -33,10 +33,29 @@ 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 {
let parts: Vec<&str> = s.split(',').collect();

if parts.len() < 2 {
return Person::default();
}

let name = parts[0];
let age = parts[1].parse::<i32>();

if name.is_empty() {
return Person::default();
}

match parts[1].parse() {
Ok(age) => Person {
name: String::from(name),
age,
},
Err(_) => Person::default(),
}
}
}

Expand Down
21 changes: 20 additions & 1 deletion exercises/conversions/from_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ struct Person {
age: usize,
}

// I AM NOT DONE
// Steps:
// 1. If the length of the provided string is 0, then return an error
// 2. Split the given string on the commas present in it
Expand All @@ -23,6 +22,26 @@ struct Person {
impl FromStr for Person {
type Err = String;
fn from_str(s: &str) -> Result<Person, Self::Err> {
let parts: Vec<&str> = s.split(',').collect();

if parts.len() < 2 {
return Err(String::from("Parsing error"));
}

let name = parts[0];
let age = parts[1].parse::<i32>();

if name.is_empty() {
return Err(String::from("No name given"));
}

match parts[1].parse() {
Ok(age) => Ok(Person {
name: String::from(name),
age,
}),
Err(_) => Err(String::from("Age parsing error")),
}
}
}

Expand Down
43 changes: 39 additions & 4 deletions exercises/conversions/try_from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,12 @@ struct Color {
blue: u8,
}

// I AM NOT DONE
fn isColorValid(red: i16, green: i16, blue: i16) -> bool {
let range = 0..=255;

range.contains(&red) && range.contains(&green) && range.contains(&blue)
}


// Your task is to complete this implementation
// and return an Ok result of inner type Color.
Expand All @@ -25,19 +30,49 @@ struct Color {
// Tuple implementation
impl TryFrom<(i16, i16, i16)> for Color {
type Error = String;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {}
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
if isColorValid(tuple.0, tuple.1, tuple.2) {
Ok(Color {
red: tuple.0 as u8,
green: tuple.1 as u8,
blue: tuple.2 as u8,
})
} else {
Err(String::from("Invalid colors"))
}
}
}

// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = String;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {}
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
if isColorValid(arr[0], arr[1], arr[2]) {
Ok(Color {
red: arr[0] as u8,
green: arr[1] as u8,
blue: arr[2] as u8,
})
} else {
Err(String::from("Invalid colors"))
}
}
}

// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = String;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {}
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
if slice.len() == 3 && isColorValid(slice[0], slice[1], slice[2]) {
Ok(Color {
red: slice[0] as u8,
green: slice[1] as u8,
blue: slice[2] as u8,
})
} else {
Err(String::from("Invalid colors"))
}
}
}

fn main() {
Expand Down
3 changes: 1 addition & 2 deletions exercises/conversions/using_as.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,11 +5,10 @@
// 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().fold(0.0, |a, b| a + b);
total / values.len()
total / values.len() as f64
}

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

// I AM NOT DONE

#[derive(Debug)]
enum Message {
// TODO: define a few types of messages as used below
Quit,
Echo,
Move,
ChangeColor,
}

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

// I AM NOT DONE

#[derive(Debug)]
enum Message {
// TODO: define the different variants used below
Move { x: i32, y: i32 },
Echo(String),
ChangeColor(i32, i32, i32),
Quit,
}

impl Message {
Expand Down
13 changes: 10 additions & 3 deletions exercises/enums/enums3.rs
Original file line number Diff line number Diff line change
@@ -1,10 +1,12 @@
// enums3.rs
// Address all the TODOs to make the tests pass!

// I AM NOT DONE

enum Message {
// TODO: implement the message variant types based on their usage below
Move(Point),
Echo(String),
ChangeColor((u8, u8, u8)),
Quit,
}

struct Point {
Expand Down Expand Up @@ -36,7 +38,12 @@ impl State {
}

fn process(&mut self, message: Message) {
// TODO: create a match expression to process the different message variants
match message {
Message::ChangeColor(value) => self.change_color(value),
Message::Quit => self.quit(),
Message::Echo(value) => self.echo(value),
Message::Move(value) => self.move_position(value),
}
}
}

Expand Down
9 changes: 4 additions & 5 deletions exercises/error_handling/errors1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@
// this function to have.
// Execute `rustlings hint errors1` for hints!

// I AM NOT DONE

pub fn generate_nametag_text(name: String) -> Option<String> {
pub fn generate_nametag_text(name: String) -> Result<String, String> {
if name.len() > 0 {
Some(format!("Hi! My name is {}", name))
Ok(format!("Hi! My name is {}", name))
} else {
// Empty names aren't allowed.
None
Err("`name` was empty; it must be nonempty.".into())
}
}

Expand All @@ -28,7 +27,7 @@ mod tests {
fn generates_nametag_text_for_a_nonempty_name() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
Some("Hi! My name is Beyoncé".into())
Ok("Hi! My name is Beyoncé".into())
);
}

Expand Down
3 changes: 1 addition & 2 deletions exercises/error_handling/errors2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,14 +16,13 @@
// There are at least two ways to implement this that are both correct-- but
// one is a lot shorter! Execute `rustlings hint errors2` for hints to both ways.

// I AM NOT DONE

use std::num::ParseIntError;

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
let processing_fee = 1;
let cost_per_item = 5;
let qty = item_quantity.parse::<i32>();
let qty = item_quantity.parse::<i32>()?;

Ok(qty * cost_per_item + processing_fee)
}
Expand Down
5 changes: 3 additions & 2 deletions exercises/error_handling/errors3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,10 @@
// Why not? What should we do to fix it?
// Execute `rustlings hint errors3` for hints!

// I AM NOT DONE

use std::num::ParseIntError;

fn main() {
fn main() -> Result<(), ParseIntError> {
let mut tokens = 100;
let pretend_user_input = "8";

Expand All @@ -20,6 +19,8 @@ fn main() {
tokens -= cost;
println!("You now have {} tokens.", tokens);
}

Ok(())
}

pub fn total_cost(item_quantity: &str) -> Result<i32, ParseIntError> {
Expand Down
Loading