Skip to content

Commit

Permalink
update
Browse files Browse the repository at this point in the history
  • Loading branch information
baiyazi233 committed Apr 11, 2024
1 parent 102bae5 commit 5926fd3
Show file tree
Hide file tree
Showing 23 changed files with 138 additions and 65 deletions.
4 changes: 2 additions & 2 deletions exercises/clippy/clippy1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,12 @@
// Execute `rustlings hint clippy1` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


use std::f32;

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

let area = pi * f32::powi(radius, 2);
Expand Down
4 changes: 2 additions & 2 deletions exercises/clippy/clippy2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,12 @@
// 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 {
if let Some(x) = option {
res += x;
}
println!("{}", res);
Expand Down
15 changes: 6 additions & 9 deletions exercises/clippy/clippy3.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,28 +4,25 @@
//
// 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
-4, -5, -6
-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 mut my_empty_vec = vec![1, 2, 3, 4, 5];
my_empty_vec.clear();
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);
}
11 changes: 6 additions & 5 deletions exercises/conversions/as_ref_mut.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,25 +7,26 @@
// 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.
???
let num = arg.as_mut();
*num *= *num;
}

#[cfg(test)]
Expand Down
22 changes: 21 additions & 1 deletion exercises/conversions/from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,30 @@ 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.is_empty() {
return Person::default();
}

let parts: Vec<&str> = s.split(',').collect();
if parts.len() != 2 {
return Person::default();
}

let name = parts[0].to_string();
if name.is_empty() {
return Person::default();
}

let age = match parts[1].parse::<usize>() {
Ok(age) => age,
Err(_) => return Person::default(),
};

Person { name, age }
}
}

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,7 @@ 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 +52,23 @@ 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);
}

let name = parts[0].to_string();
if name.is_empty() {
return Err(ParsePersonError::NoName);
}

let age = parts[1].parse::<usize>().map_err(ParsePersonError::ParseInt)?;

Ok(Person { name, age })
}
}

Expand Down
16 changes: 15 additions & 1 deletion exercises/conversions/try_from_into.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ 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 +41,34 @@ 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 < 0 || tuple.1 < 0 || tuple.2 < 0 || tuple.0 > 255 || tuple.1 > 255 || tuple.2 > 255 {
Err(IntoColorError::IntConversion)
} else {
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> {
(arr[0], arr[1], arr[2]).try_into()
}
}

// 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);
}
(slice[0], slice[1], slice[2]).try_into()
}
}

Expand Down
4 changes: 2 additions & 2 deletions exercises/conversions/using_as.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,11 +10,11 @@
// 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
4 changes: 2 additions & 2 deletions exercises/macros/macros1.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
// 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 +12,5 @@ macro_rules! my_macro {
}

fn main() {
my_macro();
my_macro!();
}
10 changes: 6 additions & 4 deletions exercises/macros/macros2.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,16 @@
// 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!();
}


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

// I AM NOT DONE

mod macros {

pub mod macros {
#[macro_export]
macro_rules! my_macro {
() => {
println!("Check out my macro!");
Expand Down
4 changes: 2 additions & 2 deletions exercises/macros/macros4.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,13 +3,13 @@
// 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
7 changes: 7 additions & 0 deletions exercises/tests/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions exercises/tests/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
[package]
name = "tests8"
version = "0.0.1"
edition = "2021"
[[bin]]
name = "tests8"
path = "tests8.rs"
7 changes: 2 additions & 5 deletions exercises/tests/build.rs
Original file line number Diff line number Diff line change
Expand Up @@ -10,15 +10,12 @@ fn main() {
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_secs(); // What's the use of this timestamp here?
let your_command = format!(
"Your command here with {}, please checkout exercises/tests/build.rs",
timestamp
);
let your_command = format!("rustc-env=TEST_FOO={}", timestamp);
println!("cargo:{}", your_command);

// In tests8, we should enable "pass" feature to make the
// testcase return early. Fill in the command to tell
// Cargo about that.
let your_command = "Your command here, please checkout exercises/tests/build.rs";
let your_command = "rustc-cfg=feature=\"pass\"";
println!("cargo:{}", your_command);
}
4 changes: 2 additions & 2 deletions exercises/tests/tests5.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@
// Execute `rustlings hint tests5` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


/// # Safety
///
Expand All @@ -32,7 +32,7 @@ unsafe fn modify_by_address(address: usize) {
// code's behavior and the contract of this function. You may use the
// comment of the test below as your format reference.
unsafe {
todo!("Your code goes here")
*(address as *mut u32) = 0xAABBCCDD;
}
}

Expand Down
7 changes: 4 additions & 3 deletions exercises/tests/tests6.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// Execute `rustlings hint tests6` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


struct Foo {
a: u128,
Expand All @@ -20,8 +20,9 @@ struct Foo {
unsafe fn raw_pointer_to_box(ptr: *mut Foo) -> Box<Foo> {
// SAFETY: The `ptr` contains an owned box of `Foo` by contract. We
// simply reconstruct the box from that pointer.
let mut ret: Box<Foo> = unsafe { ??? };
todo!("The rest of the code goes here")
let mut ret: Box<Foo> = Box::from_raw(ptr);
ret.b = Some("hello".to_owned());
ret
}

#[cfg(test)]
Expand Down
2 changes: 1 addition & 1 deletion exercises/tests/tests7.rs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@
// Execute `rustlings hint tests7` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


fn main() {}

Expand Down
2 changes: 1 addition & 1 deletion exercises/tests/tests8.rs
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
// Execute `rustlings hint tests8` or use the `hint` watch subcommand for a
// hint.

// I AM NOT DONE


fn main() {}

Expand Down
5 changes: 4 additions & 1 deletion exercises/tests/tests9.rs
Original file line number Diff line number Diff line change
Expand Up @@ -27,15 +27,18 @@
//
// You should NOT modify any existing code except for adding two lines of attributes.

// I AM NOT DONE


extern "Rust" {
#[link_name = "my_demo_function"]
fn my_demo_function(a: u32) -> u32;
#[link_name = "my_demo_function"]
fn my_demo_function_alias(a: u32) -> u32;
}

mod Foo {
// No `extern` equals `extern "Rust"`.
#[no_mangle]
fn my_demo_function(a: u32) -> u32 {
a
}
Expand Down
Loading

0 comments on commit 5926fd3

Please sign in to comment.