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

Final project submission #41

Open
wants to merge 5 commits into
base: final-project
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
1 change: 0 additions & 1 deletion .gitignore

This file was deleted.

16 changes: 16 additions & 0 deletions Cargo.lock

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

22 changes: 21 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,10 @@ members = [
"./exercises/basic-of-rust",
"./exercises/ownership-borrowing",
"./exercises/complex-type",
"./exercises/generic-type",
"./exercises/traits",
"./exercises/error-handling",
"./final-project/state-machine-atm",

]

Expand All @@ -33,5 +37,21 @@ path = "./exercises/complex-type/src/structs.rs"
name = "enums"
path = "./exercises/complex-type/src/enums.rs"

[[test]]
name = "generic-type"
path = "./exercises/generic-type/src/lib.rs"

[[test]]
name = "traits"
path = "./exercises/traits/src/lib.rs"

[[test]]
name = "error-handling"
path = "./exercises/error-handling/src/lib.rs"


[[test]]
name = "final-project"
path = "./final-project/state-machine-atm/src/lib.rs"

[dependencies]
[dependencies]
8 changes: 8 additions & 0 deletions exercises/error-handling/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "error-handling"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
10 changes: 10 additions & 0 deletions exercises/error-handling/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## Complete Error Handling exercises
### Error Handling

+ Make it compile and Complete `Error handlings` exercises in `exercises/error-handling/src/lib.rs`

+ Run tests to check your implementation

```
cargo test --test error-handling
```
82 changes: 82 additions & 0 deletions exercises/error-handling/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,82 @@
//Execise 1
// Make it compile in unit test
// Run tests
// Hint: Convert Option to Result
fn generate_nametag_text(name: String) -> Option<String> {
if name.is_empty() {
// Empty names aren't allowed.
None
} else {
Some(format!("Hi! My name is {}", name))
}
}
// Exercise 2
// Make it compile in unit test
// Run tests
// Hint: &str to integer conversion by using parse method and return Result
use std::num::ParseIntError;

fn parse_number(s: &str) -> Result<i32, ParseIntError> {
todo!()
}

// Exercise 3
// Make it compile in unit test
// Run tests
// Hint: Custom Error
#[derive(PartialEq, Debug)]
struct PositiveNonzeroInteger(u64);

#[derive(PartialEq, Debug)]
enum CreationError {
Negative,
Zero,
}

impl PositiveNonzeroInteger {
fn new(value: i64) -> Result<PositiveNonzeroInteger, CreationError> {
// Hmm...? Why is this only returning an Ok value?
Ok(PositiveNonzeroInteger(value as u64))
}
}

#[cfg(test)]
mod tests {
use super::*;

/// Test for exercise 1
#[test]
fn exercise1_should_work() {
assert_eq!(
generate_nametag_text("Beyoncé".into()),
Ok("Hi! My name is Beyoncé".into())
);

assert_eq!(
generate_nametag_text("".into()),
// Don't change this line
Err("`name` was empty; it must be nonempty.".into())
);
}

/// Test for exercise 2
#[test]
fn exercise2_should_work() {
assert_eq!(parse_number("42"), Ok(42));
assert_eq!(
parse_number("invalid"),
Err("invalid digit found in string".parse().unwrap())
);
}

/// Test for exercise 3
#[test]
fn exercise3_should_work() {
assert!(PositiveNonzeroInteger::new(10).is_ok());
assert_eq!(
Err(CreationError::Negative),
PositiveNonzeroInteger::new(-10)
);
assert_eq!(Err(CreationError::Zero), PositiveNonzeroInteger::new(0));
}
}
8 changes: 8 additions & 0 deletions exercises/generic-type/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "generic-type"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
4 changes: 4 additions & 0 deletions exercises/generic-type/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
## Complete Generic type exercises
### Generic type

