summaryrefslogtreecommitdiffstats
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/ext_traits/Cargo.toml6
-rw-r--r--src/ext_traits/src/main.rs14
-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
-rw-r--r--src/overloading/src/main.rs2
-rw-r--r--src/pancakes/Cargo.toml8
-rw-r--r--src/pancakes/src/main.rs9
-rw-r--r--src/supertraits/Cargo.toml6
l---------src/supertraits/src/.#main.rs1
-rw-r--r--src/supertraits/src/main.rs42
13 files changed, 286 insertions, 1 deletions
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);
+}