summaryrefslogtreecommitdiffstats
path: root/src/hello
diff options
context:
space:
mode:
authorhybrid <hybrid@hybridlabs.cc>2026-11-11 17:16:48 +0300
committerhybrid <hybrid@hybridlabs.cc>2026-11-11 17:16:48 +0300
commit9dea46b5e66eb54746b251d8950b2367c49be23d (patch)
treefdebf3880f2f25a1351a220e771da84ea32f07e2 /src/hello
parent59e457f7d6267ac2591837085b388d7c15ed2004 (diff)
downloadrust-book-main.tar.gz
rust-book-main.tar.bz2
rust-book-main.zip
add: supertraits, ext_traits, pancakes, hello, hello_macromain
Diffstat (limited to '')
-rw-r--r--src/hello/404.html11
-rw-r--r--src/hello/Cargo.toml6
-rw-r--r--src/hello/hello.html11
-rw-r--r--src/hello/src/lib.rs116
-rw-r--r--src/hello/src/main.rs55
5 files changed, 199 insertions, 0 deletions
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 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>Hello!</title>
+ </head>
+ <body>
+ <h1>Ooops!</h1>
+ <p>ГАСПАНЦЫ украли эту страницу!</p>
+ </body>
+</html>
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 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>Hello!</title>
+ </head>
+ <body>
+ <h1>Hello!</h1>
+ <p>Hi from Rust</p>
+ </body>
+</html>
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<Worker>,
+ sender: Option<mpsc::Sender<Job>>,
+}
+
+type Job = Box<dyn FnOnce() + Send + 'static>;
+
+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<ThreadPool, PoolCreationError> {
+ 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<F>(&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<Mutex<mpsc::Receiver<Job>>>)
+ -> 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();
+}