Skip to content

Commit

Permalink
a little love...
Browse files Browse the repository at this point in the history
  • Loading branch information
aqpower committed Oct 15, 2023
1 parent 7d52632 commit 8194de4
Show file tree
Hide file tree
Showing 14 changed files with 122 additions and 41 deletions.
5 changes: 2 additions & 3 deletions exercises/clippy/clippy1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,11 @@
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::f32;
use std::f32::{self, consts::PI};

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

let area = pi * f32::powi(radius, 2);
Expand Down
3 changes: 1 addition & 2 deletions exercises/clippy/clippy2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,11 @@
// Execute `rustlings hint clippy2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
let mut res = 42;
let option = Some(12);
for x in option {
while let Some(x) = option {
res += x;
}
println!("{}", res);
Expand Down
12 changes: 3 additions & 9 deletions exercises/clippy/clippy3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,22 @@
//
// Execute `rustlings hint clippy3` or use the `hint` watch subcommand for a hint.

// I AM NOT DONE

#[allow(unused_variables, unused_assignments)]
fn main() {
let my_option: Option<()> = None;
if my_option.is_none() {
my_option.unwrap();
}

let my_arr = &[
-1, -2, -3
-1, -2, -3,
-4, -5, -6
];
println!("My array! Here it is: {:?}", my_arr);

let my_empty_vec = vec![1, 2, 3, 4, 5].resize(0, 5);
let my_empty_vec = vec![1, 2, 3, 4, 5];
println!("This Vec is empty, see? {:?}", my_empty_vec);

let mut value_a = 45;
let mut value_b = 66;
// Let's swap these two!
value_a = value_b;
value_b = value_a;
std::mem::swap(&mut value_a, &mut value_b);
println!("value a: {}; value b: {}", value_a, value_b);
}
17 changes: 16 additions & 1 deletion exercises/conversions/from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@
// Execute `rustlings hint from_into` or use the `hint` watch subcommand for a
// hint.

use std::usize;

#[derive(Debug)]
struct Person {
name: String,
Expand Down Expand Up @@ -40,10 +42,23 @@ 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 s = s.to_string();
let parts: Vec<&str> = s.split(',').collect();

if parts.len() != 2 || parts[0].is_empty() || parts[1].parse::<usize>().is_err() {
Person {
name: "John".to_string(),
age: 30,
}
} else {
Person {
name: parts[0].to_string(),
age: parts[1].parse::<usize>().unwrap(),
}
}
}
}

Expand Down
19 changes: 18 additions & 1 deletion exercises/conversions/from_str.rs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,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
Expand All @@ -52,6 +51,24 @@ enum ParsePersonError {
impl FromStr for Person {
type Err = ParsePersonError;
fn from_str(s: &str) -> Result<Person, Self::Err> {
if s.is_empty() {
return Err(ParsePersonError::Empty);
}
let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Err(ParsePersonError::BadLen);
}
if parts[0].is_empty() {
return Err(ParsePersonError::NoName);
}
let age = match parts[1].parse::<usize>() {
Ok(parsed_age) => parsed_age,
Err(parse_err) => return Err(ParsePersonError::ParseInt(parse_err)),
};
Ok(Person {
name: parts[0].to_string(),
age,
})
}
}

