diff options
Diffstat (limited to '')
| -rw-r--r-- | Cargo.lock | 32 | ||||
| -rw-r--r-- | Cargo.toml | 7 | ||||
| -rw-r--r-- | libs/hello_macro/Cargo.toml | 6 | ||||
| -rw-r--r-- | libs/hello_macro/hello_macro_derive/Cargo.toml | 11 | ||||
| -rw-r--r-- | libs/hello_macro/hello_macro_derive/src/lib.rs | 24 | ||||
| -rw-r--r-- | libs/hello_macro/src/lib.rs | 3 | ||||
| -rw-r--r-- | src/ext_traits/Cargo.toml | 6 | ||||
| -rw-r--r-- | src/ext_traits/src/main.rs | 14 | ||||
| -rw-r--r-- | src/hello/404.html | 11 | ||||
| -rw-r--r-- | src/hello/Cargo.toml | 6 | ||||
| -rw-r--r-- | src/hello/hello.html | 11 | ||||
| -rw-r--r-- | src/hello/src/lib.rs | 116 | ||||
| -rw-r--r-- | src/hello/src/main.rs | 55 | ||||
| -rw-r--r-- | src/overloading/src/main.rs | 2 | ||||
| -rw-r--r-- | src/pancakes/Cargo.toml | 8 | ||||
| -rw-r--r-- | src/pancakes/src/main.rs | 9 | ||||
| -rw-r--r-- | src/supertraits/Cargo.toml | 6 | ||||
| l--------- | src/supertraits/src/.#main.rs | 1 | ||||
| -rw-r--r-- | src/supertraits/src/main.rs | 42 |
19 files changed, 369 insertions, 1 deletions
@@ -197,6 +197,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12a0bb14ac04a9fcf170d0bbbef949b44cc492f4452bd20c095636956f653642" [[package]] +name = "ext_traits" +version = "0.1.0" + +[[package]] name = "fahr2cel" version = "0.1.0" @@ -390,6 +394,10 @@ name = "hashmaps_01" version = "0.1.0" [[package]] +name = "hello" +version = "0.1.0" + +[[package]] name = "hello-async" version = "0.1.0" dependencies = [ @@ -401,6 +409,18 @@ name = "hello_cargo" version = "0.1.0" [[package]] +name = "hello_macro" +version = "0.1.0" + +[[package]] +name = "hello_macro_derive" +version = "0.1.0" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] name = "hello_world" version = "0.1.0" @@ -757,6 +777,14 @@ name = "overloading" version = "0.1.0" [[package]] +name = "pancakes" +version = "0.1.0" +dependencies = [ + "hello_macro", + "hello_macro_derive", +] + +[[package]] name = "panic" version = "0.1.0" @@ -1378,6 +1406,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" [[package]] +name = "supertraits" +version = "0.1.0" + +[[package]] name = "syn" version = "2.0.119" source = "registry+https://github.com/rust-lang/crates.io-index" @@ -31,8 +31,15 @@ members = [ "src/oop", "src/blog", "src/overloading", + "src/supertraits", + "src/ext_traits", + "src/pancakes", + "src/hello", "libs/restaurant", "libs/adder", + "libs/hello_macro", + "libs/hello_macro/hello_macro_derive", ] + resolver = "2" diff --git a/libs/hello_macro/Cargo.toml b/libs/hello_macro/Cargo.toml new file mode 100644 index 0000000..aaaf3bf --- /dev/null +++ b/libs/hello_macro/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "hello_macro" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/libs/hello_macro/hello_macro_derive/Cargo.toml b/libs/hello_macro/hello_macro_derive/Cargo.toml new file mode 100644 index 0000000..18f0d3f --- /dev/null +++ b/libs/hello_macro/hello_macro_derive/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "hello_macro_derive" +version = "0.1.0" +edition = "2024" + +[lib] +proc-macro = true + +[dependencies] +syn = "2.0" +quote = "1.0"
\ No newline at end of file diff --git a/libs/hello_macro/hello_macro_derive/src/lib.rs b/libs/hello_macro/hello_macro_derive/src/lib.rs new file mode 100644 index 0000000..1eaef1f --- /dev/null +++ b/libs/hello_macro/hello_macro_derive/src/lib.rs @@ -0,0 +1,24 @@ +use proc_macro::TokenStream; +use quote::quote; + +#[proc_macro_derive(HelloMacro)] +pub fn hello_macro_derive(input: TokenStream) -> TokenStream { + // Construct a representation of Rust code as a syntax tree + // that we can manipulate. + let ast = syn::parse(input).unwrap(); + + // Build the trait implementation + impl_hello_macro(&ast) +} + +fn impl_hello_macro(ast: &syn::DeriveInput) -> TokenStream { + let name = &ast.ident; + let generated = quote! { + impl HelloMacro for #name { + fn hello_macro() { + println!("Hello, Macro! My name is {}!", stringify!(#name)); + } + } + }; + generated.into() +} diff --git a/libs/hello_macro/src/lib.rs b/libs/hello_macro/src/lib.rs new file mode 100644 index 0000000..e747931 --- /dev/null +++ b/libs/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/src/ext_traits/Cargo.toml b/src/ext_traits/Cargo.toml new file mode 100644 index 0000000..49354b6 --- /dev/null +++ b/src/ext_traits/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "ext_traits" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/ext_traits/src/main.rs b/src/ext_traits/src/main.rs new file mode 100644 index 0000000..f5d8886 --- /dev/null +++ b/src/ext_traits/src/main.rs @@ -0,0 +1,14 @@ +use std::fmt; + +struct Wrapper(Vec<String>); + +impl fmt::Display for Wrapper { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "[{}]", self.0.join(", ")) + } +} + +fn main() { + let w = Wrapper(vec![String::from("hello"), String::from("world")]); + println!("w = {w}"); +} 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(); +} diff --git a/src/overloading/src/main.rs b/src/overloading/src/main.rs index c30502f..a2f250c 100644 --- a/src/overloading/src/main.rs +++ b/src/overloading/src/main.rs @@ -1,4 +1,4 @@ -use std::ops::Add; +use std::{fmt::Debug, ops::Add}; #[derive( Debug, diff --git a/src/pancakes/Cargo.toml b/src/pancakes/Cargo.toml new file mode 100644 index 0000000..e4edd51 --- /dev/null +++ b/src/pancakes/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "pancakes" +version = "0.1.0" +edition = "2024" + +[dependencies] +hello_macro = { path = "../../libs/hello_macro" } +hello_macro_derive = { path = "../../libs/hello_macro/hello_macro_derive" }
\ No newline at end of file diff --git a/src/pancakes/src/main.rs b/src/pancakes/src/main.rs new file mode 100644 index 0000000..468c30a --- /dev/null +++ b/src/pancakes/src/main.rs @@ -0,0 +1,9 @@ +use hello_macro::HelloMacro; +use hello_macro_derive::HelloMacro; + +#[derive(HelloMacro)] +struct Pancakes; + +fn main() { + Pancakes::hello_macro(); +} diff --git a/src/supertraits/Cargo.toml b/src/supertraits/Cargo.toml new file mode 100644 index 0000000..3c073ab --- /dev/null +++ b/src/supertraits/Cargo.toml @@ -0,0 +1,6 @@ +[package] +name = "supertraits" +version = "0.1.0" +edition = "2024" + +[dependencies] diff --git a/src/supertraits/src/.#main.rs b/src/supertraits/src/.#main.rs new file mode 120000 index 0000000..e886a79 --- /dev/null +++ b/src/supertraits/src/.#main.rs @@ -0,0 +1 @@ +hybrid@polar.514225:1793336784
\ No newline at end of file diff --git a/src/supertraits/src/main.rs b/src/supertraits/src/main.rs new file mode 100644 index 0000000..3053c5a --- /dev/null +++ b/src/supertraits/src/main.rs @@ -0,0 +1,42 @@ +use std::fmt; + +trait OutlinePrint: fmt::Display { + fn outline_print(&self) { + let output = self.to_string(); + let len = output.len(); + + println!("{}", "*".repeat(len + 4)); + println!("*{}*", " ".repeat(len + 2)); + println!("* {output} *"); + println!("*{}*", " ".repeat(len + 2)); + println!("{}", "*".repeat(len + 4)); + } +} + +struct Point { + x: i32, + y: i32, +} + +impl Point { + fn new() -> Point { + Point { + x: 0, + y: 0, + } + } +} + +impl fmt::Display for Point { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + write!(f, "({}, {})" , self.x, self.y) + } +} + +impl OutlinePrint for Point {} + +fn main() { + let point = Point::new(); + + OutlinePrint::outline_print(&point); +} |