+ Make it compile, add logic code `Generic Type` exercises in `exercises/generic-type/src/lib.rs`
144 changes: 144 additions & 0 deletions exercises/generic-type/src/lib.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,144 @@
// Exercise 1
// Implement struct Point to make it work.
// Make it compile
fn exercise1() {
let integer = Position { x: 5, y: 10 };
let float = Position { x: 1.0, y: 4.0 };
}



// Exercise 2
// Modify this struct to make the code work
// Make it compile
struct Point<T> {
x: T,
y: T,
}

fn exercise2() {
// DON'T modify this code.
let p = Point{x: 5, y : "hello".to_string()};
}



// Exercise 3
// Make it compile
// Add generic for Val to make the code work, DON'T modify the code in `main`.
struct Val {
val: f64,
}

impl Val {
fn value(&self) -> &f64 {
&self.val
}
}


fn exercise3() {
let x = Val{ val: 3.0 };
let y = Val{ val: "hello".to_string()};
println!("{}, {}", x.value(), y.value());
}

// Exercise 4
// Find the maximum value in a collection
// Make it compile
// Implementing logic
// Run tests

fn find_max<T>(collection: &[T]) -> Option<&T> {
todo!()
}

// Exercise 5
// Reverse the elements in a collection
// Make it compile
// Run tests
fn reverse_collection<T>(collection: &[T]) {
todo!()
}


// Exercise 6
// Function to check if a collection contains a specific value
fn contains_value<T>(collection: &[T], value: &T) -> bool {
todo!()
}

// Unit tests
#[cfg(test)]
mod tests {
use super::*;

// Test for exercise 4
#[test]
fn test_find_max_with_numbers() {
let numbers = vec![1, 5, 3, 8, 2];
assert_eq!(find_max(&numbers), Some(&8));
}

// Test for exercise 4
#[test]
fn test_find_max_with_strings() {
let strings = vec!["apple", "banana", "cherry", "durian"];
assert_eq!(find_max(&strings), Some(&"durian"));
}

// Test for exercise 4
#[test]
fn test_find_max_with_empty_collection() {
let empty: Vec<i32> = Vec::new();
assert_eq!(find_max(&empty), None);
}

// Test for exercise 5
#[test]
fn test_reverse_collection_with_numbers() {
let mut numbers = vec![1, 2, 3, 4, 5];
reverse_collection(&mut numbers);
assert_eq!(numbers, vec![5, 4, 3, 2, 1]);
}

// Test for exercise 5
#[test]
fn test_reverse_collection_with_strings() {
let mut strings = vec!["apple", "banana", "cherry", "durian"];
reverse_collection(&mut strings);
assert_eq!(strings, vec!["durian", "cherry", "banana", "apple"]);
}

// Test for exercise 5
#[test]
fn test_reverse_collection_with_empty_collection() {
let mut empty: Vec<i32> = Vec::new();
reverse_collection(&mut empty);
assert_eq!(empty, Vec::<i32>::new());
}

// Test for exercise 6
#[test]
fn test_contains_value_with_numbers() {
let numbers = vec![1, 2, 3, 4, 5];
assert_eq!(contains_value(&numbers, &3), true);
assert_eq!(contains_value(&numbers, &6), false);
}

// Test for exercise 6
#[test]
fn test_contains_value_with_strings() {
let strings = vec!["apple", "banana", "cherry", "durian"];
assert_eq!(contains_value(&strings, &"banana"), true);
assert_eq!(contains_value(&strings, &"grape"), false);
}

// Test for exercise 6
#[test]
fn test_contains_value_with_empty_collection() {
let empty: Vec<i32> = Vec::new();
assert_eq!(contains_value(&empty, &5), false);
}

}
8 changes: 8 additions & 0 deletions exercises/traits/Cargo.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
[package]
name = "traits"
version = "0.1.0"
edition = "2021"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]
10 changes: 10 additions & 0 deletions exercises/traits/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
## Complete Trait exercises
### Trait

+ Make it compile and Complete `Traits` exercises in `exercises/traits/src/lib.rs`

+ Run tests to check your implementation

```
cargo test --test traits
```
Loading