summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
authorAdam Carpenter <53hornet@gmail.com>2019-03-26 15:05:10 -0400
committerAdam Carpenter <53hornet@gmail.com>2019-03-26 15:05:10 -0400
commit5718a0b54869b341bc74416bf82b716aa15d582c (patch)
tree0a1ab65ecc854733c15011f364524bde8379ae1b
parent29db8e4c4182877e5e723e26e2c5ae11e9383520 (diff)
downloadlearning-rust-5718a0b54869b341bc74416bf82b716aa15d582c.tar.xz
learning-rust-5718a0b54869b341bc74416bf82b716aa15d582c.zip
Finished web server project. Book done!
-rw-r--r--advanced/adv-fn-closure/Cargo.lock7
-rw-r--r--advanced/adv-fn-closure/Cargo.toml1
-rw-r--r--advanced/adv-fn-closure/src/main.rs82
-rw-r--r--advanced/hello_macro/Cargo.toml7
-rw-r--r--advanced/hello_macro/src/lib.rs3
-rw-r--r--hello_server/404.html19
-rw-r--r--hello_server/Cargo.lock4
-rw-r--r--hello_server/Cargo.toml7
-rw-r--r--hello_server/hello.html18
-rw-r--r--hello_server/src/bin/main.rs44
-rw-r--r--hello_server/src/lib.rs88
11 files changed, 272 insertions, 8 deletions
diff --git a/advanced/adv-fn-closure/Cargo.lock b/advanced/adv-fn-closure/Cargo.lock
index cfa8ec5..360607c 100644
--- a/advanced/adv-fn-closure/Cargo.lock
+++ b/advanced/adv-fn-closure/Cargo.lock
@@ -1,4 +1,11 @@
[[package]]
name = "adv-fn-closure"
version = "0.1.0"
+dependencies = [
+ "hello_macro 0.1.0",
+]
+
+[[package]]
+name = "hello_macro"
+version = "0.1.0"
diff --git a/advanced/adv-fn-closure/Cargo.toml b/advanced/adv-fn-closure/Cargo.toml
index 259562e..6cd8dbd 100644
--- a/advanced/adv-fn-closure/Cargo.toml
+++ b/advanced/adv-fn-closure/Cargo.toml
@@ -5,3 +5,4 @@ authors = ["Adam Carpenter <53hornet@gmail.com>"]
edition = "2018"
[dependencies]
+hello_macro = { path = "../hello_macro" }
diff --git a/advanced/adv-fn-closure/src/main.rs b/advanced/adv-fn-closure/src/main.rs
index d31bd90..064f300 100644
--- a/advanced/adv-fn-closure/src/main.rs
+++ b/advanced/adv-fn-closure/src/main.rs
@@ -1,13 +1,79 @@
-fn add_one(x: i32) -> i32 {
- x + 1
-}
+use hello_macro::HelloMacro;
+//use hello_macro_derive::HelloMacro;
+
+struct Pancakes;
-fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
- f(arg) + f(arg)
+impl HelloMacro for Pancakes {
+ fn hello_macro() {
+ println!("pancakes");
+ }
}
fn main() {
- let answer = do_twice(add_one, 5);
-
- println!("{}", answer);
+ Pancakes::hello_macro();
}
+
+//fn add_one(x: i32) -> i32 {
+// x + 1
+//}
+//
+//fn do_twice(f: fn(i32) -> i32, arg: i32) -> i32 {
+// f(arg) + f(arg)
+//}
+
+
+//fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
+// Box::new(|x| x + 1)
+//}
+//
+//
+//enum Status {
+// Value(u32),
+// Stop,
+//}
+
+
+//#[macro_export]
+//macro_rules! vec {
+// ( $( $x:expr ), * ) => {
+// {
+// let mut temp_vec = Vec::new();
+// $(
+// temp_vec.push($x);
+// )*
+// temp_vec
+// }
+// };
+//}
+
+
+//#[some_attribute]
+//pub fn some_name(input: TokenStream) -> TokenStream {
+//}
+//
+//
+//fn main() {
+// let answer = do_twice(add_one, 5);
+//
+// println!("{}", answer);
+
+
+// let list_of_numbers = vec![1, 2, 3];
+// let list_of_strings: Vec<String> = list_of_numbers
+// .iter()
+// .map(ToString::to_string)
+// .collect();
+// dbg!(list_of_strings);
+
+
+// let list_of_statuses: Vec<Status> =
+// (0u32..20)
+// .map(Status::Value)
+// .collect();
+
+
+ //returns_closure();
+
+
+
+//}
diff --git a/advanced/hello_macro/Cargo.toml b/advanced/hello_macro/Cargo.toml
new file mode 100644
index 0000000..e812230
--- /dev/null
+++ b/advanced/hello_macro/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "hello_macro"
+version = "0.1.0"
+authors = ["Adam Carpenter <53hornet@gmail.com>"]
+edition = "2018"
+
+[dependencies]
diff --git a/advanced/hello_macro/src/lib.rs b/advanced/hello_macro/src/lib.rs
new file mode 100644
index 0000000..e747931
--- /dev/null
+++ b/advanced/hello_macro/src/lib.rs
@@ -0,0 +1,3 @@
+pub trait HelloMacro {
+ fn hello_macro();
+}
diff --git a/hello_server/404.html b/hello_server/404.html
new file mode 100644
index 0000000..b106938
--- /dev/null
+++ b/hello_server/404.html
@@ -0,0 +1,19 @@
+
+<!doctype html>
+<html lang="en">
+ <head>
+ <meta charset="utf-8">
+ <title>
+ Hello!
+ </title>
+ </head>
+ <body>
+ <h1>
+ Oops!
+ </h1>
+ <p>
+ Sorry, Idk what you're asking for.
+ </p>
+ </body>
+</html>
+
diff --git a/hello_server/Cargo.lock b/hello_server/Cargo.lock
new file mode 100644
index 0000000..738010c
--- /dev/null
+++ b/hello_server/Cargo.lock
@@ -0,0 +1,4 @@
+[[package]]
+name = "hello_server"
+version = "0.1.0"
+
diff --git a/hello_server/Cargo.toml b/hello_server/Cargo.toml
new file mode 100644
index 0000000..39057cc
--- /dev/null
+++ b/hello_server/Cargo.toml
@@ -0,0 +1,7 @@
+[package]
+name = "hello_server"
+version = "0.1.0"
+authors = ["Adam Carpenter <53hornet@gmail.com>"]
+edition = "2018"
+
+[dependencies]
diff --git a/hello_server/hello.html b/hello_server/hello.html
new file mode 100644
index 0000000..869c8f9
--- /dev/null
+++ b/hello_server/hello.html
@@ -0,0 +1,18 @@
+<!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/hello_server/src/bin/main.rs b/hello_server/src/bin/main.rs
new file mode 100644
index 0000000..522777a
--- /dev/null
+++ b/hello_server/src/bin/main.rs
@@ -0,0 +1,44 @@
+use hello_server::ThreadPool;
+use std::thread;
+use std::time::Duration;
+use std::io::prelude::*;
+use std::fs;
+use std::net::TcpStream;
+use std::net::TcpListener;
+
+fn main() {
+ let listener = TcpListener::bind("127.0.0.1:7878").unwrap();
+ let pool = ThreadPool::new(4).unwrap();
+
+ for stream in listener.incoming() {
+ let stream = stream.unwrap();
+
+ pool.execute(|| {
+ handle_connection(stream);
+ });
+ }
+
+}
+
+fn handle_connection(mut stream: TcpStream) {
+ let mut buffer = [0; 512];
+ stream.read(&mut buffer).unwrap();
+ let get = b"GET / HTTP/1.1\r\n";
+ let sleep = b"GET /sleep HTTP/1.1\r\n";
+
+ let (status_line, filename) = if buffer.starts_with(get) {
+ ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+ }
+ else if buffer.starts_with(sleep) {
+ thread::sleep(Duration::from_secs(5));
+ ("HTTP/1.1 200 OK\r\n\r\n", "hello.html")
+ }
+ else {
+ ("HTTP/1.1 404 NOT FOUND\r\n\r\n", "404.html")
+ };
+
+ let contents = fs::read_to_string(filename).unwrap();
+ let response = format!("{}{}", status_line, contents);
+ stream.write(response.as_bytes()).unwrap();
+ stream.flush().unwrap();
+}
diff --git a/hello_server/src/lib.rs b/hello_server/src/lib.rs
new file mode 100644
index 0000000..c8e6a3e
--- /dev/null
+++ b/hello_server/src/lib.rs
@@ -0,0 +1,88 @@
+use std::sync::Arc;
+use std::sync::Mutex;
+use std::sync::mpsc;
+use std::thread;
+
+trait FnBox {
+ fn call_box(self: Box<Self>);
+}
+
+impl <F: FnOnce()> FnBox for F {
+ fn call_box(self: Box<F>) {
+ (*self)()
+ }
+}
+
+type Job = Box<FnBox + Send + 'static>;
+
+pub struct ThreadPool {
+ workers: Vec<Worker>,
+ sender: mpsc::Sender<Job>,
+}
+
+impl ThreadPool {
+ pub fn new(size: usize) -> Result<ThreadPool, &'static str> {
+ if size <= 0 {
+ return Err("failed to create pool");
+ }
+
+ 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,
+ })
+ }
+
+ pub fn spawn<F, T>(f: F) -> thread::JoinHandle<T>
+ where
+ F: FnOnce() -> T + Send + 'static,
+ T: Send + 'static
+ {
+ thread::spawn(f)
+ }
+
+ pub fn execute<F>(&self, f: F)
+ where
+ F: FnOnce() + Send + 'static
+ {
+ let job = Box::new(f);
+ self.sender.send(job).unwrap();
+ }
+
+}
+
+struct Worker {
+ id: usize,
+ thread: thread::JoinHandle<()>,
+}
+
+impl Worker {
+ pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Job>>>)
+ -> Result<Worker, &'static str>
+ {
+ let thread = thread::spawn(move || {
+ loop {
+ let job = receiver
+ .lock().expect("lock poisoned!")
+ .recv().unwrap();
+ println!("worker {} got job; executing...", id);
+
+ job.call_box();
+ }
+ });
+
+ Ok(Worker {
+ id,
+ thread,
+ })
+ }
+}