From 62dcfb1d9f95503f8eb8be1b29fa1d75bfcc27e2 Mon Sep 17 00:00:00 2001 From: hybrid Date: Sat, 31 Oct 2026 03:54:43 +0300 Subject: add: 7 craits smartpointers interior_mutability threads mutex hello-async async_concurrency multi_futures --- src/async_concurrency/Cargo.toml | 7 +++ src/async_concurrency/src/main.rs | 104 ++++++++++++++++++++++++++++++++++++ src/closures/Cargo.toml | 6 +++ src/closures/src/main.rs | 34 ++++++++++++ src/hello-async/Cargo.toml | 7 +++ src/hello-async/src/main.rs | 31 +++++++++++ src/interior_mutability/Cargo.toml | 6 +++ src/interior_mutability/src/lib.rs | 72 +++++++++++++++++++++++++ src/interior_mutability/src/main.rs | 73 +++++++++++++++++++++++++ src/minigrep/src/lib.rs | 45 ++++++++-------- src/minigrep/src/main.rs | 25 +++++---- src/multi_futures/Cargo.toml | 7 +++ src/multi_futures/src/main.rs | 61 +++++++++++++++++++++ src/mutex/Cargo.toml | 6 +++ src/mutex/src/main.rs | 32 +++++++++++ src/panic/src/main.rs | 2 +- src/shirt-company/Cargo.toml | 6 +++ src/shirt-company/src/main.rs | 52 ++++++++++++++++++ src/smartpointers/Cargo.toml | 6 +++ src/smartpointers/src/main.rs | 16 ++++++ src/threads/Cargo.toml | 6 +++ src/threads/src/main.rs | 93 ++++++++++++++++++++++++++++++++ 22 files changed, 664 insertions(+), 33 deletions(-) create mode 100644 src/async_concurrency/Cargo.toml create mode 100644 src/async_concurrency/src/main.rs create mode 100644 src/closures/Cargo.toml create mode 100644 src/closures/src/main.rs create mode 100644 src/hello-async/Cargo.toml create mode 100644 src/hello-async/src/main.rs create mode 100644 src/interior_mutability/Cargo.toml create mode 100644 src/interior_mutability/src/lib.rs create mode 100644 src/interior_mutability/src/main.rs create mode 100644 src/multi_futures/Cargo.toml create mode 100644 src/multi_futures/src/main.rs create mode 100644 src/mutex/Cargo.toml create mode 100644 src/mutex/src/main.rs create mode 100644 src/shirt-company/Cargo.toml create mode 100644 src/shirt-company/src/main.rs create mode 100644 src/smartpointers/Cargo.toml create mode 100644 src/smartpointers/src/main.rs create mode 100644 src/threads/Cargo.toml create mode 100644 src/threads/src/main.rs (limited to 'src') diff --git a/src/async_concurrency/Cargo.toml b/src/async_concurrency/Cargo.toml new file mode 100644 index 0000000..22ffac4 --- /dev/null +++ b/src/async_concurrency/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "async_concurrency" +version = "0.1.0" +edition = "2024" + +[dependencies] +trpl = "0.3.0" diff --git a/src/async_concurrency/src/main.rs b/src/async_concurrency/src/main.rs new file mode 100644 index 0000000..0feadc5 --- /dev/null +++ b/src/async_concurrency/src/main.rs @@ -0,0 +1,104 @@ +use std::time::Duration; +use trpl; + +fn main() { + trpl::block_on(async { + let handle = trpl::spawn_task(async { + for i in 1..10 { + println!("hi number {i} from the first task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }); + + for i in 1..5 { + println!("hi number {i} from the second task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + + handle.await.unwrap(); + + let fut1 = async { + for i in 1..10 { + println!("hi number {i} from the third task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }.await; + + let fut2 = async { + for i in 1..5 { + println!("hi number {i} from the fourth task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }.await; + + let fut3 = async { + for i in 1..5 { + println!("hi number {i} from the fifth task!"); + trpl::sleep(Duration::from_millis(500)).await; + } + }.await; + + let (tx, mut rx) = trpl::channel(); + + let tx_fut = async move { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("future"), + ]; + + for val in vals { + tx.send(val).unwrap(); + trpl::sleep(Duration::from_millis(500)).await; + } + }; + + let rx_fut = async { + while let Some(value) = rx.recv().await { + println!("received '{value}'"); + } + }; + + trpl::join(tx_fut, rx_fut).await; + + let (tx, mut rx) = trpl::channel(); + + let tx1 = tx.clone(); + let tx1_fut = async move { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("future"), + ]; + + for val in vals { + tx1.send(val).unwrap(); + trpl::sleep(Duration::from_millis(500)).await; + } + }; + + let rx_fut = async { + while let Some(value) = rx.recv().await { + println!("received '{value}'"); + } + }; + + let tx_fut = async move { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + trpl::sleep(Duration::from_millis(1500)).await; + } + }; + + trpl::join!(tx1_fut, tx_fut, rx_fut); + }); +} diff --git a/src/closures/Cargo.toml b/src/closures/Cargo.toml new file mode 100644 index 0000000..a48c2e4 --- /dev/null +++ b/src/closures/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "closures" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/closures/src/main.rs b/src/closures/src/main.rs new file mode 100644 index 0000000..c16cf8b --- /dev/null +++ b/src/closures/src/main.rs @@ -0,0 +1,34 @@ +use std::thread; + +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +fn main() { + let mut list_1 = vec![1, 2, 3]; + println!("[list_1] Before defining closure: {list_1:?}"); + + let mut borrows_mutably = || list_1.push(7); + + borrows_mutably(); + + println!("[list_1] After calling closure: {list_1:?}"); + + let list_2 = vec![1, 2, 3]; + println!("[list_2] Before defining closure: {list_2:?}"); + + thread::spawn(move || println!("[list_2] From thread: {list_2:?}")) + .join() + .unwrap(); + + let mut list_3 = [ + Rectangle { width: 10, height: 1 }, + Rectangle { width: 3, height: 5 }, + Rectangle { width: 7, height: 12 }, + ]; + + list_3.sort_by_key(|r| r.width); + println!("{list_3:#?}"); +} diff --git a/src/hello-async/Cargo.toml b/src/hello-async/Cargo.toml new file mode 100644 index 0000000..8c4be20 --- /dev/null +++ b/src/hello-async/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello-async" +version = "0.1.0" +edition = "2024" + +[dependencies] +trpl = "0.3.0" diff --git a/src/hello-async/src/main.rs b/src/hello-async/src/main.rs new file mode 100644 index 0000000..9d8a343 --- /dev/null +++ b/src/hello-async/src/main.rs @@ -0,0 +1,31 @@ +use std::env; +use trpl::{Either, Html}; + +fn main() { + let args: Vec = env::args().collect(); + + trpl::block_on(async { + let title_fut_1 = page_title(&args[1]); + let title_fut_2 = page_title(&args[2]); + + let (url, maybe_title) = + match trpl::select(title_fut_1, title_fut_2).await { + Either::Left(left) => left, + Either::Right(right) => right, + }; + + println!("{url} returned first"); + match maybe_title { + Some(title) => println!("Its page title was: '{title}'"), + None => println!("It had no title"), + } + }) +} + +async fn page_title(url: &str) -> (&str, Option) { + let response_text = trpl::get(url).await.text().await; + let title = Html::parse(&response_text) + .select_first("title") + .map(|title| title.inner_html()); + (url, title) +} diff --git a/src/interior_mutability/Cargo.toml b/src/interior_mutability/Cargo.toml new file mode 100644 index 0000000..5167438 --- /dev/null +++ b/src/interior_mutability/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "interior_mutability" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/interior_mutability/src/lib.rs b/src/interior_mutability/src/lib.rs new file mode 100644 index 0000000..c854bb1 --- /dev/null +++ b/src/interior_mutability/src/lib.rs @@ -0,0 +1,72 @@ +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> +where + T: Messenger, +{ + pub fn new(messenger: &'a T, max: usize) -> LimitTracker<'a, T> { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("Error: You are over your quota!"); + } else if percentage_of_max >= 0.9 { + self.messenger + .send("Urgent warning: You've used up over 90% of your quota!"); + } else if percentage_of_max >= 0.75 { + self.messenger + .send("Warning: You've used up over 75% of your quota!"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { + sent_messages: RefCell::new(vec![]), + } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.borrow_mut().push(String::from(message)); + } + } + + #[test] + fn it_sends_an_over_75_percent_warning_message() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} diff --git a/src/interior_mutability/src/main.rs b/src/interior_mutability/src/main.rs new file mode 100644 index 0000000..019a4ac --- /dev/null +++ b/src/interior_mutability/src/main.rs @@ -0,0 +1,73 @@ +use crate::List::{Cons, Nil}; +use std::cell::RefCell; +use std::rc::{Rc, Weak}; + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell>, + children: RefCell>>, +} + +#[derive(Debug)] +enum List { + Cons(Rc>, Rc), + Nil, +} + +fn main() { + let value = Rc::new(RefCell::new(5)); + + let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); + + let b = Cons(Rc::new(RefCell::new(3)), Rc::clone(&a)); + let c = Cons(Rc::new(RefCell::new(4)), Rc::clone(&a)); + + *value.borrow_mut() += 10; + + println!("a after = {a:?}"); + println!("b after = {b:?}"); + println!("c after = {c:?}"); + + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + + { + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + } + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); +} diff --git a/src/minigrep/src/lib.rs b/src/minigrep/src/lib.rs index 064cf7a..a2bf5ce 100644 --- a/src/minigrep/src/lib.rs +++ b/src/minigrep/src/lib.rs @@ -1,29 +1,24 @@ -pub fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { - let mut results = Vec::new(); - - for line in contents.lines() { - if line.contains(query) { - results.push(line); - } - } - - results +pub fn search<'a>( + query: &str, + contents: &'a str +) -> impl Iterator +{ + contents + .lines() + .filter(move |line| line.contains(query)) } pub fn search_case_insensitive<'a>( query: &str, contents: &'a str, -) -> Vec<&'a str> { - let query = query.to_lowercase(); - let mut results = Vec::new(); - - for line in contents.lines() { - if line.to_lowercase().contains(&query) { - results.push(line); - } - } - - results +) -> impl Iterator { + contents + .lines() + .filter( + |line| line + .to_lowercase() + .contains(&query.to_lowercase()) + ) } #[cfg(test)] @@ -39,7 +34,9 @@ safe, fast, productive. Pick three. Duct tape."; - assert_eq!(vec!["safe, fast, productive."], search(query, contents)); + let test = search(query, contents).collect::>(); + + assert_eq!(vec!["safe, fast, productive."], test); } #[test] @@ -51,9 +48,11 @@ safe, fast, productive. Pick three. Trust me."; + let test = search_case_insensitive(query, contents).collect::>(); + assert_eq!( vec!["Rust:", "Trust me."], - search_case_insensitive(query, contents) + test ); } } diff --git a/src/minigrep/src/main.rs b/src/minigrep/src/main.rs index 0e36bc6..0d0a16c 100644 --- a/src/minigrep/src/main.rs +++ b/src/minigrep/src/main.rs @@ -4,9 +4,7 @@ use std::error::Error; use minigrep::{search, search_case_insensitive}; fn main() { - let args: Vec = env::args().collect(); - - let config = Config::build(&args).unwrap_or_else(|err| { + let config = Config::build(env::args()).unwrap_or_else(|err| { eprintln!("Problem parsing arguments: {err}"); process::exit(1); }); @@ -26,8 +24,10 @@ fn run(config: Config) -> Result<(), Box> { let results = if config.ignore_case { search_case_insensitive(&config.query, &contents) + .collect::>() } else { search(&config.query, &contents) + .collect::>() }; for line in results { @@ -44,13 +44,20 @@ struct Config{ } impl Config { - fn build(args: &[String]) -> Result { - if args.len() < 3 { - return Err("not enough arguments"); - } + fn build( + mut args: impl Iterator, + ) -> Result { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; - let query = args[1].clone(); - let file_path = args[2].clone(); + let file_path = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a file path"), + }; let ignore_case = env::var("IGNORE_CASE").is_ok(); diff --git a/src/multi_futures/Cargo.toml b/src/multi_futures/Cargo.toml new file mode 100644 index 0000000..c8d3a70 --- /dev/null +++ b/src/multi_futures/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "multi_futures" +version = "0.1.0" +edition = "2024" + +[dependencies] +trpl = "0.3.0" diff --git a/src/multi_futures/src/main.rs b/src/multi_futures/src/main.rs new file mode 100644 index 0000000..918e341 --- /dev/null +++ b/src/multi_futures/src/main.rs @@ -0,0 +1,61 @@ +use std::{thread, time::Duration}; +use trpl::{self, Either}; + +fn main() { + trpl::block_on(async{ + let a = async { + println!("'a' started."); + slow("a", 30); + trpl::yield_now().await; + slow("a", 10); + trpl::yield_now().await; + slow("a", 20); + trpl::yield_now().await; + trpl::sleep(Duration::from_millis(50)).await; + println!("'a' finished."); + }; + + let b = async { + println!("'b' started."); + slow("b", 75); + trpl::yield_now().await; + slow("b", 10); + trpl::yield_now().await; + slow("b", 15); + trpl::yield_now().await; + slow("b", 350); + trpl::yield_now().await; + trpl::sleep(Duration::from_millis(50)).await; + println!("'b' finished."); + }; + + trpl::select(a, b).await; + + let slow = async { + trpl::sleep(Duration::from_secs(2)).await; + "Finally finished" + }; + + match timeout(slow, Duration::from_secs(5)).await { + Ok(message) => println!("Succeeded with '{message}'"), + Err(duration) => { + println!("Failed after {} seconds", duration.as_secs()) + } + } + }); +} + +fn slow(name: &str, ms: u64) { + thread::sleep(Duration::from_millis(ms)); + println!("'{name}' ran for {ms}ms"); +} + +async fn timeout( + future_to_try: F, + max_time: Duration, +) -> Result { + match trpl::select(future_to_try, trpl::sleep(max_time)).await { + Either::Left(output) => Ok(output), + Either::Right(_) => Err(max_time), + } +} diff --git a/src/mutex/Cargo.toml b/src/mutex/Cargo.toml new file mode 100644 index 0000000..c2b8701 --- /dev/null +++ b/src/mutex/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "mutex" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/mutex/src/main.rs b/src/mutex/src/main.rs new file mode 100644 index 0000000..d09c789 --- /dev/null +++ b/src/mutex/src/main.rs @@ -0,0 +1,32 @@ +use std::sync::{Arc, Mutex}; +use std::thread; + +fn main() { + let m = Mutex::new(5); + + { + let mut num = m.lock().unwrap(); + *num = 6; + } + + println!("m = {m:?}"); + + let counter = Arc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Arc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + println!("Result: {}", *counter.lock().unwrap()); +} diff --git a/src/panic/src/main.rs b/src/panic/src/main.rs index bf8be55..c3e302f 100644 --- a/src/panic/src/main.rs +++ b/src/panic/src/main.rs @@ -3,7 +3,7 @@ struct Test { b: T, } -#![allow(unused)] +#[allow(unused)] fn main() { use std::fs::File; use std::io::{self, Read}; diff --git a/src/shirt-company/Cargo.toml b/src/shirt-company/Cargo.toml new file mode 100644 index 0000000..4f22291 --- /dev/null +++ b/src/shirt-company/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "shirt-company" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/shirt-company/src/main.rs b/src/shirt-company/src/main.rs new file mode 100644 index 0000000..2c87d69 --- /dev/null +++ b/src/shirt-company/src/main.rs @@ -0,0 +1,52 @@ +#[derive(Debug, PartialEq, Copy, Clone)] +enum ShirtColor { + Red, + Blue, +} + +struct Inventory { + shirts: Vec, +} + +impl Inventory { + fn giveaway(&self, user_preference: Option) -> ShirtColor { + user_preference.unwrap_or_else(|| self.most_stocked()) + } + + fn most_stocked(&self) -> ShirtColor { + let mut num_red = 0; + let mut num_blue = 0; + + for color in &self.shirts { + match color { + ShirtColor::Red => num_red += 1, + ShirtColor::Blue => num_blue += 1, + } + } + if num_red > num_blue { + ShirtColor::Red + } else { + ShirtColor::Blue + } + } +} + +fn main() { + let store = Inventory { + shirts: vec![ShirtColor::Blue, ShirtColor::Red, ShirtColor::Blue], + }; + + let user_pref1 = Some(ShirtColor::Red); + let giveaway1 = store.giveaway(user_pref1); + println!( + "The user with preference {:?} gets {:?}", + user_pref1, giveaway1 + ); + + let user_pref2 = None; + let giveaway2 = store.giveaway(user_pref2); + println!( + "The user with preference {:?} gets {:?}", + user_pref2, giveaway2 + ); +} diff --git a/src/smartpointers/Cargo.toml b/src/smartpointers/Cargo.toml new file mode 100644 index 0000000..2a65854 --- /dev/null +++ b/src/smartpointers/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "smartpointers" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/smartpointers/src/main.rs b/src/smartpointers/src/main.rs new file mode 100644 index 0000000..594c5c1 --- /dev/null +++ b/src/smartpointers/src/main.rs @@ -0,0 +1,16 @@ +enum List { + Cons(i32, Rc), + Nil, +} + +use crate::List::{Cons, Nil}; +use std::rc::Rc; + +fn main() { + let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); + println!("a have {} references", Rc::strong_count(&a)); + let b = Cons(3, Rc::clone(&a)); + println!("a have {} references", Rc::strong_count(&a)); + let c = Cons(4, Rc::clone(&a)); + println!("a have {} references", Rc::strong_count(&a)); +} diff --git a/src/threads/Cargo.toml b/src/threads/Cargo.toml new file mode 100644 index 0000000..f210198 --- /dev/null +++ b/src/threads/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "threads" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/threads/src/main.rs b/src/threads/src/main.rs new file mode 100644 index 0000000..18b2645 --- /dev/null +++ b/src/threads/src/main.rs @@ -0,0 +1,93 @@ +use std::thread; +use std::time::Duration; + +use std::sync::mpsc; + +fn main() { + let handle = thread::spawn(|| { + for i in 1..10 { + println!("hi number {i} from the spawned thread!"); + thread::sleep(Duration::from_millis(1)); + } + }); + + for i in 1..5 { + println!("hi number {i} from the main thread!"); + thread::sleep(Duration::from_millis(1)); + } + + handle.join().unwrap(); + + let v = vec![1, 2, 3]; + + let handle_vec = thread::spawn(move || { + println!("Here's a vector: {v:?}"); + }); + + handle_vec.join().unwrap(); + + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let val = String::from("hi"); + tx.send(val).unwrap(); + }); + + let received = rx.recv().unwrap(); + println!("Got: {received}"); + + let (tx, rx) = mpsc::channel(); + + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {received}"); + } + + let (tx, rx) = mpsc::channel(); + + let tx1 = tx.clone(); + thread::spawn(move || { + let vals = vec![ + String::from("hi"), + String::from("from"), + String::from("the"), + String::from("thread"), + ]; + + for val in vals { + tx1.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + thread::spawn(move || { + let vals = vec![ + String::from("more"), + String::from("messages"), + String::from("for"), + String::from("you"), + ]; + + for val in vals { + tx.send(val).unwrap(); + thread::sleep(Duration::from_secs(1)); + } + }); + + for received in rx { + println!("Got: {received}"); + } +} -- cgit v1.3.1