diff options
author | Adam Carpenter <gitlab@53hor.net> | 2019-07-09 15:14:04 -0400 |
---|---|---|
committer | Adam Carpenter <gitlab@53hor.net> | 2019-07-09 15:14:04 -0400 |
commit | 7e8ee5ed9cad6484e9f13f81731b102ced58402e (patch) | |
tree | 5395402ab07bbb5a659dbd68c701e22a1227202f /rust-book | |
download | learning-rust-7e8ee5ed9cad6484e9f13f81731b102ced58402e.tar.xz learning-rust-7e8ee5ed9cad6484e9f13f81731b102ced58402e.zip |
Init.
Diffstat (limited to 'rust-book')
133 files changed, 3685 insertions, 0 deletions
diff --git a/rust-book/add/Cargo.lock b/rust-book/add/Cargo.lock new file mode 100755 index 0000000..64cb0d1 --- /dev/null +++ b/rust-book/add/Cargo.lock @@ -0,0 +1,11 @@ +[[package]] +name = "add-one" +version = "0.1.0" + +[[package]] +name = "adder" +version = "0.1.0" +dependencies = [ + "add-one 0.1.0", +] + diff --git a/rust-book/add/Cargo.toml b/rust-book/add/Cargo.toml new file mode 100755 index 0000000..37b9688 --- /dev/null +++ b/rust-book/add/Cargo.toml @@ -0,0 +1,7 @@ +[workspace] + +members = [ + "adder", + "add-one", +] + diff --git a/rust-book/add/add-one/Cargo.toml b/rust-book/add/add-one/Cargo.toml new file mode 100755 index 0000000..88d65d1 --- /dev/null +++ b/rust-book/add/add-one/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "add-one" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] +rand = "0.3.14" diff --git a/rust-book/add/add-one/src/lib.rs b/rust-book/add/add-one/src/lib.rs new file mode 100755 index 0000000..fe3583e --- /dev/null +++ b/rust-book/add/add-one/src/lib.rs @@ -0,0 +1,11 @@ +pub fn add_one(x: i32) -> i32 { + x + 1 +} + +#[cfg(test)] +mod tests { + #[test] + fn it_works() { + assert_eq!(2 + 2, 4); + } +} diff --git a/rust-book/add/adder/Cargo.toml b/rust-book/add/adder/Cargo.toml new file mode 100755 index 0000000..1fefcc2 --- /dev/null +++ b/rust-book/add/adder/Cargo.toml @@ -0,0 +1,9 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] +add-one = { path = "../add-one" } + diff --git a/rust-book/add/adder/src/main.rs b/rust-book/add/adder/src/main.rs new file mode 100755 index 0000000..7099fb8 --- /dev/null +++ b/rust-book/add/adder/src/main.rs @@ -0,0 +1,6 @@ +use add_one; + +fn main() { + let num = 10; + println!("{}", add_one::add_one(num)); +} diff --git a/rust-book/adder/Cargo.lock b/rust-book/adder/Cargo.lock new file mode 100755 index 0000000..4fb18f9 --- /dev/null +++ b/rust-book/adder/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "adder" +version = "0.1.0" + diff --git a/rust-book/adder/Cargo.toml b/rust-book/adder/Cargo.toml new file mode 100755 index 0000000..5224ea1 --- /dev/null +++ b/rust-book/adder/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adder" +version = "0.1.0" +authors = ["carpenat"] +edition = "2018" + +[dependencies] diff --git a/rust-book/adder/src/lib.rs b/rust-book/adder/src/lib.rs new file mode 100755 index 0000000..bc79931 --- /dev/null +++ b/rust-book/adder/src/lib.rs @@ -0,0 +1,92 @@ +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn it_works() -> Result<(), String> { + if 2 + 2 == 4 { + Ok(()) + } + else { + Err(String::from("two plus two does not equal four")) + } + } + + #[test] + fn larger_can_hold_smaller() { + let larger = Rectangle { length: 8, width: 7 }; + let smaller = Rectangle { length: 5, width: 1 }; + + assert!(larger.can_hold(&smaller)); + } + + #[test] + fn smaller_cannot_hold_larger() { + let larger = Rectangle { length: 8, width: 7 }; + let smaller = Rectangle { length: 5, width: 1 }; + + assert!(!smaller.can_hold(&larger)); + } + + #[test] + fn it_adds_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn it_wont_add_two() { + assert_ne!(4, add_two(3)); + } + + #[test] + fn greeting_contains_name() { + let result = greeting("adam"); + assert!(result.contains("adam")); + } + + #[test] + #[should_panic(expected = "must be between 1 and 100")] + fn greater_than_100() { + Guess::new(200); + } +} + +#[derive(Debug)] +pub struct Rectangle { + length: u32, + width: u32, +} + +pub struct Guess { + value: i32, +} + +impl Guess { + pub fn new(value: i32) -> Guess { + if value < 1 || value > 100 { + panic!("must be between 1 and 100, not {}", value); + } + //if value < 1 { + // panic!("must be greater than 1, not {}", value); + //} + //else if value > 100 { + // panic!("must be less than 100, not {}", value); + //} + + Guess { value } + } +} + +impl Rectangle { + pub fn can_hold(&self, other: &Rectangle) -> bool { + self.length > other.length && self.width > other.width + } +} + +pub fn add_two(a: i32) -> i32 { + a + 2 +} + +pub fn greeting(name: &str) -> String { + format!("hello {}", name) +} diff --git a/rust-book/advanced/adv-fn-closure/Cargo.lock b/rust-book/advanced/adv-fn-closure/Cargo.lock new file mode 100755 index 0000000..360607c --- /dev/null +++ b/rust-book/advanced/adv-fn-closure/Cargo.lock @@ -0,0 +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/rust-book/advanced/adv-fn-closure/Cargo.toml b/rust-book/advanced/adv-fn-closure/Cargo.toml new file mode 100755 index 0000000..6cd8dbd --- /dev/null +++ b/rust-book/advanced/adv-fn-closure/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "adv-fn-closure" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] +hello_macro = { path = "../hello_macro" } diff --git a/rust-book/advanced/adv-fn-closure/src/main.rs b/rust-book/advanced/adv-fn-closure/src/main.rs new file mode 100755 index 0000000..064f300 --- /dev/null +++ b/rust-book/advanced/adv-fn-closure/src/main.rs @@ -0,0 +1,79 @@ +use hello_macro::HelloMacro; +//use hello_macro_derive::HelloMacro; + +struct Pancakes; + +impl HelloMacro for Pancakes { + fn hello_macro() { + println!("pancakes"); + } +} + +fn main() { + 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/rust-book/advanced/adv-lifetimes/Cargo.lock b/rust-book/advanced/adv-lifetimes/Cargo.lock new file mode 100755 index 0000000..591810c --- /dev/null +++ b/rust-book/advanced/adv-lifetimes/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "adv-lifetimes" +version = "0.1.0" + diff --git a/rust-book/advanced/adv-lifetimes/Cargo.toml b/rust-book/advanced/adv-lifetimes/Cargo.toml new file mode 100755 index 0000000..b127e9f --- /dev/null +++ b/rust-book/advanced/adv-lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adv-lifetimes" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/advanced/adv-lifetimes/src/main.rs b/rust-book/advanced/adv-lifetimes/src/main.rs new file mode 100755 index 0000000..755baf4 --- /dev/null +++ b/rust-book/advanced/adv-lifetimes/src/main.rs @@ -0,0 +1,36 @@ +fn main() { + let num = 5; + + let obj = Box::new(Ball { diameter: &num }) as Box<dyn Red>; +} + +struct Context<'s>(&'s str); + +struct Parser<'c, 's: 'c> { + context: &'c Context<'s>, +} + +impl<'c, 's> Parser<'c, 's> { + fn parse(&self) -> Result<(), &'s str> { + Err(&self.context.0[1..]) + } +} + +fn parse_context(context: Context) -> Result<(), &str> { + Parser { context: &context }.parse() +} + +trait Red { } + +struct Ball<'a> { + diameter: &'a i32, +} + +impl<'a> Red for Ball<'a> { } + +struct StrWrap<'a>(&'a str); + +fn foo(string: &str) -> StrWrap<'_> { + StrWrap(string) +} + diff --git a/rust-book/advanced/adv-traits/Cargo.lock b/rust-book/advanced/adv-traits/Cargo.lock new file mode 100755 index 0000000..4fb1ae5 --- /dev/null +++ b/rust-book/advanced/adv-traits/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "adv-traits" +version = "0.1.0" + diff --git a/rust-book/advanced/adv-traits/Cargo.toml b/rust-book/advanced/adv-traits/Cargo.toml new file mode 100755 index 0000000..b1c5f6a --- /dev/null +++ b/rust-book/advanced/adv-traits/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adv-traits" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/advanced/adv-traits/src/main.rs b/rust-book/advanced/adv-traits/src/main.rs new file mode 100755 index 0000000..659883c --- /dev/null +++ b/rust-book/advanced/adv-traits/src/main.rs @@ -0,0 +1,163 @@ +//fn main() { +// println!("Hello, world!"); +//} +// +//pub trait Iterator { +// type Item; +// +// fn next(&mut self) -> Option<Self::Item>; +//} +// +// +//#[derive(Debug, PartialEq)] +//struct Point { +// x: i32, +// y: i32, +//} +// +//impl Add for Point { +// type Output = Point; +// +// fn add(self, other: Point) -> Point { +// Point { +// x: self.x + other.x, +// y: self.y + other.y, +// } +// } +//} + +//fn main() { +// assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 }, +// Point { x: 3, y: 3 }); +// println!("Done."); +//} + +//trait Add<RHS=Self> { +// type Output; +// +// fn add(self, rhs: RHS) -> Self::Output; +//} + +//use std::ops::Add; +// +//struct Millimeters(u32); +//struct Meters(u32); +// +//impl Add<Meters> for Millimeters { +// type Output = Millimeters; +// +// fn add(self, other: Meters) -> Millimeters { +// Millimeters(self.0 + (other.0 * 1000)) +// } +//} + + +//trait Pilot { +// fn fly(&self); +//} +// +//trait Wizard { +// fn fly(&self); +//} +// +//struct Human; +// +//impl Pilot for Human { +// fn fly(&self) { +// println!("Because I was inverted."); +// } +//} +// +//impl Wizard for Human { +// fn fly(&self) { +// println!("Fly, you fools."); +// } +//} +// +//impl Human { +// fn fly(&self) { +// println!("*feels real loose like a long-neck goose*"); +// } +//} +// +// +//trait Animal { +// fn baby_name() -> String; +//} +// +//struct Dog; +// +//impl Dog { +// fn baby_name() -> String { +// String::from("Spot") +// } +//} +// +//impl Animal for Dog { +// fn baby_name() -> String { +// String::from("puppy") +// } +//} + + +//fn main() { +// let person = Human; +// person.fly(); +// Pilot::fly(&person); +// Wizard::fly(&person); +// +// +// println!("A baby dog is called a {}", <Dog as Animal>::baby_name()); +// +// +// println!("Done."); +//} +// + + +//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 OutlinePrint for Point {} +// +//impl fmt::Display for Point { +// fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { +// write!(f, "({}, {})", self.x, self.y) +// } +//} +// +//fn main() { +// let point = Point { x: 5, y: 6 }; +// point.outline_print(); +//} + +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/rust-book/advanced/adv-types/Cargo.lock b/rust-book/advanced/adv-types/Cargo.lock new file mode 100755 index 0000000..a7ad78b --- /dev/null +++ b/rust-book/advanced/adv-types/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "adv-types" +version = "0.1.0" + diff --git a/rust-book/advanced/adv-types/Cargo.toml b/rust-book/advanced/adv-types/Cargo.toml new file mode 100755 index 0000000..a3ca211 --- /dev/null +++ b/rust-book/advanced/adv-types/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "adv-types" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/advanced/adv-types/src/main.rs b/rust-book/advanced/adv-types/src/main.rs new file mode 100755 index 0000000..60d42b2 --- /dev/null +++ b/rust-book/advanced/adv-types/src/main.rs @@ -0,0 +1,41 @@ +//use std::io::Error; +//use std::fmt; + +//pub trait Write { +// +// fn write(&mut self, buf: &[u8]) -> Result<usize>; +// fn flush(&mut self) -> Result<(), Error>; +// +// fn write_all(&mut self, buf: &[u8]) -> Result<()>; +// fn write_fmt(&mut self, fmt: fmt::Arguments) -> Result<()>; +//} + +//fn main() { +// type Miles = i32; +// +// let x: i32 = 5; +// let y: Miles = 5; +// +// println!("x + y = {}", x + y); + + +//} + +//type Thunk = Box<dyn Fn() + Send + 'static>; +// +//let f: Thunk = Box::new(|| println!("hi")); +// +//fn takes_long_type(f: Thunk) { +//} +// +//fn returns_long_type() -> Thunk { +//} + +fn main() { + print!("forever"); + + loop { + print!("and ever "); + } +} + diff --git a/rust-book/advanced/hello_macro/Cargo.toml b/rust-book/advanced/hello_macro/Cargo.toml new file mode 100755 index 0000000..e812230 --- /dev/null +++ b/rust-book/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/rust-book/advanced/hello_macro/src/lib.rs b/rust-book/advanced/hello_macro/src/lib.rs new file mode 100755 index 0000000..e747931 --- /dev/null +++ b/rust-book/advanced/hello_macro/src/lib.rs @@ -0,0 +1,3 @@ +pub trait HelloMacro { + fn hello_macro(); +} diff --git a/rust-book/advanced/unsafe-rust/Cargo.lock b/rust-book/advanced/unsafe-rust/Cargo.lock new file mode 100755 index 0000000..fbd902c --- /dev/null +++ b/rust-book/advanced/unsafe-rust/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "unsafe-rust" +version = "0.1.0" + diff --git a/rust-book/advanced/unsafe-rust/Cargo.toml b/rust-book/advanced/unsafe-rust/Cargo.toml new file mode 100755 index 0000000..b37474a --- /dev/null +++ b/rust-book/advanced/unsafe-rust/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "unsafe-rust" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/advanced/unsafe-rust/src/main.rs b/rust-book/advanced/unsafe-rust/src/main.rs new file mode 100755 index 0000000..c9967a8 --- /dev/null +++ b/rust-book/advanced/unsafe-rust/src/main.rs @@ -0,0 +1,62 @@ +fn main() { + let mut num = 5; + + let r1 = &num as *const i32; + let r2 = &mut num as *mut i32; + + let address = 0x012345usize; + let r = address as *const i32; + + unsafe { + println!("{}", *r1); + println!("{}", *r2); + } + + unsafe { + dangerous(); + } + + + unsafe { + println!("c call: {}", abs(-3)); + } + + + unsafe { + HELLO_WORLD = "test"; + println!("{}", HELLO_WORLD); + } + println!("{}", HI_THERE); + + add_to_count(3); + + unsafe { + println!("counter: {}", COUNTER); + } +} + +unsafe fn dangerous() {} + +extern "C" { + fn abs(input: i32) -> i32; +} + +static mut HELLO_WORLD: &str = "hello world"; +static mut COUNTER: u32 = 0; + +fn add_to_count(inc: u32) { + unsafe { + COUNTER += inc; + } +} + +const HI_THERE: &str = "hi there"; + +unsafe trait Foo { + // methods +} + +unsafe impl Foo for i32 { + // implementations +} + diff --git a/rust-book/blog/Cargo.lock b/rust-book/blog/Cargo.lock new file mode 100755 index 0000000..8e79386 --- /dev/null +++ b/rust-book/blog/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "blog" +version = "0.1.0" + diff --git a/rust-book/blog/Cargo.toml b/rust-book/blog/Cargo.toml new file mode 100755 index 0000000..0f971d3 --- /dev/null +++ b/rust-book/blog/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "blog" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/blog/src/lib.rs b/rust-book/blog/src/lib.rs new file mode 100755 index 0000000..8436a36 --- /dev/null +++ b/rust-book/blog/src/lib.rs @@ -0,0 +1,127 @@ +//pub struct Post { +// state: Option<Box<dyn State>>, +// content: String, +//} +// +//impl Post { +// pub fn new() -> Post { +// Post { +// state: Some(Box::new(Draft {})), +// content: String::new(), +// } +// } +// +// pub fn add_text(&mut self, text: &str) { +// self.content.push_str(text); +// } +// +// pub fn content(&self) -> &str { +// self.state.as_ref().unwrap().content(&self) +// } +// +// pub fn request_review(&mut self) { +// if let Some(s) = self.state.take() { +// self.state = Some(s.request_review()) +// } +// } +// +// pub fn approve(&mut self) { +// if let Some(s) = self.state.take() { +// self.state = Some(s.approve()) +// } +// } +//} +// +//trait State { +// fn request_review(self: Box<Self>) -> Box<dyn State>; +// fn approve(self: Box<Self>) -> Box<dyn State>; +// fn content<'a>(&self, post: &'a Post) -> &'a str { +// "" +// } +//} +// +//struct Draft {} +// +//impl State for Draft { +// fn request_review(self: Box<Self>) -> Box<dyn State> { +// Box::new(PendingReview {}) +// } +// +// fn approve(self: Box<Self>) -> Box<dyn State> { +// self +// } +//} +// +//struct PendingReview {} +// +//impl State for PendingReview { +// fn request_review(self: Box<Self>) -> Box<dyn State> { +// self +// } +// +// fn approve(self: Box<Self>) -> Box<dyn State> { +// Box::new(Published {}) +// } +//} +// +//struct Published {} +// +//impl State for Published { +// fn request_review(self: Box<Self>) -> Box<dyn State> { +// self +// } +// +// fn approve(self: Box<Self>) -> Box<dyn State> { +// self +// } +// +// fn content<'a>(&self, post: &'a Post) -> &'a str { +// &post.content +// } +//} + + + +pub struct Post { + content: String, +} + +pub struct DraftPost { + content: String, +} + +pub struct PendingReviewPost { + content: String, +} + +impl Post { + pub fn new() -> DraftPost { + DraftPost { + content: String::new(), + } + } + + pub fn content(&self) -> &str { + &self.content + } +} + +impl DraftPost { + pub fn add_text(&mut self, text: &str) { + self.content.push_str(text); + } + + pub fn request_review(self) -> PendingReviewPost { + PendingReviewPost { + content: self.content, + } + } +} + +impl PendingReviewPost { + pub fn approve(self) -> Post { + Post { + content: self.content, + } + } +} diff --git a/rust-book/blog/src/main.rs b/rust-book/blog/src/main.rs new file mode 100755 index 0000000..c976cd9 --- /dev/null +++ b/rust-book/blog/src/main.rs @@ -0,0 +1,36 @@ +use blog::Post; + +fn main() { +// let mut post = Post::new(); +// +// post.add_text("salad"); +// assert_eq!("", post.content()); +// +// post.request_review(); +// assert_eq!("", post.content()); +// +// post.approve(); +// assert_eq!("salad", post.content()); + + + +// let mut post = Post::new(); +// post.add_text("salad"); +// assert_eq!("", post.content()); + + + + let mut post = Post::new(); + + post.add_text("salad"); + let post = post.request_review(); + let post = post.approve(); + + assert_eq!("salad", post.content()); + + + + + + println!("Done."); +} diff --git a/rust-book/collections/Cargo.lock b/rust-book/collections/Cargo.lock new file mode 100755 index 0000000..14856a6 --- /dev/null +++ b/rust-book/collections/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "collections" +version = "0.1.0" + diff --git a/rust-book/collections/Cargo.toml b/rust-book/collections/Cargo.toml new file mode 100755 index 0000000..8460a0c --- /dev/null +++ b/rust-book/collections/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "collections" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/collections/src/main.rs b/rust-book/collections/src/main.rs new file mode 100755 index 0000000..7257ce2 --- /dev/null +++ b/rust-book/collections/src/main.rs @@ -0,0 +1,133 @@ +use std::collections::HashMap; + +fn main() { + //let v: Vec<i32> = Vec::new(); + //let mut v = vec![1, 2, 3, 4, 5]; + + // let third: &i32 = &v[2]; + // println!("the third element is {}", third); + // + // match v.get(2) { + // Some(third) => println!("third is {}", third), + // None => println!("no third element"), + // } + // + // for i in &mut v { + // *i += 10; + // println!("{}", *i); + // } + // for i in &v { + // println!("{}", i); + // } + + // enum SpreadsheetCell { + // Int(i32), + // Float(f64), + // Text(String), + // } + // + // let row = vec![ + // SpreadsheetCell::Int(3), + // SpreadsheetCell::Text(String::from("blue")), + // SpreadsheetCell::Float(10.12), + // ]; + + //let mut s = String::new(); + + //let data = "initial contents"; + //let s = data.to_string(); + //dbg!(s); + //let s = "initial contents".to_string(); + //dbg!(s); + //let s = String::from("initial contents"); + //dbg!(s); + + //let mut s = String::from("hello"); + //s.push_str(" world"); + + //let mut s1 = String::from("hello"); + //let s2 = " world"; + //s1.push_str(s2); + //s1.push('!'); + //dbg!(s1); + + //let s1 = String::from("Hello "); + //let s2 = String::from("world"); + //let s3 = s1 + &s2 + "!"; + //dbg!(s3); + + //let my_result: Result<&'static str, &'static str> = Ok("test"); + + //dbg!(my_result); + + //let s1 = String::from("tic"); + //let s2 = String::from("tac"); + //let s3 = String::from("toe"); + + //let s = format!("{}-{}-{}", s1, s2, s3); + //dbg!(s); + + //let s = String::from("welcome to hello world"); + //let len = s.len(); + //dbg!(len); + //let s1 = s[0..15].to_string(); + //dbg!(s1); + + //for c in "hello world".bytes() { + // dbg!(c); + //} + + //let mut scores = HashMap::new(); + //scores.insert(String::from("Blue"), 10); + //scores.insert(String::from("Yellow"), 50); + //scores.insert(String::from("Blue"), 20); + //dbg!(scores); + + //let teams = vec![String::from("blue"), String::from("yellow")]; + //let initial_scores = vec![10, 20]; + //let scores: HashMap<_, _> = teams.iter().zip(initial_scores.iter()).collect(); + //dbg!(scores); + + //let field_name = String::from("favorite color"); + //let field_value = String::from("blue"); + + //let mut map = HashMap::new(); + //map.insert(field_name, field_value); + + //let mut scores = HashMap::new(); + //scores.insert(String::from("blue"), 10); + //scores.insert(String::from("yellow"), 50); + + //let team_name = String::from("blue"); + //let score = scores.get(&team_name); + + //dbg!(team_name); + //dbg!(score); + + //let mut scores = HashMap::new(); + + //scores.insert(String::from("blue"), 10); + //scores.insert(String::from("yellow"), 50); + + //for (key, value) in &scores { + // dbg!(key); + // dbg!(value); + //} + + // let mut scores = HashMap::new(); + // scores.insert(String::from("blue"), 10); + // scores.entry(String::from("yellow")).or_insert(50); + // scores.entry(String::from("blue")).or_insert(50); + // dbg!(scores); + + //let text = "when in the course of himan events it becomes necessary for one people to dissolve the political bands which have connected them with another and to assume among the powers of the earth the separate and equal station to which thelaws of nature and of nature's God entitle them a decent respect to the opinions of mankind requires that they should declare the causes which impel them to the separation"; + //let mut map = HashMap::new(); + + //for word in text.split_whitespace() { + // let count = map.entry(word).or_insert(0); + // *count += 1; + //} + + //dbg!(map); + +} diff --git a/rust-book/concurrency/Cargo.lock b/rust-book/concurrency/Cargo.lock new file mode 100755 index 0000000..74a4d7a --- /dev/null +++ b/rust-book/concurrency/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "concurrency" +version = "0.1.0" + diff --git a/rust-book/concurrency/Cargo.toml b/rust-book/concurrency/Cargo.toml new file mode 100755 index 0000000..0bfe465 --- /dev/null +++ b/rust-book/concurrency/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "concurrency" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/concurrency/src/main.rs b/rust-book/concurrency/src/main.rs new file mode 100755 index 0000000..53417eb --- /dev/null +++ b/rust-book/concurrency/src/main.rs @@ -0,0 +1,137 @@ +use std::sync::Arc; +use std::rc::Rc; +use std::sync::Mutex; +use std::thread; +use std::sync::mpsc; +use std::time::Duration; + +fn main() { +// let handle = thread::spawn(|| { +// for i in 1..10 { +// println!("spawned: {}", i); +// thread::sleep(Duration::from_millis(1)); +// } +// }); +// +// for i in 1..5 { +// println!("main: {}", i); +// thread::sleep(Duration::from_millis(1)); +// } +// +// handle.join().unwrap(); + + + +// let v = vec![1, 2, 3]; +// +// let handle = thread::spawn(move || { +// println!("Here's a vector: {:?}", v); +// }); +// +// drop(v); +// handle.join().unwrap(); + + + +// let (tx, rx) = mpsc::channel(); +// +// thread::spawn(move || { +// let val = String::from("hi"); +// tx.send(val).unwrap(); +// dbg!(val); +// }); +// +// let received = rx.recv().unwrap(); +// dbg!(received); + + + +// let (tx, rx) = mpsc::channel(); +// +// thread::spawn(move || { +// let vals = vec![ +// String::from("the"), +// String::from("walking"), +// String::from("thread"), +// ]; +// +// for val in vals { +// tx.send(val).unwrap(); +// thread::sleep(Duration::from_secs(1)); +// } +// }); +// +// for received in rx { +// println!("got {}", received); +// } + + + +// let (tx, rx) = mpsc::channel(); +// +// let tx1 = mpsc::Sender::clone(&tx); +// thread::spawn(move || { +// let vals = vec![ +// String::from("the"), +// String::from("walking"), +// String::from("thread"), +// ]; +// +// for val in vals { +// tx1.send(val).unwrap(); +// thread::sleep(Duration::from_secs(1)); +// } +// }); +// +// thread::spawn(move || { +// let vals = vec![ +// String::from("welcome"), +// String::from("to"), +// String::from("woodberry"), +// String::from("!"), +// ]; +// +// for val in vals { +// tx.send(val).unwrap(); +// thread::sleep(Duration::from_secs(1)); +// } +// }); +// +// for received in rx { +// dbg!(received); +// } + + + +// let m = Mutex::new(5); +// +// { +// let mut num = m.lock().unwrap(); +// *num = 6; +// } +// +// println!("m = {:?}", m); + + + + let counter = Arc::new(Mutex::new(0)); + let mut handles = vec![]; + + for _ in 0..10 { + let counter = Arc::clone(&counter); + let handle = thread::spawn(move || { + let mut num = counter.lock().unwrap(); + + *num += 1; + }); + handles.push(handle); + } + + for handle in handles { + handle.join().unwrap(); + } + + dbg!(*counter.lock().unwrap()); + + println!("Done."); +} diff --git a/rust-book/control/Cargo.lock b/rust-book/control/Cargo.lock new file mode 100755 index 0000000..81a9861 --- /dev/null +++ b/rust-book/control/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "control" +version = "0.1.0" + diff --git a/rust-book/control/Cargo.toml b/rust-book/control/Cargo.toml new file mode 100755 index 0000000..70b4d1d --- /dev/null +++ b/rust-book/control/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "control" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/control/src/main.rs b/rust-book/control/src/main.rs new file mode 100755 index 0000000..0b74683 --- /dev/null +++ b/rust-book/control/src/main.rs @@ -0,0 +1,7 @@ +fn main() { + + for number in (1..1000).rev() { + println!("{}", number); + } +} + diff --git a/rust-book/crates/Cargo.lock b/rust-book/crates/Cargo.lock new file mode 100755 index 0000000..3e95fa1 --- /dev/null +++ b/rust-book/crates/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "crates" +version = "0.1.0" + diff --git a/rust-book/crates/Cargo.toml b/rust-book/crates/Cargo.toml new file mode 100755 index 0000000..202ff1d --- /dev/null +++ b/rust-book/crates/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "crates" +version = "0.1.0" +authors = ["53hornet <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/crates/src/lib.rs b/rust-book/crates/src/lib.rs new file mode 100755 index 0000000..5cf1d97 --- /dev/null +++ b/rust-book/crates/src/lib.rs @@ -0,0 +1,33 @@ +//! # Art +//! +//! A library for modeling artistic concepts. + +pub use kinds::PrimaryColor; +pub use kinds::SecondaryColor; +pub use utils::mix; + +pub mod kinds { + /// The primary colors according to the RYB color model. + pub enum PrimaryColor { + Red, + Yellow, + Blue, + } + + /// The secondary colors according to the RYB color model. + pub enum SecondaryColor { + Orange, + Green, + Purple, + } +} + +pub mod utils { + use crate::kinds::*; + + /// Combines two primary color in equal amounts to create + /// a secondary color. + pub fn mix(c1: PrimaryColor, c2: PrimaryColor) -> SecondaryColor { + SecondaryColor::Green + } +} diff --git a/rust-book/crates/src/main.rs b/rust-book/crates/src/main.rs new file mode 100755 index 0000000..80668f2 --- /dev/null +++ b/rust-book/crates/src/main.rs @@ -0,0 +1,8 @@ +use art::PrimaryColor; +use art::mix; + +fn main() { + let red = PrimaryColor::Red, + let yellow = PrimaryColor::Yellow; + mix(red, yellow); +} diff --git a/rust-book/employees/Cargo.lock b/rust-book/employees/Cargo.lock new file mode 100755 index 0000000..a6d8fc5 --- /dev/null +++ b/rust-book/employees/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "employees" +version = "0.1.0" + diff --git a/rust-book/employees/Cargo.toml b/rust-book/employees/Cargo.toml new file mode 100755 index 0000000..016ef3b --- /dev/null +++ b/rust-book/employees/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "employees" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/employees/src/main.rs b/rust-book/employees/src/main.rs new file mode 100755 index 0000000..0900bed --- /dev/null +++ b/rust-book/employees/src/main.rs @@ -0,0 +1,181 @@ +use std::collections::HashMap; +use std::process; +use std::io::{self, Write}; + +struct Employees { + departments: HashMap<String, Vec<String>>, +} + +impl Employees { + + fn add_employee(&self, name: &Option<&String>, department: &Option<&String>) -> Result<(), &'static str> { + // parse name + let name = match name { + Some(s) => s, + None => { + return Err("Invalid or empty name."); + }, + }; + + // parse department + let dept = match department { + Some(s) => s, + None => { + return Err("Invalid or empty department."); + }, + }; + + // add name to department in departments + // and create department if it doesn't exist + employees.entry(dept.to_string()) + .or_insert(Vec::new()) + .push(name.to_string()); + + Ok(()) + } +} + +//fn list_employees() { +// let dept = match actions.get(1) { +// Some(s) => s, +// None => { +// "" +// } +// }; +// +// if dept == "" { +// // print employees in all depts +// for each in employees.keys() { +// println!("{}", each); +// match employees.get(&each.to_string()) { +// Some(v) => { +// for every in v { +// println!(" {}", every); +// } +// }, +// None => continue, +// }; +// } +// } +// else { +// // print employees in single dept +// match employees.get(&dept.to_string()) { +// Some(v) => { +// for every in v { +// println!("{}", every); +// }; +// }, +// None => { +// eprintln!("List: Invalid department."); +// continue; +// } +// }; +// } +//} +// +//fn list_employee(name) { +//} + + +//fn remove_employee(name) { +// let name = match actions.get(1) { +// Some(s) => s, +// None => { +// eprintln!("Remove: Invalid or empty name."); +// continue; +// }, +// }; +// +// let dept = match actions.get(2) { +// Some(s) => s, +// None => { +// eprintln!("Remove: Empty department."); +// continue; +// }, +// }; +// +// match employees.get_mut(&dept.to_string()) { +// Some(v) => { +// v.retain(|employee| employee != name); +// }, +// None => { +// eprintln!("Remove: Invalid department."); +// continue; +// } +// }; + +//} + +fn get_actions() -> Vec<String> { + print!("> "); + io::stdout().flush().unwrap(); + + // grab input + let mut input = String::new(); + io::stdin().read_line(&mut input) + .expect("Failed to read input."); + + // finish on eof + if input == "" { + println!("Bye."); + process::exit(0); + } + + // collect all CLI arguments into vector of trimmed Strings + input.trim() + .split_whitespace() + .map(|action| action.to_string()) + .collect() +} + +fn main() { + println!("Welcome to employee manager."); + println!("Enter 'help' for help or Ctrl+D to exit."); + let mut departments: HashMap<String, Vec<String>> = HashMap::new(); + + // operating loop + loop { + let actions = get_actions(); + + // act on actions + let command = match actions.get(0) { + Some(c) => c, + None => { + eprintln!("Empty command. Enter Ctrl+D to exit."); + continue; + } + }; + + match command.as_str() { + // add employee to department + "add" => { + match add_employee(&actions.get(1), &actions.get(2), &mut departments) { + Ok(()) => {dbg!(&departments);}, + Err(e) => eprintln!("{}", e), + }; + }, + + // list employees from one or all departments + "list" => { + }, + + // remove employee from department + "remove" => { + }, + + // print help + "help" => { + println!("Valid commands include:"); + println!("\tlist [department]"); + println!("\tadd <name> <department>"); + println!("\tremove <name> <department>"); + println!("Enter 'help' for help or Ctrl+D to exit."); + }, + + // all else fails + _ => eprintln!("Invalid command."), + } + + } + +} diff --git a/rust-book/enums/Cargo.lock b/rust-book/enums/Cargo.lock new file mode 100755 index 0000000..d3577dd --- /dev/null +++ b/rust-book/enums/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "enums" +version = "0.1.0" + diff --git a/rust-book/enums/Cargo.toml b/rust-book/enums/Cargo.toml new file mode 100755 index 0000000..99fb9fc --- /dev/null +++ b/rust-book/enums/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "enums" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/enums/src/main.rs b/rust-book/enums/src/main.rs new file mode 100755 index 0000000..b8c61de --- /dev/null +++ b/rust-book/enums/src/main.rs @@ -0,0 +1,12 @@ +fn main() { + let some_u8_value = Some(3u8); +// match some_u8_value { +// Some(3) => println!("three"), +// _ => (), +// } + + if let Some(3) = some_u8_value { + println!("three"); + } + +} diff --git a/rust-book/enums/src/main1.rs b/rust-book/enums/src/main1.rs new file mode 100755 index 0000000..9670693 --- /dev/null +++ b/rust-book/enums/src/main1.rs @@ -0,0 +1,48 @@ +#[derive(Debug)] +enum UsState { + NY, + VA, + NC, +} + +enum Coin { + Penny, + Nickel, + Dime, + Quarter(UsState), +} + +impl Coin { + + fn value_in_cents(self) -> u32 { + + match self { + Coin::Penny => { + println!("lucky penny"); + 1 + }, + Coin::Nickel => 5, + Coin::Dime => 10, + Coin::Quarter(state) => { + println!("State quarter from {:?}", state); + 25 + }, + + } + + } +} + +fn plus_one(x: Option<i32>) -> Option<i32> { + + match x { + None => None, + Some(i) => Some(i + 1), + } +} + +fn main() { + let five = Some(5); + let six = plus_one(five); + let none = plus_one(None); +} diff --git a/rust-book/errors/Cargo.lock b/rust-book/errors/Cargo.lock new file mode 100755 index 0000000..749984f --- /dev/null +++ b/rust-book/errors/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "errors" +version = "0.1.0" + diff --git a/rust-book/errors/Cargo.toml b/rust-book/errors/Cargo.toml new file mode 100755 index 0000000..e531a1b --- /dev/null +++ b/rust-book/errors/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "errors" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/errors/src/main.rs b/rust-book/errors/src/main.rs new file mode 100755 index 0000000..1250677 --- /dev/null +++ b/rust-book/errors/src/main.rs @@ -0,0 +1,38 @@ +use std::io; +use std::io::Read; +use std::fs::File; +//use std::io::ErrorKind; + +fn read_username_from_file() -> Result<String, io::Error> { +// let f = File::open("hello.txt"); +// let mut f = match f { +// Ok(file) => file, +// Err(e) => return Err(e), +// }; +// let mut s = String::new(); +// match f.read_to_string(&mut s) { +// Ok(_) => Ok(s), +// Err(e) => Err(e), +// } + let mut s = String::new(); + File::open("hello.txt")?.read_to_string(&mut s)?; + Ok(s) +} +fn main() { +// let f = File::open("hello.txt").map_err(|error| { +// if error.kind() == ErrorKind::NotFound { +// File::create("hello.txt").unwrap_or_else(|error| { +// panic!("Could not create file: {:?}", error); +// }) +// } +// else { +// panic!("Problem opening file: {:?}", error); +// } +// }); + + //let f = File::open("hello.txt").unwrap(); + + //let f = File::open("hello.txt").expect("failed to open hello.txt"); + + dbg!(read_username_from_file()); +} diff --git a/rust-book/fibonacci/Cargo.lock b/rust-book/fibonacci/Cargo.lock new file mode 100755 index 0000000..06aa71c --- /dev/null +++ b/rust-book/fibonacci/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "fibonacci" +version = "0.1.0" + diff --git a/rust-book/fibonacci/Cargo.toml b/rust-book/fibonacci/Cargo.toml new file mode 100755 index 0000000..60bf227 --- /dev/null +++ b/rust-book/fibonacci/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "fibonacci" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/fibonacci/src/main.rs b/rust-book/fibonacci/src/main.rs new file mode 100755 index 0000000..0b4f22b --- /dev/null +++ b/rust-book/fibonacci/src/main.rs @@ -0,0 +1,31 @@ +use std::env; + +fn fib(n: u32) -> u32 { + + if n == 0 || n == 1 { + return n; + } + else { + return fib(n - 1) + fib(n - 2); + } + +} + +fn main() { + // grab iterations + let iterations: u32 = match env::args().nth(1) { + Some(s) => { + let attempt: u32 = s.trim().parse() + .expect("error: could not parse iterations"); + attempt + }, + None => { + eprintln!("error: usage: fibonacci [iterations]"); + return; + }, + }; + + for i in 0..iterations { + println!("{}", fib(i)); + } +} diff --git a/rust-book/ftoctof/Cargo.lock b/rust-book/ftoctof/Cargo.lock new file mode 100755 index 0000000..e716471 --- /dev/null +++ b/rust-book/ftoctof/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ftoctof" +version = "0.1.0" + diff --git a/rust-book/ftoctof/Cargo.toml b/rust-book/ftoctof/Cargo.toml new file mode 100755 index 0000000..544eb2b --- /dev/null +++ b/rust-book/ftoctof/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ftoctof" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/ftoctof/src/main.rs b/rust-book/ftoctof/src/main.rs new file mode 100755 index 0000000..6425344 --- /dev/null +++ b/rust-book/ftoctof/src/main.rs @@ -0,0 +1,43 @@ +use std::env; + +fn print_usage() { + eprintln!("error: usage: ftoctof [degrees] [f|c]"); +} + +fn main() { + // grab degrees value + let degrees: f32 = match env::args().nth(1) { + Some(s) => { + let attempt: f32 = s.trim().parse() + .expect("error: could not parse degrees"); + attempt + }, + None => { + print_usage(); + return; + }, + }; + + // grab scale identifier + let scale = match env::args().nth(2) { + Some(s) => s.to_lowercase(), + None => { + print_usage(); + return; + }, + }; + + // compute and print conversion + if scale == "f" { + let result: f32 = (degrees - 32.0) * 5.0 / 9.0; + println!("{} degrees fahrenheight is {} degrees celcius.", degrees, result); + } + else if scale == "c" { + let result: f32 = degrees * 9.0 / 5.0 + 32.0; + println!("{} degrees celcius is {} degrees fahrenheight.", degrees, result); + } + else { + print_usage(); + } + +} diff --git a/rust-book/functional/Cargo.lock b/rust-book/functional/Cargo.lock new file mode 100755 index 0000000..ba41a73 --- /dev/null +++ b/rust-book/functional/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "functional" +version = "0.1.0" + diff --git a/rust-book/functional/Cargo.toml b/rust-book/functional/Cargo.toml new file mode 100755 index 0000000..960ba85 --- /dev/null +++ b/rust-book/functional/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functional" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/functional/src/main.rs b/rust-book/functional/src/main.rs new file mode 100755 index 0000000..7749e58 --- /dev/null +++ b/rust-book/functional/src/main.rs @@ -0,0 +1,188 @@ +//use std::thread; +//use std::time::Duration; +// +//struct Cacher<T> +// where T: Fn(u32) -> u32 +//{ +// calculation: T, +// value: Option<u32>, +//} +// +//impl<T> Cacher<T> +// where T: Fn(u32) -> u32 +//{ +// fn new (calculation: T) -> Cacher<T> { +// Cacher { +// calculation, +// value: None, +// } +// } +// +// fn value(&mut self, arg: u32) -> u32 { +// match self.value { +// Some(v) => v, +// None => { +// let v = (self.calculation)(arg); +// self.value = Some(v); +// v +// }, +// } +// } +//} +// +//fn main() { +// let simulated_user_specified_value = 26; +// let simulated_random_number = 3; +// +// generate_workout( +// simulated_user_specified_value, +// simulated_random_number +// ); +//} +// +//fn generate_workout(intensity: u32, random_number: u32) { +// let mut expensive_result = Cacher::new(|num| { +// println!("calculating slowly..."); +// thread::sleep(Duration::from_secs(2)); +// num +// }); +// +// if intensity < 25 { +// println!( +// "Today, do {} pushups!", +// expensive_result.value(intensity) +// ); +// println!( +// "Next, do {} situps!", +// expensive_result.value(intensity) +// ); +// } +// else { +// if random_number == 3 { +// println!("Take a break today! Remember to stay hydrated!"); +// } +// else { +// println!( +// "Today, run for {} minutes!", +// expensive_result.value(intensity) +// ); +// } +// } +//} +// + + + + +fn main() { + let v1 = vec![1, 2, 3]; + let v1_iter = v1.iter(); + + for val in v1_iter { + dbg!(val); + } +} + +#[test] +fn iterator_demonstration() { + let v1 = vec![1, 2, 3]; + let mut v1_iter = v1.iter(); + + assert_eq!(v1_iter.next(), Some(&1)); + assert_eq!(v1_iter.next(), Some(&2)); + assert_eq!(v1_iter.next(), Some(&3)); + assert_eq!(v1_iter.next(), None); +} + +#[test] +fn iterator_sum() { + let v1 = vec![1, 2, 3]; + let v1_iter = v1.iter(); + let total: i32 = v1_iter.sum(); + assert_eq!(total, 6); +} + +#[test] +fn iterator_map() { + let v1: Vec<i32> = vec![1, 2, 3]; + let v2: Vec<_> = v1.iter().map(|x| x + 1).collect(); + assert_eq!(v2, vec![2, 3, 4]); +} + + + +#[derive(PartialEq, Debug)] +struct Shoe { + size: i32, + style: String, +} + +fn shoes_in_my_size(shoes: Vec<Shoe>, shoe_size: i32) -> Vec<Shoe> { + shoes.into_iter() + .filter(|s| s.size == shoe_size) + .collect() +} + +#[test] +fn filters_by_size() { + let shoes = vec![ + Shoe { size: 10, style: String::from("sneaker") }, + Shoe { size: 10, style: String::from("boot") }, + Shoe { size: 13, style: String::from("sandal") }, + ]; + + let in_my_size = shoes_in_my_size(shoes, 10); + + assert_eq!( + in_my_size, + vec![ + Shoe { size: 10, style: String::from("sneaker") }, + Shoe { size: 10, style: String::from("boot") }, + ] + ); +} + +struct Counter { + count: u32, +} + +impl Counter { + fn new() -> Counter { + Counter { count: 0 } + } +} + +impl Iterator for Counter { + type Item = u32; + + fn next(&mut self) -> Option<Self::Item> { + self.count += 1; + + if self.count < 6 { + Some(self.count) + } + else { + None + } + } +} + +#[test] +fn calling_next_directly() { + let mut counter = Counter::new(); + assert_eq!(counter.next(), Some(1)); + assert_eq!(counter.next(), Some(2)); + assert_eq!(counter.next(), Some(3)); + assert_eq!(counter.next(), Some(4)); + assert_eq!(counter.next(), Some(5)); + assert_eq!(counter.next(), None); +} + +#[test] +fn using_other_iterator_trait_methods() { + let sum: u32 = Counter::new().zip(Counter::new().skip(1)) + .map(|(a, b)| a * b) + .filter(|x| x % 3 == 0) + .sum(); + assert_eq!(18, sum); +} diff --git a/rust-book/functions/Cargo.lock b/rust-book/functions/Cargo.lock new file mode 100755 index 0000000..89a654d --- /dev/null +++ b/rust-book/functions/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "functions" +version = "0.1.0" + diff --git a/rust-book/functions/Cargo.toml b/rust-book/functions/Cargo.toml new file mode 100755 index 0000000..656b779 --- /dev/null +++ b/rust-book/functions/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "functions" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/functions/src/main.rs b/rust-book/functions/src/main.rs new file mode 100755 index 0000000..43284ff --- /dev/null +++ b/rust-book/functions/src/main.rs @@ -0,0 +1,10 @@ +fn main() { + let x = plus_one(5); + + println!("The value of x is {}", x); +} + +fn plus_one(x: i32) -> i32 { + x + 1 +} + diff --git a/rust-book/generics/Cargo.lock b/rust-book/generics/Cargo.lock new file mode 100755 index 0000000..3ddbc8c --- /dev/null +++ b/rust-book/generics/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "generics" +version = "0.1.0" + diff --git a/rust-book/generics/Cargo.toml b/rust-book/generics/Cargo.toml new file mode 100755 index 0000000..5529f73 --- /dev/null +++ b/rust-book/generics/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "generics" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/generics/src/main.rs b/rust-book/generics/src/main.rs new file mode 100755 index 0000000..e41d6f5 --- /dev/null +++ b/rust-book/generics/src/main.rs @@ -0,0 +1,68 @@ +//struct Point<T, U> { +// x: T, +// y: U, +//} + +//impl<T, U> Point<T, U> { +// fn x(&self) -> &T { +// &self.x +// } +// +// fn y(&self) -> &T { +// &self.y +// } + +// fn mixup<V, W>(self, other: Point<V, W>) -> Point<T, W> { +// Point { +// x: self.x, +// y: other.y, +// } +// } +//} + +fn largest<T: PartialOrd + Copy>(list: &[T]) -> T { + let mut largest = list[0]; + + for &item in list.iter() { + + if item > largest { + largest = item; + } + + } + + largest +} + +//enum Option_i32 { +// Some(i32), +// None, +//} +// +//enum Option_f64 { +// Some(f64), +// None, +//} + +fn main() { + let number_list = vec![34, 50, 25, 100, 65]; + dbg!(largest(&number_list)); + let char_list = vec!['h', 'e', 'l', 'l', 'o']; + dbg!(largest(&char_list)); +// let integer = Point { x: 5, y: 10 }; +// let float = Point { x: 5.0, y: 10.0 }; + +// let p = Point { x: 5.0, y: 10.5 }; +// dbg!(p.x()); +// dbg!(p.y()); + +// let p1 = Point { x: 5, y: 10.4 }; +// let p2 = Point { x: "Hello", y: 'c' }; +// let p3 = p1.mixup(p2); +// +// dbg!(p3.x); +// dbg!(p3.y); + +// let integer = Option_i32::Some(5); +// let float = Option_f64::Some(5.0); +} diff --git a/rust-book/guessing-game/Cargo.lock b/rust-book/guessing-game/Cargo.lock new file mode 100755 index 0000000..c25e3df --- /dev/null +++ b/rust-book/guessing-game/Cargo.lock @@ -0,0 +1,80 @@ +[[package]] +name = "bitflags" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "fuchsia-zircon" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)", + "fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "fuchsia-zircon-sys" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "guessing-game" +version = "0.1.0" +dependencies = [ + "rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "libc" +version = "0.2.45" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "rand" +version = "0.3.22" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", + "rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "rand" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)", + "libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +dependencies = [ + "winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", + "winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" + +[metadata] +"checksum bitflags 1.0.4 (registry+https://github.com/rust-lang/crates.io-index)" = "228047a76f468627ca71776ecdebd732a3423081fcf5125585bcd7c49886ce12" +"checksum fuchsia-zircon 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "2e9763c69ebaae630ba35f74888db465e49e259ba1bc0eda7d06f4a067615d82" +"checksum fuchsia-zircon-sys 0.3.3 (registry+https://github.com/rust-lang/crates.io-index)" = "3dcaa9ae7725d12cdb85b3ad99a434db70b468c09ded17e012d86b5c1010f7a7" +"checksum libc 0.2.45 (registry+https://github.com/rust-lang/crates.io-index)" = "2d2857ec59fadc0773853c664d2d18e7198e83883e7060b63c924cb077bd5c74" +"checksum rand 0.3.22 (registry+https://github.com/rust-lang/crates.io-index)" = "15a732abf9d20f0ad8eeb6f909bf6868722d9a06e1e50802b6a70351f40b4eb1" +"checksum rand 0.4.3 (registry+https://github.com/rust-lang/crates.io-index)" = "8356f47b32624fef5b3301c1be97e5944ecdd595409cc5da11d05f211db6cfbd" +"checksum winapi 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "92c1eb33641e276cfa214a0522acad57be5c56b10cb348b3c5117db75f3ac4b0" +"checksum winapi-i686-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" +"checksum winapi-x86_64-pc-windows-gnu 0.4.0 (registry+https://github.com/rust-lang/crates.io-index)" = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" diff --git a/rust-book/guessing-game/Cargo.toml b/rust-book/guessing-game/Cargo.toml new file mode 100755 index 0000000..08e8e30 --- /dev/null +++ b/rust-book/guessing-game/Cargo.toml @@ -0,0 +1,10 @@ +[package] +name = "guessing-game" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" +description = "A fun game where you guess what number the computer has chosen." +license = "MIT OR Apache-2.0" + +[dependencies] +rand = "0.3.14" diff --git a/rust-book/guessing-game/src/main.rs b/rust-book/guessing-game/src/main.rs new file mode 100755 index 0000000..38dd28d --- /dev/null +++ b/rust-book/guessing-game/src/main.rs @@ -0,0 +1,36 @@ +use std::io; +use std::cmp::Ordering; +use rand::Rng; + +fn main() { + println!("Guess the number!"); + + let secret_number = rand::thread_rng().gen_range(1, 101); + //println!("The secret number is: {}", secret_number); + + loop { + println!("Enter a guess."); + + let mut guess = String::new(); + + io::stdin().read_line(&mut guess) + .expect("Failed to read line."); + + let guess: u32 = match guess.trim().parse() { + Ok(num) => num, + Err(_) => continue, + }; + + println!("You guessed: {}", guess); + + match guess.cmp(&secret_number) { + Ordering::Less => println!("Too small!"), + Ordering::Greater => println!("Too big!"), + Ordering::Equal => { + println!("You win!"); + break; + } + } + } + +} diff --git a/rust-book/hello_server/404.html b/rust-book/hello_server/404.html new file mode 100755 index 0000000..b106938 --- /dev/null +++ b/rust-book/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/rust-book/hello_server/Cargo.lock b/rust-book/hello_server/Cargo.lock new file mode 100755 index 0000000..738010c --- /dev/null +++ b/rust-book/hello_server/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "hello_server" +version = "0.1.0" + diff --git a/rust-book/hello_server/Cargo.toml b/rust-book/hello_server/Cargo.toml new file mode 100755 index 0000000..39057cc --- /dev/null +++ b/rust-book/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/rust-book/hello_server/hello.html b/rust-book/hello_server/hello.html new file mode 100755 index 0000000..869c8f9 --- /dev/null +++ b/rust-book/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/rust-book/hello_server/src/bin/main.rs b/rust-book/hello_server/src/bin/main.rs new file mode 100755 index 0000000..bcf1e46 --- /dev/null +++ b/rust-book/hello_server/src/bin/main.rs @@ -0,0 +1,46 @@ +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().take(2) { + let stream = stream.unwrap(); + + pool.execute(|| { + handle_connection(stream); + }); + } + + println!("shutting down..."); + +} + +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/rust-book/hello_server/src/lib.rs b/rust-book/hello_server/src/lib.rs new file mode 100755 index 0000000..cd1f616 --- /dev/null +++ b/rust-book/hello_server/src/lib.rs @@ -0,0 +1,117 @@ +use std::sync::Arc; +use std::sync::Mutex; +use std::sync::mpsc; +use std::thread; + +enum Message { + NewJob(Job), + Terminate, +} + +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<Message>, +} + +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(Message::NewJob(job)).unwrap(); + } + +} + +impl Drop for ThreadPool { + fn drop(&mut self) { + for _ in &mut self.workers { + self.sender.send(Message::Terminate).unwrap(); + } + + println!("shutting down all workers..."); + + for worker in &mut self.workers { + println!("shutting down worker {}", worker.id); + + if let Some(thread) = worker.thread.take() { + thread.join().unwrap(); + } + } + } +} + +struct Worker { + id: usize, + thread: Option<thread::JoinHandle<()>>, +} + +impl Worker { + pub fn new(id: usize, receiver: Arc<Mutex<mpsc::Receiver<Message>>>) + -> Result<Worker, &'static str> + { + let thread = thread::spawn(move || { + loop { + let message = receiver.lock().unwrap().recv().unwrap(); + + match message { + Message::NewJob(job) => { + println!("worker {} got job, executing...", id); + job.call_box(); + }, + Message::Terminate => { + println!("worker {} was told to terminate...", id); + break; + }, + } + } + }); + + Ok(Worker { + id, + thread: Some(thread), + }) + } +} diff --git a/rust-book/hello_world/hello_cargo/Cargo.lock b/rust-book/hello_world/hello_cargo/Cargo.lock new file mode 100755 index 0000000..bd8a836 --- /dev/null +++ b/rust-book/hello_world/hello_cargo/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "hello_cargo" +version = "0.1.0" + diff --git a/rust-book/hello_world/hello_cargo/Cargo.toml b/rust-book/hello_world/hello_cargo/Cargo.toml new file mode 100755 index 0000000..61d091a --- /dev/null +++ b/rust-book/hello_world/hello_cargo/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "hello_cargo" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/hello_world/hello_cargo/src/main.rs b/rust-book/hello_world/hello_cargo/src/main.rs new file mode 100755 index 0000000..e7a11a9 --- /dev/null +++ b/rust-book/hello_world/hello_cargo/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/rust-book/hello_world/main.exe b/rust-book/hello_world/main.exe Binary files differnew file mode 100755 index 0000000..8bb285b --- /dev/null +++ b/rust-book/hello_world/main.exe diff --git a/rust-book/hello_world/main.rs b/rust-book/hello_world/main.rs new file mode 100755 index 0000000..3d46bbe --- /dev/null +++ b/rust-book/hello_world/main.rs @@ -0,0 +1,4 @@ +fn main() { + println!("hello world!"); +} + diff --git a/rust-book/horcrux/Cargo.toml b/rust-book/horcrux/Cargo.toml new file mode 100755 index 0000000..f6996ac --- /dev/null +++ b/rust-book/horcrux/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "horcrux" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/horcrux/src/main.rs b/rust-book/horcrux/src/main.rs new file mode 100755 index 0000000..e7a11a9 --- /dev/null +++ b/rust-book/horcrux/src/main.rs @@ -0,0 +1,3 @@ +fn main() { + println!("Hello, world!"); +} diff --git a/rust-book/lifetimes/Cargo.lock b/rust-book/lifetimes/Cargo.lock new file mode 100755 index 0000000..0c2507e --- /dev/null +++ b/rust-book/lifetimes/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "lifetimes" +version = "0.1.0" + diff --git a/rust-book/lifetimes/Cargo.toml b/rust-book/lifetimes/Cargo.toml new file mode 100755 index 0000000..8003864 --- /dev/null +++ b/rust-book/lifetimes/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "lifetimes" +version = "0.1.0" +authors = ["53hornet <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/lifetimes/src/main.rs b/rust-book/lifetimes/src/main.rs new file mode 100755 index 0000000..87b6ce6 --- /dev/null +++ b/rust-book/lifetimes/src/main.rs @@ -0,0 +1,43 @@ +fn longest<'a>(x: &'a str, y: &'a str) -> &'a str { + // what this is doing is basically tagging x and y and the + // result with the same 'a, telling rust not to let any + // of them expire before the others; that way nothing + // will go out of scope prematurely and the result will + // always have a non-null reference + + // basically, 'a gives all three values the same lifetime. + // so long as they're all alive at the same time, there are + // no reference errors + + // note that the lifetime selected for the result is + // equal to the smaller of the lifetimes of the + // parameters + + if x.len() > y.len() { + x + } + else { + y + } +} + +struct ImportantExcerpt<'a> { + part: &'a str, +} + +fn main() { + let string1 = String::from("abcd"); + { + let string2 = "xyz"; + + let result = longest(string1.as_str(), string2); + //dbg!(result); + } + + let script = String::from("Before time began, there was the cube. We know not where it comes from."); + let first_sentence = script.split('.') + .next() + .expect("Could not find a '.'"); + let i = ImportantExcerpt { part: first_sentence }; + dbg!(i.part); +} diff --git a/rust-book/mathsssss/Cargo.lock b/rust-book/mathsssss/Cargo.lock new file mode 100755 index 0000000..7ef6f32 --- /dev/null +++ b/rust-book/mathsssss/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "mathsssss" +version = "0.1.0" + diff --git a/rust-book/mathsssss/Cargo.toml b/rust-book/mathsssss/Cargo.toml new file mode 100755 index 0000000..201c096 --- /dev/null +++ b/rust-book/mathsssss/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "mathsssss" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/mathsssss/src/main.rs b/rust-book/mathsssss/src/main.rs new file mode 100755 index 0000000..991590b --- /dev/null +++ b/rust-book/mathsssss/src/main.rs @@ -0,0 +1,61 @@ +use std::env; +use std::collections::HashMap; + +fn calc_mean(numbers: &Vec<i32>) -> f32 { + let sum: i32 = numbers.iter().sum(); + sum as f32 / numbers.len() as f32 +} + +fn calc_median(numbers: &Vec<i32>) -> i32 { + numbers[numbers.len() / 2] +} + +fn calc_mode(numbers: &Vec<i32>) -> i32 { + let mut counts: HashMap<i32, i32> = HashMap::new(); + + for each in numbers { + let count = counts.entry(*each).or_insert(0); + *count += 1; + } + + let mut most: i32 = 0; + let mut result: i32 = 0; + + for (key, val) in counts.iter() { + + if val > &most { + most = *val; + result = *key; + } + } + + if most <= 1 { + 0 + } + else { + result + } + +} + +fn main() { + // grab numbers + let mut numbers: Vec<i32> = Vec::new(); + + for arg in env::args().skip(1) { + let number: i32 = arg.trim().parse() + .expect("error: could not parse arg"); + numbers.push(number); + } + + // sort list (mostly for median) + numbers.sort_by(|a, b| a.partial_cmp(b).unwrap()); + + // calculate and print results + let mean: f32 = calc_mean(&numbers); + println!("mean: {}", mean); + let median: i32 = calc_median(&numbers); + println!("median: {}", median); + let mode: i32 = calc_mode(&numbers); + println!("mode: {}", mode); +} diff --git a/rust-book/minigrep/Cargo.lock b/rust-book/minigrep/Cargo.lock new file mode 100755 index 0000000..5b5afdd --- /dev/null +++ b/rust-book/minigrep/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "minigrep" +version = "0.1.0" + diff --git a/rust-book/minigrep/Cargo.toml b/rust-book/minigrep/Cargo.toml new file mode 100755 index 0000000..09021c1 --- /dev/null +++ b/rust-book/minigrep/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "minigrep" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] + diff --git a/rust-book/minigrep/src/lib.rs b/rust-book/minigrep/src/lib.rs new file mode 100755 index 0000000..bb8b4d7 --- /dev/null +++ b/rust-book/minigrep/src/lib.rs @@ -0,0 +1,96 @@ +use std::env; +use std::error::Error; +use std::fs; + +pub struct Config { + pub query: String, + pub filename: String, + pub case_sensitive: bool, +} + +impl Config { + + pub fn new(mut args: std::env::Args) -> Result<Config, &'static str> { + args.next(); + + let query = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a query string"), + }; + + let filename = match args.next() { + Some(arg) => arg, + None => return Err("Didn't get a filename"), + }; + + let case_sensitive = env::var("CASE_INSENSITIVE").is_err(); + + Ok(Config { query, filename, case_sensitive }) + } + +} + +pub fn run(config: Config) -> Result<(), Box<dyn Error>> { + let contents = fs::read_to_string(config.filename)?; + + let results = if config.case_sensitive { + search(&config.query, &contents) + } + else { + search_case_insensitive(&config.query, &contents) + }; + + for line in results { + println!("{}", line); + } + + Ok(()) +} + +fn search<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + contents.lines() + .filter(|line| line.contains(query)) + .collect() +} + +fn search_case_insensitive<'a>(query: &str, contents: &'a str) -> Vec<&'a str> { + contents.lines() + .filter(|line| line.to_lowercase() + .contains(&query.to_lowercase())) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn case_sensitive() { + let query = "duct"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Duct tape."; + + assert_eq!( + vec!["safe, fast, productive."], + search(query, contents) + ); + } + + #[test] + fn case_insensitive() { + let query = "rUsT"; + let contents = "\ +Rust: +safe, fast, productive. +Pick three. +Trust me."; + + assert_eq!( + vec!["Rust:", "Trust me."], + search_case_insensitive(query, contents) + ); + } +} diff --git a/rust-book/minigrep/src/main.rs b/rust-book/minigrep/src/main.rs new file mode 100755 index 0000000..c752da1 --- /dev/null +++ b/rust-book/minigrep/src/main.rs @@ -0,0 +1,17 @@ +use std::process; +use std::env; + +use minigrep; +use minigrep::Config; + +fn main() { + let config = Config::new(env::args()).unwrap_or_else(|err| { + eprintln!("Problem parsing arguments: {}", err); + process::exit(1); + }); + if let Err(e) = minigrep::run(config) { + eprintln!("Application error: {}", e); + process::exit(1); + } +} + diff --git a/rust-book/oop/Cargo.lock b/rust-book/oop/Cargo.lock new file mode 100755 index 0000000..fd3ef4a --- /dev/null +++ b/rust-book/oop/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "oop" +version = "0.1.0" + diff --git a/rust-book/oop/Cargo.toml b/rust-book/oop/Cargo.toml new file mode 100755 index 0000000..28311ff --- /dev/null +++ b/rust-book/oop/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "oop" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/oop/src/lib.rs b/rust-book/oop/src/lib.rs new file mode 100755 index 0000000..91ef2e8 --- /dev/null +++ b/rust-book/oop/src/lib.rs @@ -0,0 +1,41 @@ +pub trait Draw { + fn draw(&self); +} + +pub struct Screen { + pub components: Vec<Box<dyn Draw>>, +} + +impl Screen { + pub fn run(&self) { + for component in self.components.iter() { + component.draw(); + } + } +} + +pub struct Button { + pub width: u32, + pub height: u32, + pub label: String, +} + +impl Draw for Button { + fn draw(&self) { + dbg!("drew button"); + } +} + +pub struct SelectBox { + pub width: u32, + pub height: u32, + pub options: Vec<String>, +} + +impl Draw for SelectBox { + fn draw(&self) { + dbg!("drew select box"); + } +} + + diff --git a/rust-book/oop/src/main.rs b/rust-book/oop/src/main.rs new file mode 100755 index 0000000..e92c07c --- /dev/null +++ b/rust-book/oop/src/main.rs @@ -0,0 +1,56 @@ +use oop::{Screen, Button, SelectBox}; + +pub struct AveragedCollection { + list: Vec<i32>, + average: f64, +} + +impl AveragedCollection { + pub fn add(&mut self, value: i32) { + self.list.push(value); + self.update_average(); + } + + pub fn remove(&mut self) -> Option<i32> { + let result = self.list.pop(); + match result { + Some(value) => { + self.update_average(); + Some(value) + }, + None => None, + } + } + + pub fn average(&self) -> f64 { + self.average + } + + fn update_average(&mut self) { + let total: i32 = self.list.iter().sum(); + self.average = total as f64 / self.list.len() as f64; + } +} + +fn main() { + let screen = Screen { + components: vec![ + Box::new(SelectBox { + width: 75, + height: 10, + options: vec![ + String::from("Yes"), + String::from("Maybe"), + String::from("No") + ], + }), + Box::new(Button { + width: 50, + height: 10, + label: String::from("OK"), + }), + ], + }; + + screen.run(); +} diff --git a/rust-book/ownership/Cargo.lock b/rust-book/ownership/Cargo.lock new file mode 100755 index 0000000..9e4e62d --- /dev/null +++ b/rust-book/ownership/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "ownership" +version = "0.1.0" + diff --git a/rust-book/ownership/Cargo.toml b/rust-book/ownership/Cargo.toml new file mode 100755 index 0000000..f21df45 --- /dev/null +++ b/rust-book/ownership/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "ownership" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/ownership/src/main.rs b/rust-book/ownership/src/main.rs new file mode 100755 index 0000000..1684f55 --- /dev/null +++ b/rust-book/ownership/src/main.rs @@ -0,0 +1,51 @@ +fn main() { + //let words = String::from("hello there world"); + //let words = "hello there world"; + //let first = first_word(&words); + //let second = second_word(&words); + //let last = last_word(&words); + //println!("{}\n{}", first, last); + let a = [1, 2, 3, 4, 5]; + let slice = &a[1..4]; + + for each in slice { + println!("{}", each); + } +} + +fn first_word(s: &str) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[..i]; + } + } + + &s +} + +fn second_word(s: &str) -> &str { + let bytes = s.as_bytes(); + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + return &s[i + 1..]; + } + } + + &s +} + +fn last_word(s: &str) -> &str { + let bytes = s.as_bytes(); + let mut result = ""; + + for (i, &item) in bytes.iter().enumerate() { + if item == b' ' { + result = &s[i + 1..]; + } + } + + &result +} diff --git a/rust-book/packages/my-project/Cargo.lock b/rust-book/packages/my-project/Cargo.lock new file mode 100755 index 0000000..9679152 --- /dev/null +++ b/rust-book/packages/my-project/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "my-project" +version = "0.1.0" + diff --git a/rust-book/packages/my-project/Cargo.toml b/rust-book/packages/my-project/Cargo.toml new file mode 100755 index 0000000..6edcb51 --- /dev/null +++ b/rust-book/packages/my-project/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "my-project" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/packages/my-project/src/main.rs b/rust-book/packages/my-project/src/main.rs new file mode 100755 index 0000000..486ae46 --- /dev/null +++ b/rust-book/packages/my-project/src/main.rs @@ -0,0 +1,82 @@ +mod sound; + +fn main() { + crate::sound::instrument::clarinet(); + sound::instrument::clarinet(); +} +//mod sound { +// pub mod instrument { +// pub mod woodwind { +// +// pub fn clarinet() { +// println!("clarinet"); +// } +// +// } +// +// pub mod string { +// +// pub fn guitar() { +// println!("guitar"); +// super::woodwind::clarinet(); +// } +// +// } +// +// } +// +// mod voice { +// } +// +//} +// +//mod performance_group { +// pub use crate::sound::instrument::woodwind; +// +// pub fn clarinet_trio() { +// woodwind::clarinet(); +// woodwind::clarinet(); +// woodwind::clarinet(); +// } +// +//} +// +//fn main() { +// performance_group::clarinet_trio(); +// performance_group::woodwind::clarinet(); +//} + +//mod plant { +// pub struct Vegetable { +// pub name: String, +// id: i32, +// } +// +// impl Vegetable { +// pub fn new(name: &str) -> Vegetable { +// Vegetable { +// name: String::from(name), +// id: 1, +// } +// } +// } +//} +// +//fn main() { +// let mut v = plant::Vegetable::new("squash"); +// v.name = String::from("butternut squash"); +// println!("{} are delicious", v.name); +// //println!("The id is: {}", v.id); +//} + +//mod menu { +// pub enum Appetizer { +// Soup, +// Salad, +// } +//} +// +//fn main() { +// let order1 = menu::Appetizer::Soup; +// let order2 = menu::Appetizer::Salad; +//} diff --git a/rust-book/packages/my-project/src/sound.rs b/rust-book/packages/my-project/src/sound.rs new file mode 100755 index 0000000..866ac56 --- /dev/null +++ b/rust-book/packages/my-project/src/sound.rs @@ -0,0 +1 @@ +pub mod instrument; diff --git a/rust-book/packages/my-project/src/sound/instrument.rs b/rust-book/packages/my-project/src/sound/instrument.rs new file mode 100755 index 0000000..727784e --- /dev/null +++ b/rust-book/packages/my-project/src/sound/instrument.rs @@ -0,0 +1,3 @@ +pub fn clarinet() { + println!("clarinet"); +} diff --git a/rust-book/patterns/Cargo.lock b/rust-book/patterns/Cargo.lock new file mode 100755 index 0000000..a233623 --- /dev/null +++ b/rust-book/patterns/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "patterns" +version = "0.1.0" + diff --git a/rust-book/patterns/Cargo.toml b/rust-book/patterns/Cargo.toml new file mode 100755 index 0000000..784a66d --- /dev/null +++ b/rust-book/patterns/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "patterns" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/patterns/src/main.rs b/rust-book/patterns/src/main.rs new file mode 100755 index 0000000..4ee101d --- /dev/null +++ b/rust-book/patterns/src/main.rs @@ -0,0 +1,316 @@ +fn main() { +// let favorite_color: Option<&str> = None; +// let is_tuesday = false; +// let age: Result<u8, _> = "34".parse(); +// +// if let Some(color) = favorite_color { +// dbg!(color); +// } +// else if is_tuesday { +// dbg!("green"); +// } +// else if let Ok(age) = age { +// if age > 30 { +// dbg!("purple"); +// } +// else { +// dbg!("orange"); +// } +// } +// else { +// dbg!("blue"); +// } + + +// let mut stack = Vec::new(); +// +// stack.push(1); +// stack.push(2); +// stack.push(3); +// +// while let Some(top) = stack.pop() { +// dbg!(top); +// } + + +// let v = vec!['a', 'b', 'c']; +// +// for (_, value) in v.iter().enumerate() { +// //println!("{} is at index {}", value, index); +// dbg!(value); +// } + + +// let (..) = (1, 2, 3); + + +// let point = (3, 5); +// print_coords(&point); + + +// let Some(x) = Some(5); +// if let Some(x) = Some(5) { +// dbg!(x); +// } +// if let x = 5 { +// dbg!(x); +// }; + + +// let x = 1; +// +// match x { +// 1 => dbg!("one"), +// 2 => dbg!("two"), +// 3 => dbg!("three"), +// _ => dbg!("else"), +// }; + + + +// let x = Some(5); +// let y = 10; +// +// match x { +// Some(50) => println!("got 50"), +// Some(y) => println!("matched, y == {:?}", y), +// _ => println!("default: x == {:?}", x), +// } +// +// println!("end: x == {:?}, y == {:?}", x, y); + + +// let x = 5; +// +// match x { +// 1 ... 5 => println!("one through five"), +// _ => println!("else"), +// } + + +// let x = 'w'; +// +// match x { +// 'a' ... 'j' => println!("early ascii char"), +// 'k' ... 'z' => println!("late ascii char"), +// _ => println!("else"), +// } + + + +// let p = Point { x: 0, y: 7 }; +// //let Point { x: a, y: b } = p; +// let Point { x, y } = p; +// assert_eq!(0, x); +// assert_eq!(7, y); + + +// let p = Point { x: 1, y: 0 }; +// +// match p { +// Point { x, y: 0 } => dbg!("x-axis"), +// Point { x: 0, y } => dbg!("y-axis"), +// Point { x, y } => dbg!("neither"), +// }; + + +// //let msg = Message::ChangeColor(0, 160, 255); +// //let msg = Message::Write(String::from("hi there")); +// //let msg = Message::Move { +// // x: 1, +// // y: 2, +// //}; +// let msg = Message::ChangeColor(Color::Hsv(0, 160, 255)); +// +// match msg { +// Message::Quit => { +// println!("the quit variant has no data to destructure.") +// }, +// Message::Move { x, y } => { +// println!( +// "Move in the direction {}, {}", +// x, +// y +// ); +// } +// Message::Write(text) => println!("text message: {}", text), +// Message::ChangeColor(Color::Rgb(r, g, b)) => { +// println!( +// "Change the color to RGB {}{}{}", +// r, +// g, +// b +// ) +// } +// Message::ChangeColor(Color::Hsv(h, s, v)) => { +// println!( +// "Change the color to HSV {}{}{}", +// h, +// s, +// v +// ) +// } +// } + + +// let points = vec![ +// Point { x: 0, y: 0 }, +// Point { x: 1, y: 5 }, +// Point { x: 10, y: -3 }, +// ]; +// +// let sum_of_squares: i32 = points +// .iter() +// .map(|&Point { x, y } | x * x + y * y) +// .sum(); +// dbg!(sum_of_squares); +// +// +// let ((feet, inches), Point { x, y }) = ((3, 10), Point { x: 3, y: -10 }); + + +// foo(3, 4); + + +// let mut setting_value = Some(5); +// //let new_setting_value = Some(10); +// let new_setting_value = None; +// +// match (setting_value, new_setting_value) { +// (Some(_), Some(_)) => { +// println!("can't overwrite existing customized value."); +// } +// _ => { +// setting_value = new_setting_value; +// } +// } +// +// println!("setting is {:?}", setting_value); +// +// +// let numbers = (2, 4, 8, 16, 32); +// +// match numbers { +// (first, _, third, _, fifth) => { +// println!("numbers: {}, {}, {}", first, third, fifth) +// }, +// } +// +// +// let _x = 5; +// let _y = 10; +// +// +// let s = Some(String::from("hello")); +// +// if let Some(_) = s { +// println!("found a string"); +// } +// +// println!("{:?}", s); + + +// let origin = Point { x: 1, y: 2, z: 3 }; +// +// match origin { +// Point {x, .. } => dbg!(x), +// }; +// +// let numbers = (2, 4, 8, 16, 32); +// +// match numbers { +// (first, .., last) => { +// dbg!(first); +// dbg!(last); +// }, +// } + + +// let num = Some(4); +// +// let test = match num { +// Some(x) if x < 5 => println!("{}", x), +// Some(x) => println!("{}", x), +// None => (), +// }; + + +// let x = Some(10); +// let y = 10; +// +// match x { +// Some(50) => println!("got 50"), +// Some(n) if n == y => println!("{:?}", n), +// _ => println!("{:?}", x), +// } +// +// println!("{:?} {:?}", x, y); + + +// let x = 4; +// let y = false; +// +// match x { +// 4 | 5 | 6 if y => println!("yes"), +// _ => println!("no"), +// } + + + enum Message { + Hello { id: i32 }, + } + + let msg = Message::Hello { id: 13 }; + + match msg { + Message::Hello { id: id_variable @ 3...7 } => { + println!("{}", id_variable) + }, + Message::Hello { id: 10...12 } => { + println!("another range") + }, + Message::Hello { id } => { + println!("else") + }, + } + + + println!("Done."); +} + + +//struct Point { +// x: i32, +// y: i32, +// z: i32, +//} + + +//fn foo(_: i32, y: i32) { +// println!("this code only uses y: {}", y); +//} + + +//fn print_coords(&(x, y): &(i32, i32)) { +// println!("{}, {}", x, y); +//} + + +//struct Point { +// x: i32, +// y: i32, +//} + + +//enum Message { +// Quit, +// Move { x: i32, y: i32 }, +// Write(String), +// ChangeColor(Color), +//} +// +// +//enum Color { +// Rgb(i32, i32, i32), +// Hsv(i32, i32, i32) +//} diff --git a/rust-book/piglatin/Cargo.lock b/rust-book/piglatin/Cargo.lock new file mode 100755 index 0000000..67b9b02 --- /dev/null +++ b/rust-book/piglatin/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "piglatin" +version = "0.1.0" + diff --git a/rust-book/piglatin/Cargo.toml b/rust-book/piglatin/Cargo.toml new file mode 100755 index 0000000..7d62333 --- /dev/null +++ b/rust-book/piglatin/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "piglatin" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/piglatin/src/main.rs b/rust-book/piglatin/src/main.rs new file mode 100755 index 0000000..c5d9813 --- /dev/null +++ b/rust-book/piglatin/src/main.rs @@ -0,0 +1,38 @@ +use std::env; + +fn print_usage() { + eprintln!("error: usage: piglatin [word] [words]..."); +} + +fn main() { + + for mut word in env::args().skip(1) { + // grab first letter + let first = match word.get(0..1) { + Some(s) => s, + None => { + print_usage(); + return; + } + }; + + // check if first letter is vowel or consonant + // if vowel, append -hay and print + // if consonant, appent first letter and -ay and print + match first { + "a" | "e" | "i" | "o" | "u" | + "A" | "E" | "I" | "O" | "U" => { + print!("{}-hay ", word); + }, + _ => { + let rest = match word.get(1..) { + Some(s) => s, + None => "", + }; + print!("{}-{}ay ", rest, first); + }, + } + } + + println!(); +} diff --git a/rust-book/smart-pointers/Cargo.lock b/rust-book/smart-pointers/Cargo.lock new file mode 100755 index 0000000..7dec816 --- /dev/null +++ b/rust-book/smart-pointers/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "smart-pointers" +version = "0.1.0" + diff --git a/rust-book/smart-pointers/Cargo.toml b/rust-book/smart-pointers/Cargo.toml new file mode 100755 index 0000000..0dcde9f --- /dev/null +++ b/rust-book/smart-pointers/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "smart-pointers" +version = "0.1.0" +authors = ["Adam Carpenter <53hornet@gmail.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/smart-pointers/src/main.rs b/rust-book/smart-pointers/src/main.rs new file mode 100755 index 0000000..5a59f52 --- /dev/null +++ b/rust-book/smart-pointers/src/main.rs @@ -0,0 +1,234 @@ +use List::{Cons, Nil}; +use std::cell::RefCell; +use std::ops::Deref; +use std::rc::{Rc, Weak}; + +//enum List { +// Cons(i32, Rc<List>), +// Nil, +//} + +//#[derive(Debug)] +//enum List { +// Cons(Rc<RefCell<i32>>, Rc<List>), +// Nil, +//} + +#[derive(Debug)] +enum List { + Cons(i32, RefCell<Rc<List>>), + Nil, +} + +impl List { + fn tail(&self) -> Option<&RefCell<Rc<List>>> { + match self { + Cons(_, item) => Some(item), + Nil => None, + } + } +} + +//enum List { +// Cons(i32, Box<List>), +// Nil, +//} + +struct MyBox<T>(T); + +impl<T> MyBox<T> { + fn new(x: T) -> MyBox<T> { + MyBox(x) + } +} + +impl<T> Deref for MyBox<T> { + type Target = T; + fn deref(&self) -> &T { + &self.0 + } +} + +struct CustomSmartPointer { + data: String, +} + +impl Drop for CustomSmartPointer { + fn drop(&mut self) { + println!("Dropped `{}`", self.data); + } +} + +#[derive(Debug)] +struct Node { + value: i32, + parent: RefCell<Weak<Node>>, + children: RefCell<Vec<Rc<Node>>>, +} + +fn main() { +// let x = 5; +// let y = MyBox::new(x); +// +// assert_eq!(5, x); +// assert_eq!(5, *y); + +// let m = MyBox::new(String::from("world")); +// hello(&m); + +// let c = CustomSmartPointer { data: String::from("my stuff") }; +// drop(c); +// let d = CustomSmartPointer { data: String::from("other stuff") }; +// println!("created."); + +// let a = Rc::new(Cons(5, Rc::new(Cons(10, Rc::new(Nil))))); +// dbg!(Rc::strong_count(&a)); +// let b = Cons(3, Rc::clone(&a)); +// dbg!(Rc::strong_count(&a)); +// { +// let c = Cons(4, Rc::clone(&a)); +// dbg!(Rc::strong_count(&a)); +// } +// dbg!(Rc::strong_count(&a)); + +// let value = Rc::new(RefCell::new(5)); +// +// let a = Rc::new(Cons(Rc::clone(&value), Rc::new(Nil))); +// +// let b = Cons(Rc::new(RefCell::new(6)), Rc::clone(&a)); +// let c = Cons(Rc::new(RefCell::new(10)), Rc::clone(&a)); +// +// *value.borrow_mut() += 10; +// +// dbg!(a); +// dbg!(b); +// dbg!(c); + +// let a = Rc::new(Cons(5, RefCell::new(Rc::new(Nil)))); +// dbg!(Rc::strong_count(&a)); +// dbg!(a.tail()); +// let b = Rc::new(Cons(10, RefCell::new(Rc::clone(&a)))); +// dbg!(Rc::strong_count(&a)); +// dbg!(Rc::strong_count(&b)); +// dbg!(b.tail()); +// +// if let Some(link) = a.tail() { +// *link.borrow_mut() = Rc::clone(&b); +// } +// +// dbg!(Rc::strong_count(&b)); +// dbg!(Rc::strong_count(&a)); + + //dbg!(a.tail()); // stack overflow + + let leaf = Rc::new(Node { + value: 3, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![]), + }); + + println!("leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf),); + + { + let branch = Rc::new(Node { + value: 5, + parent: RefCell::new(Weak::new()), + children: RefCell::new(vec![Rc::clone(&leaf)]), + }); + + *leaf.parent.borrow_mut() = Rc::downgrade(&branch); + + println!( + "branch strong = {}, weak = {}", + Rc::strong_count(&branch), + Rc::weak_count(&branch), + ); + + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); + } + + println!("leaf parent = {:?}", leaf.parent.borrow().upgrade()); + println!( + "leaf strong = {}, weak = {}", + Rc::strong_count(&leaf), + Rc::weak_count(&leaf), + ); +} + +fn hello(name: &str) { + println!("hiya {}", name); +} + +pub trait Messenger { + fn send(&self, msg: &str); +} + +pub struct LimitTracker<'a, T: 'a + Messenger> { + messenger: &'a T, + value: usize, + max: usize, +} + +impl<'a, T> LimitTracker<'a, T> where T: Messenger { + pub fn new(messenger: &T, max: usize) -> LimitTracker<T> { + LimitTracker { + messenger, + value: 0, + max, + } + } + + pub fn set_value(&mut self, value: usize) { + self.value = value; + + let percentage_of_max = self.value as f64 / self.max as f64; + + if percentage_of_max >= 1.0 { + self.messenger.send("over quota"); + } + else if percentage_of_max >= 0.9 { + self.messenger.send("90% of quota"); + } + else if percentage_of_max >= 0.75 { + self.messenger.send("75% of quota"); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::cell::RefCell; + + struct MockMessenger { + sent_messages: RefCell<Vec<String>>, + } + + impl MockMessenger { + fn new() -> MockMessenger { + MockMessenger { sent_messages: RefCell::new(vec![]) } + } + } + + impl Messenger for MockMessenger { + fn send(&self, message: &str) { + self.sent_messages.borrow_mut().push(String::from(message)); + } + } + + #[test] + fn sends_75() { + let mock_messenger = MockMessenger::new(); + let mut limit_tracker = LimitTracker::new(&mock_messenger, 100); + + limit_tracker.set_value(80); + + assert_eq!(mock_messenger.sent_messages.borrow().len(), 1); + } +} diff --git a/rust-book/structs/Cargo.lock b/rust-book/structs/Cargo.lock new file mode 100755 index 0000000..25b0b72 --- /dev/null +++ b/rust-book/structs/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "structs" +version = "0.1.0" + diff --git a/rust-book/structs/Cargo.toml b/rust-book/structs/Cargo.toml new file mode 100755 index 0000000..e61ea2a --- /dev/null +++ b/rust-book/structs/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "structs" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/structs/src/main.rs b/rust-book/structs/src/main.rs new file mode 100755 index 0000000..cf93866 --- /dev/null +++ b/rust-book/structs/src/main.rs @@ -0,0 +1,32 @@ +#[derive(Debug)] +struct Rectangle { + width: u32, + height: u32, +} + +impl Rectangle { + + fn area(&self) -> u32 { + self.width * self.height + } + + fn can_hold(&self, other: &Rectangle ) -> bool { + self.width > other.width && self.height > other.height + } + +} + +fn main() { + let rect1 = Rectangle { + width: 30, + height: 50, + }; + let rect2 = Rectangle { + width: 3, + height: 5, + }; + println!("{:#?}", rect1); + println!("The area of the rectangle is {} square pixels.", rect1.area()); + println!("{}", rect1.can_hold(&rect2)); +} + diff --git a/rust-book/structs/src/main.rs.bak b/rust-book/structs/src/main.rs.bak new file mode 100755 index 0000000..361b225 --- /dev/null +++ b/rust-book/structs/src/main.rs.bak @@ -0,0 +1,36 @@ +struct User { + username: String, + email: String, + sign_in_count: u64, + active: bool, +} + +fn main() { +// let mut user1 = User { +// email: String::from("test@tester.net"), +// username: String::from("testytester"), +// active: true, +// sign_in_count: 999, +// }; +// let user1 = build_user(String::from("dennis.nedry@adp.com"), String::from("nedryland")); +// let user2 = User { +// email: String::from("john.hammond@adp.com"), +// username: String::from("spare_no_expense"), +// ..user1 +// }; +// println!("{} {} {} {}", user2.email, user2.username, user2.active, user2.sign_in_count); + + struct Color(u32, u32, u32); + struct Point(i32, i32, i32); + let black = Color(0, 0, 0); + let origin = Point(0, -1, 0); +} + +fn build_user(email: String, username: String) -> User { + User { + email, + username, + active: true, + sign_in_count: 1, + } +} diff --git a/rust-book/testing/Cargo.lock b/rust-book/testing/Cargo.lock new file mode 100755 index 0000000..f38ac62 --- /dev/null +++ b/rust-book/testing/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "testing" +version = "0.1.0" + diff --git a/rust-book/testing/Cargo.toml b/rust-book/testing/Cargo.toml new file mode 100755 index 0000000..665256c --- /dev/null +++ b/rust-book/testing/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "testing" +version = "0.1.0" +authors = ["carpenat"] +edition = "2018" + +[dependencies] diff --git a/rust-book/testing/src/lib.rs b/rust-book/testing/src/lib.rs new file mode 100755 index 0000000..9ce4804 --- /dev/null +++ b/rust-book/testing/src/lib.rs @@ -0,0 +1,32 @@ +pub fn add_two(a: i32) -> i32 { + internal_adder(a, 2) +} + +fn internal_adder(a: i32, b: i32) -> i32 { + a + b +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn add_two_and_two() { + assert_eq!(4, add_two(2)); + } + + #[test] + fn add_three_and_two() { + assert_eq!(5, add_two(3)); + } + + #[test] + #[ignore] + fn one_hundred() { + assert_eq!(102, add_two(100)); + } + + fn internal() { + assert_eq!(4, internal_adder(2, 2)); + } +} diff --git a/rust-book/testing/tests/common/mod.rs b/rust-book/testing/tests/common/mod.rs new file mode 100755 index 0000000..c00b3a6 --- /dev/null +++ b/rust-book/testing/tests/common/mod.rs @@ -0,0 +1,3 @@ +pub fn setup() { + // setup code +} diff --git a/rust-book/testing/tests/integration_test.rs b/rust-book/testing/tests/integration_test.rs new file mode 100755 index 0000000..ce04ce3 --- /dev/null +++ b/rust-book/testing/tests/integration_test.rs @@ -0,0 +1,9 @@ +use testing; +mod common; + +#[test] +fn it_adds_two() { + common::setup(); + assert_eq!(4, testing::add_two(2)); +} + diff --git a/rust-book/traits/Cargo.lock b/rust-book/traits/Cargo.lock new file mode 100755 index 0000000..3eff52b --- /dev/null +++ b/rust-book/traits/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "traits" +version = "0.1.0" + diff --git a/rust-book/traits/Cargo.toml b/rust-book/traits/Cargo.toml new file mode 100755 index 0000000..461bdcd --- /dev/null +++ b/rust-book/traits/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "traits" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/traits/src/main.rs b/rust-book/traits/src/main.rs new file mode 100755 index 0000000..770caa9 --- /dev/null +++ b/rust-book/traits/src/main.rs @@ -0,0 +1,114 @@ +use std::fmt::Display; + +struct Pair<T> { + x: T, + y: T, +} + +impl<T> Pair<T> { + fn new(x: T, y: T) -> Self { + Self { + x, + y, + } + } +} + +impl<T: Display + PartialOrd> Pair<T> { + fn cmp_display(&self) { + if self.x >= self.y { + println!("{}", self.x); + } + else { + println!("{}", self.y); + } + } +} + +pub trait Summary { + fn summarize(&self) -> String { + format!("(read more from {}...)", self.summarize_author()) + } + + fn summarize_author(&self) -> String; +} + +pub struct NewsArticle { + pub headline: String, + pub location: String, + pub author: String, + pub content: String, +} + +impl Summary for NewsArticle { +// fn summarize(&self) -> String { +// format!("{}, by {} ({})", self.headline, self.author, self.location) +// } + + fn summarize_author(&self) -> String { + format!("{}", self.author) + } + +} + +pub struct Tweet { + pub username: String, + pub content: String, + pub reply: bool, + pub retweet: bool, +} + +impl Summary for Tweet { +// fn summarize(&self) -> String { +// format!("{}: {}", self.username, self.content) +// } + + fn summarize_author(&self) -> String { + format!("@{}", self.username) + } +} + +pub fn notify(item: impl Summary) { + println!("breaking news: {}", item.summarize()); +} + +fn returns_summarizable() -> impl Summary { + + NewsArticle { + headline: String::from("Penguins win the stanley cup championship!"), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from("The pittsburgh penguins are winners I guess."), + } +// Tweet { +// username: String::from("horse_ebooks"), +// content: String::from("of course blargh"), +// reply: false, +// retweet: false, +// } +} + +fn main() { + + let tweet = Tweet { + username: String::from("horse_ebooks"), + content: String::from("of course, as you probably already know, people"), + reply: false, + retweet: false, + }; + + //dbg!(tweet.summarize()); + + let article = NewsArticle { + headline: String::from("Penguins win the stanley cup championship!"), + location: String::from("Pittsburgh, PA, USA"), + author: String::from("Iceburgh"), + content: String::from("The pittsburgh penguins are winners I guess."), + }; + + //dbg!(article.summarize()); + + //notify(tweet); + + returns_summarizable(); +} diff --git a/rust-book/variables/Cargo.lock b/rust-book/variables/Cargo.lock new file mode 100755 index 0000000..6d77f6b --- /dev/null +++ b/rust-book/variables/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "variables" +version = "0.1.0" + diff --git a/rust-book/variables/Cargo.toml b/rust-book/variables/Cargo.toml new file mode 100755 index 0000000..62ee489 --- /dev/null +++ b/rust-book/variables/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "variables" +version = "0.1.0" +authors = ["Adam Carpenter <carpenat@ES.AD.ADP.COM>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/variables/src/main.rs b/rust-book/variables/src/main.rs new file mode 100755 index 0000000..d632530 --- /dev/null +++ b/rust-book/variables/src/main.rs @@ -0,0 +1,6 @@ +fn main() { + let a: [i32; 5] = [1, 2, 3, 4, 5]; + let first = a[0]; + let second = a[1]; + println!("{} {}", first, second); +} diff --git a/rust-book/xmas/Cargo.lock b/rust-book/xmas/Cargo.lock new file mode 100755 index 0000000..033bd72 --- /dev/null +++ b/rust-book/xmas/Cargo.lock @@ -0,0 +1,4 @@ +[[package]] +name = "xmas" +version = "0.1.0" + diff --git a/rust-book/xmas/Cargo.toml b/rust-book/xmas/Cargo.toml new file mode 100755 index 0000000..d10c790 --- /dev/null +++ b/rust-book/xmas/Cargo.toml @@ -0,0 +1,7 @@ +[package] +name = "xmas" +version = "0.1.0" +authors = ["Adam Carpenter <adam.carpenter@adp.com>"] +edition = "2018" + +[dependencies] diff --git a/rust-book/xmas/src/main.rs b/rust-book/xmas/src/main.rs new file mode 100755 index 0000000..e725a26 --- /dev/null +++ b/rust-book/xmas/src/main.rs @@ -0,0 +1,42 @@ +fn main() { + let days = [ + "1st", + "2nd", + "3rd", + "4th", + "5th", + "6th", + "7th", + "8th", + "9th", + "10th", + "11th", + "12th", + ]; + let gifts = [ + "A partridge in a pear tree", + "Two turtle doves and", + "Three French hens", + "Four calling birds", + "Five golden rings", + "Six geese a-laying", + "Seven swans a-swimming", + "Eight maids a-milking", + "Nine ladies dancing", + "Ten lords a-leaping", + "Eleven pipers piping", + "Twelve drummers drumming", + ]; + + // for each day + for mut each in 0..12 { + println!("\nOn the {} day of Christmas,", days[each]); + println!("My true love gave to me"); + + // print associated lyrics + for i in (0..each+1).rev() { + println!("{}", gifts[i]); + } + + } +} |