From 9dea46b5e66eb54746b251d8950b2367c49be23d Mon Sep 17 00:00:00 2001 From: hybrid Date: Wed, 11 Nov 2026 17:16:48 +0300 Subject: add: supertraits, ext_traits, pancakes, hello, hello_macro --- src/hello/404.html | 11 +++++ src/hello/Cargo.toml | 6 +++ src/hello/hello.html | 11 +++++ src/hello/src/lib.rs | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++ src/hello/src/main.rs | 55 ++++++++++++++++++++++++ 5 files changed, 199 insertions(+) create mode 100644 src/hello/404.html create mode 100644 src/hello/Cargo.toml create mode 100644 src/hello/hello.html create mode 100644 src/hello/src/lib.rs create mode 100644 src/hello/src/main.rs (limited to 'src/hello') diff --git a/src/hello/404.html b/src/hello/404.html new file mode 100644 index 0000000..0ace400 --- /dev/null +++ b/src/hello/404.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Ooops!

+

ГАСПАНЦЫ украли эту страницу!

+ + diff --git a/src/hello/Cargo.toml b/src/hello/Cargo.toml new file mode 100644 index 0000000..f6f3649 --- /dev/null +++ b/src/hello/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "hello" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/hello/hello.html b/src/hello/hello.html new file mode 100644 index 0000000..c4f7386 --- /dev/null +++ b/src/hello/hello.html @@ -0,0 +1,11 @@ + + + + + Hello! + + +

Hello!

+

Hi from Rust

+ + diff --git a/src/hello/src/lib.rs b/src/hello/src/lib.rs new file mode 100644 index 0000000..3e58638 --- /dev/null +++ b/src/hello/src/lib.rs @@ -0,0 +1,116 @@ +use std::{ + thread, + sync::{mpsc, Arc, Mutex}, +}; + +#[derive(Debug)] +pub enum PoolCreationError { + ZeroThreads, +} + +pub struct ThreadPool { + workers: Vec, + sender: Option>, +} + +type Job = Box; + +impl ThreadPool { + /// Create a new ThreadPool. + /// + /// The size is the number of threads in the pool. + /// + /// # Panics + /// + /// The 'new' function will panic if the size is zero. + pub fn new(size: usize) -> ThreadPool { + assert!(size > 0); + + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + ThreadPool { + workers, + sender: Some(sender), + } + } + + pub fn build(size: usize) -> Result { + match size { + 0 => Err(PoolCreationError::ZeroThreads), + _ => { + let (sender, receiver) = mpsc::channel(); + + let receiver = Arc::new(Mutex::new(receiver)); + + let mut workers = Vec::with_capacity(size); + + for id in 0..size { + workers.push(Worker::new(id, Arc::clone(&receiver))); + } + + Ok(ThreadPool { workers, sender: Some(sender) }) + } + } + } + + pub fn execute(&self, f: F) + where + F: FnOnce() + Send + 'static, + { + let job = Box::new(f); + + self.sender.as_ref().unwrap().send(job).unwrap(); + } +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + drop(self.sender.take()); + + for worker in self.workers.drain(..) { + println!("Shutting down worker {}", worker.id); + + worker.thread.join().unwrap(); + } + } +} + +struct Worker { + id: usize, + thread: thread::JoinHandle<()>, +} + +impl Worker { + pub fn new( + id: usize, + receiver: Arc>>) + -> Worker { + let thread = thread::spawn(move || { + loop { + let message = receiver.lock().unwrap().recv(); + + match message { + Ok(job) => { + println!("Worker {id} got a job; executing."); + + job(); + } + Err(_) => { + println!("Worker {id} disconnected; shutting down."); + break; + } + } + } + }); + + Worker { id, thread } + } +} diff --git a/src/hello/src/main.rs b/src/hello/src/main.rs new file mode 100644 index 0000000..09fc5a0 --- /dev/null +++ b/src/hello/src/main.rs @@ -0,0 +1,55 @@ +use std::{ + fs, + net::{TcpListener, TcpStream}, + io::{BufReader, prelude::*}, + thread, + time::Duration, +}; +use hello::ThreadPool; + +fn main() { + let listener = TcpListener::bind("127.0.0.1:7878").unwrap(); + let pool = ThreadPool::build(4) + .expect("Might be 0 threads specified. Try more"); + + for stream in listener.incoming().take(2) { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + + println!("Shutting down."); +} + +fn handle_connection(mut stream: TcpStream) { + let buf_reader = BufReader::new(&stream); + let request_line = buf_reader.lines().next().unwrap().unwrap(); + + let (status_line, filename) = match &request_line[..]{ + "GET / HTTP/1.1" => { + ("HTTP/1.1 200 OK", "/mnt/hdd2tb/git/rust-book/src/hello/hello.html") + } + "GET /sleep HTTP/1.1" => { + thread::sleep(Duration::from_secs(5)); + ("HTTP/1.1 200 OK", "/mnt/hdd2tb/git/rust-book/src/hello/hello.html") + } + _ => ("HTTP/1.1 400 NOT FOUND", "/mnt/hdd2tb/git/rust-book/src/hello/404.html") + }; + + let contents = fs::read_to_string(filename).unwrap(); + let length = contents.len(); + + let response = format!( + "{status_line}\r\nContent-Length: {length}\r\n\r\n{contents}" + ); + + stream.write_all(response.as_bytes()).unwrap(); + + // let http_request: Vec<_> = buf_reader + // .lines() + // .map(|result| result.unwrap()) + // .take_while(|line| !line.is_empty()) + // .collect(); +} -- cgit v1.3.1