Expand Down
66 changes: 65 additions & 1 deletion exercises/conversions/try_from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,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
Expand All @@ -41,20 +40,85 @@ enum IntoColorError {
impl TryFrom<(i16, i16, i16)> for Color {
type Error = IntoColorError;
fn try_from(tuple: (i16, i16, i16)) -> Result<Self, Self::Error> {
let (a, b, c) = tuple;
let ua = match a.to_string().parse::<u8>() {
Ok(num) => num,
_ => return Err(IntoColorError::IntConversion),
};
let ub = match b.to_string().parse::<u8>() {
Ok(num) => num,
_ => return Err(IntoColorError::IntConversion),
};
let uc = match c.to_string().parse::<u8>() {
Ok(num) => num,
_ => return Err(IntoColorError::IntConversion),
};
Ok(Color {
red: ua,
green: ub,
blue: uc,
})
}
}

// Array implementation
impl TryFrom<[i16; 3]> for Color {
type Error = IntoColorError;
fn try_from(arr: [i16; 3]) -> Result<Self, Self::Error> {
if arr.len() != 3 {
return Err(IntoColorError::BadLen);
}
let a: Vec<Option<u8>> = arr
.iter()
.map(|x| {
if x.to_string().parse::<u8>().is_err() {
None
} else {
Some(x.to_string().parse::<u8>().unwrap())
}
})
.collect();
for item in &a {
if *item == None {
return Err(IntoColorError::IntConversion);
}
}
Ok(Color {
red: a[0].unwrap(),
green: a[1].unwrap(),
blue: a[2].unwrap(),
})
}
}

// Slice implementation
impl TryFrom<&[i16]> for Color {
type Error = IntoColorError;
fn try_from(slice: &[i16]) -> Result<Self, Self::Error> {
let arr: Vec<i16> = slice.iter().map(|x| x.clone()).collect();
if arr.len() != 3 {
return Err(IntoColorError::BadLen);
}
let a: Vec<Option<u8>> = arr
.iter()
.map(|x| {
if x.to_string().parse::<u8>().is_err() {
None
} else {
Some(x.to_string().parse::<u8>().unwrap())
}
})
.collect();
for item in &a {
if *item == None {
return Err(IntoColorError::IntConversion);
}
}
Ok(Color {
red: a[0].unwrap(),
green: a[1].unwrap(),
blue: a[2].unwrap(),
})
}
}

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 @@ -10,11 +10,10 @@
// Execute `rustlings hint using_as` or use the `hint` watch subcommand for a
// hint.

// 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
3 changes: 1 addition & 2 deletions exercises/macros/macros1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint macros1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

macro_rules! my_macro {
() => {
Expand All @@ -12,5 +11,5 @@ macro_rules! my_macro {
}

fn main() {
my_macro();
my_macro!();
}
11 changes: 5 additions & 6 deletions exercises/macros/macros2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,13 @@
// Execute `rustlings hint macros2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

fn main() {
my_macro!();
}

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

fn main() {
my_macro!();
}

3 changes: 1 addition & 2 deletions exercises/macros/macros3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,7 @@
// Execute `rustlings hint macros3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[macro_use]
mod macros {
macro_rules! my_macro {
() => {
Expand Down
3 changes: 1 addition & 2 deletions exercises/macros/macros4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,12 @@
// Execute `rustlings hint macros4` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

#[rustfmt::skip]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
}
};
($val:expr) => {
println!("Look at this other macro: {}", $val);
}
Expand Down
2 changes: 1 addition & 1 deletion exercises/threads/threads1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@
// Execute `rustlings hint threads1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::thread;
use std::time::{Duration, Instant};
Expand All @@ -27,6 +26,7 @@ fn main() {
let mut results: Vec<u128> = vec![];
for handle in handles {
// TODO: a struct is returned from thread::spawn, can you use it?
results.push(handle.join().unwrap());
}

if results.len() != 10 {
Expand Down
9 changes: 4 additions & 5 deletions exercises/threads/threads2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,8 @@
// Execute `rustlings hint threads2` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::sync::Arc;
use std::sync::{Arc, Mutex};
use std::thread;
use std::time::Duration;

Expand All @@ -18,14 +17,14 @@ struct JobStatus {
}

fn main() {
let status = Arc::new(JobStatus { jobs_completed: 0 });
let status = Arc::new(Mutex::new(JobStatus { jobs_completed: 0 }));
let mut handles = vec![];
for _ in 0..10 {
let status_shared = Arc::clone(&status);
let handle = thread::spawn(move || {
thread::sleep(Duration::from_millis(250));
// TODO: You must take an action before you update a shared value
status_shared.jobs_completed += 1;
status_shared.lock().unwrap().jobs_completed += 1;
});
handles.push(handle);
}
Expand All @@ -34,6 +33,6 @@ fn main() {
// TODO: Print the value of the JobStatus.jobs_completed. Did you notice
// anything interesting in the output? Do you have to 'join' on all the
// handles?
println!("jobs completed {}", ???);
println!("jobs completed {}", status.lock().unwrap().jobs_completed);
}
}
7 changes: 3 additions & 4 deletions exercises/threads/threads3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@
// Execute `rustlings hint threads3` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE

use std::sync::mpsc;
use std::sync::Arc;
Expand All @@ -30,19 +29,19 @@ fn send_tx(q: Queue, tx: mpsc::Sender<u32>) -> () {
let qc = Arc::new(q);
let qc1 = Arc::clone(&qc);
let qc2 = Arc::clone(&qc);

let tx1 = tx.clone();
thread::spawn(move || {
for val in &qc1.first_half {
println!("sending {:?}", val);
tx.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});

thread::spawn(move || {
for val in &qc2.second_half {
println!("sending {:?}", val);
tx.send(*val).unwrap();
tx1.send(*val).unwrap();
thread::sleep(Duration::from_secs(1));
}
});
Expand Down

0 comments on commit 8194de4

Please sign in to comment.