<repo_name>crollax/Rust<file_sep>/solo/src/ownership.rs
use std::vec;

pub fn run () {
  // let x: u8 = 1;

  // let mut s = String::from("A String");
  // let x = 1;
  // s.pop();

  // println!("{}", s);

  ///////////////////////////////////////////////////
  
  // Compiler will automatically make copies
    /* Rust Stack | Copy types
          bool, character, numbers, slices
          fix sized arrays, touples containing primitives
          function pointers
    */
  let x = 10;
  let y = x;
  let z = x;
  // println!("x = {}", x);
  // println!("y = {}", y);
  // println!("z = {}", z);

  // copy(true);
  // copy("a");
  // copy("a slice");
  // copy(x);
  // copy(String::from("Test")); // causes error
  ///////////////////////////////////////////////////
  
  let mut a = String::from("A String");

  let x = &mut a;
  let y = &mut a;

}

fn copy<T>(t: T) -> T
where // Guard
  T: Copy, // T must ba able to implement Trait Copy
{
  let x = t;
  x
}

fn print(a: u8) {
  println!("value {}", a);
}

fn re(v: Vec<i32>) -> Vec<i32> {
  println!("{}", v[120] + v[111]);
  v
}

fn borrow1(v: &Vec<i32>) {
  // *v == pointer to the ref of the vector arg
  println!("{}", (*v)[10] + (*v)[12]);
}

fn borrow2(v: &Vec<i32>) {
  println!("{}", v[10] + v[11]);
}

fn count(v: &Vec<i32>, val: i32) -> usize {
  v.into_iter().filter(|&&x| x == val).count()
}

pub fn run_2 () {
  let mut v = Vec::new();

  for i in 1..1000 {
    v.push(i);
  }

  // Transfer ownership to re function and then back
  v = re(v);

  println!("Still own v: {} {}", v[0], v[1]);
  
  borrow1(&v);
  println!("Still own v: {} {}", v[0], v[1]);

  borrow2(&v);
  println!("Still own v: {} {}", v[0], v[1]);

  let mut vs = vec![4,5,3,6,7,4,8,6,4,2,4,2,5,3,7,7];
  // Need to sort before dedup
  vs.sort();
  println!("vs sorted: {:?}", &vs);
  // Clone to new set var
  let mut set = vs.clone();
  // Create the set with dedup
  set.dedup();
  println!("set dedup: {:?}", &set);
  println!("vs: {:?}", vs);

  // &i destructures the &{integer} type for i 
  for &i in &set {
    let r = count(&vs, i);
    println!("{} is repeated {} times", i, r);
  }
}<file_sep>/solo/src/traits.rs
trait Shape { 
  fn area(&self) -> u32;
}

struct Rectangle {
  x: u32,
  y: u32,
}

struct Circle {
  radius: f64;
}

impl Shape for Rectangle {
  fn area(&self) -> u32 {
    self.x * self.y
  }
}

impl Shape for Circle {
  fn area(&self) -> u32 {
    (3.141 * self.radius * self.radius) as u32
  }
}

/////////////////////////////////////////////////////////////////////////
// Using generics
/////////////////////////////////////////////////////////////////////////

use std::ops::Mul;
trait Shape_2<T> {
  fn area(&self) -> T;
}

struct Rectangle_2<T: Mul> {
  x: T,
  y: T,
}

// Where T uses mult triat and output must be of type T and implements Copy
impl <T:Mul<Output = T> + Copy> Shape_2<T> for Rectangle_2<T> {
  fn area(&self) -> T {
    self.x * self.y
  }
}

// using copy trait makes all uses set to var a copy
// with clone must use .clone() syntax
#[derive(Debug, Clone, Copy)]
struct A(i32);

// comparison operator traits
#[derive(Eq, PartialEq, PartialOrd, Ord)]
struct B(f32);

trait Iterator {
  type Item;

  fn next(&mut self) -> Option<Self::Item>;
}

pub fn run() {

}<file_sep>/solo/src/main.rs
#![allow(dead_code)]

// mod ipadd;
// mod message;
// mod coin;
// mod restaurant;
// mod trash;
// mod print;
// mod rectangle;
// mod arrays;
// mod vectors;
// mod conditionals;
// mod closures;
// mod minigrep;
// mod linkedlist;
// mod hashmaps;
// mod traits;

// mod ownership;
// mod structs;
// mod loops;
// mod matches;
// mod enums;
// mod options;

mod lifetimes;

fn main() {

    lifetimes::run();
    // closures::test();

    // vectors::run_2();
    // ownership::run_2();
    // structs::run();

    // loops::run();
    // matches::run();
    // enums::run();
    // options::run();

    // arrays::run();
    // vectors::run();
    // vectors::make_vecs();

    // ipadd::ipadd();
    // message::message();
    // coin::coin();
    // trash::option_match();
    // restaurant::eat_at_restaurant();
    // print::run();
    // conditionals::run();
    // closures::run();
    // minigrep::run();
    // linkedlist::run();
    // hashmaps::run();
    // traits::run();
    // rectangle::test_rectangle();

}

<file_sep>/solo/src/hashmaps.rs
// HashMaps
  // Need consistant types


use std::collections::HashMap;

// enum Score {
//   Color,
//   Value
// }

pub fn run () {

  let mut scores = HashMap::new();
  let mut hm = HashMap::new();

  // let mut score = HashMap::new();


  hm.insert(String::from("random"), 12);
  hm.insert(String::from("strings"), 49);

  for (k, v) in &hm {
    println!("{}: {}", k, v);
  }

  // Use get method with key
    // and destruct to gain access to value
  let key = &String::from("random");
  match hm.get(key) {
    Some(&n) => println!("value: {}", n),
    _ => println!("no match"),
  }

  scores.insert(String::from("Blue"), 10);
  scores.insert(String::from("Yellow"), 50);

  println!("HashMap scores {:?}", scores)

}<file_sep>/apts_api/src/main.rs
#![feature(proc_macro_hygiene, decl_macro)]

#[macro_use]
extern crate rocket;
// #[macro_use]
extern crate rocket_contrib;
// #![macro_use]
extern crate mysql;

mod routes;
// mod examples;

// #[database("rocket_app")]
// pub struct DbConn(diesel::MysqlConnection);

fn rocket() -> rocket::Rocket {
  rocket::ignite()
    .mount("/", routes![
      routes::index,
      routes::run_payments,
    ])
    // .attach(DbConn::fairing())
}

fn main() {
  rocket().launch();
}<file_sep>/apts_api/migrations/2019-12-12-154127_create_books/up.sql
-- Your SQL goes here

Create table books (
  id int not null auto_increment,
  title varchar(200) not null,
  author varchar(200) not null,
  published boolean not null default 0,
  PRIMARY KEY(id)
);<file_sep>/apts_api/src/examples/mod.rs
pub mod payments;

pub fn run() {
  payments::run();
}

pub fn run_payments() {
  payments::run();
}<file_sep>/solo/src/options.rs

// Options -> Basic enum type
// enum Option<T> {
//   Some(T),
//   None,
// }

pub fn run () {
  option_match();
}

fn option_match() {
  let five = Some(5);
  let six = plus_one(five);
  let none = plus_one(None);

  println!("{:?}, {:?}, {:?}", five, six, none);
}

fn plus_one(x: Option<i32>) -> Option<i32> {
  match x {
      None => None,
      Some(i) => Some(i + 1),
  }
}<file_sep>/solo/src/restaurant.rs
pub use crate::restaurant::front_of_house::hosting;

pub fn eat_at_restaurant() {
  // front_of_house::hosting::add_to_waitlist();
  hosting::add_to_waitlist();
  front_of_house::serving::take_order("smothered and covered");
  back_of_house::fix_incorrect_order();
  let mut meal = back_of_house::Breakfast::summer("Rye");
  meal.toast = String::from("Wheat");

  println!("I'd like {} toast please", meal.toast);
}


fn plus_one(x: Option<i32>) -> Option<i32> {
  match x {
    None => None,
    Some(i) => Some(i + 1),
  }
}

mod front_of_house {
  pub mod hosting {
    pub fn add_to_waitlist() {
      println!("INSIDE of add_to_waitlist()");
    }

    fn _seat_at_table() {}
  }

  pub mod serving {
    pub fn take_order(order:&str) {
      println!("Taking this order: {}", &order);
    }

    fn _serve_order() {}

    fn _take_payment() {}
  }
}

fn serve_order() {
  println!("INSIDE serve_order()");
}

mod back_of_house {
  pub fn fix_incorrect_order() {
    cook_order();
    super::serve_order();
  }

  fn cook_order() {}
  
  pub struct Breakfast {
    pub toast: String,
    seasonal_fruit: String,
  }

  impl Breakfast {
    pub fn summer(toast:&str) -> Breakfast {
      Breakfast {
        toast: String::from(toast),
        seasonal_fruit: String::from("peaches"),
      }
    }
  }
}

<file_sep>/solo/src/ipadd.rs
pub fn ipadd() {
    let home = IPAddrKind::V4(String::from("127.0.0.1"));
    let loopback = IPAddrKind::V6(String::from("::1"));
}


enum IPAddrKind { // Type
    V4(String),
    V6(String),
}

<file_sep>/apts_api/src/routes.rs
use apts_api::examples;

#[get("/main")]
pub fn index() -> &'static str {
  "Application successfully started!"
}

#[get("/payments")]
pub fn run_payments() -> &'static str {
  examples::run_payments();
  "Payments api call successfully called!"
}<file_sep>/solo/src/pointers.rs
pub fn run () {
  using_ref();
}

fn using_ref () {
    // using ref
    let u = 10;
    // the next two statements are equivlent
    let v = &u;
    let ref z = u;
  
    if z == v {
      println!("They are equal");
    }
}<file_sep>/solo/src/matches.rs
// What if you want to match multiple arms?

//If let or While let
  // Pattern matching
pub fn run_2 () {
  let mut s = Some(0);

  if let Some(i) = s {
    println!("i: {}", i);
  }

  while let Some(i) = s {
    if i > 19 { 
      println!("Quit");
      s = None;
    } else {
      println!("{}", i);
      s = Some(i + 2);
    }
  }
}

pub fn run () {
  // clone_match();
  check_shapes();
}

// Matching on values with no ownership
  // sets value of p to n 
fn clone_match () {
  let p = 0;
  let n = match p {
    n @ 1 ..= 12 => n,
    n @ 13 ..= 19 => n,
    _ => 0,
  };
  println!("n: {}", n)
}

fn guard_match () {
  let pair = (5, -5);
  match pair {
    (x, y) if x == y => println!("Equal"),
    (x, y) if x + y == 0 => println!("Equal Zero"),
    (x, _) if x % 2 == 0 => println!("X is even"),
    _ => println!("No match"),
  }
}

fn touple_match () {
  let pair = (0, -2);
  // Matches on the non var item
    // Binds the var to the other param (destructures the touple)
  match pair {
    (0, y) => println!("y: {}", y),
    (x, 0) => println!("x: {}", x),
     _     => println!("No match"),
  }
}

fn match1 () {
  let x = 10;
  match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    4 => println!("four"),
    5 => println!("five"),
    _ => println!("something else"),
  }
}

fn match2 () {
  let n = 15;
  match n {
    1 => println!("One!"),
    // Conditional check
    2 | 3 | 5 | 7 | 11 => println!("This is a prime"),
    13 ..= 19 => println!("A teen"),
    _ => println!("Ain't special"),
  }
}

enum Shape {
  Rectangle {width: u32, height: u32},
  Square(u32),
  Circle(f64),
}

impl Shape{
  fn area(&self) -> f64 {
    match *self {
      Shape::Rectangle {width, height} => (width * height) as f64,
      Shape::Square(ref s) => (s * s) as f64,
      Shape::Circle(ref r) => 3.14 * (r * r),
    }
  }
}

fn check_shapes () {
  let r = Shape::Rectangle{width: 10, height: 70};
  let s = Shape::Square(10);
  let c = Shape::Circle(4.5);

  let ar = r.area();
  println!("{}", ar);

  let aq = s.area();
  println!("{}", aq);

  let ac = c.area();
  println!("{}", ac);
}


fn option_match() {
  let five = Some(5);
  let six = plus_one(five);
  let none = plus_one(None);

  println!("{:?}, {:?}, {:?}", five, six, none);
}

fn plus_one(x: Option<i32>) -> Option<i32> {
  match x {
    None => None,
    Some(i) => Some(i + 1),
  }
}

// Using a Result enum
use std::fs::File;
fn open_file() {
  let f = File::open("test.txt");
  let f = match f {
    Ok(file) => file,
    Err(error) => {
      panic!("There was a problem opening the file: {:?}", error);
    }
  }
}<file_sep>/solo/src/closures.rs
use std::thread;
use std::time::Duration;

pub fn run () {
  let intensity = 10;
  let random_number = 5;
  generate_workout(intensity, random_number)
}

pub fn test () {
  let f = |i| i + 1;
  let x = 10;
  println!("{}", f(x));

  let p = || println!("This is a closure");
  p();

  let k = create();
  k();

  // Closure inside of an iterator
  let v = vec![1,2,3];
  println!("is 2 in v? {}", v.iter().any(|&x| x != 2));
}

// Using  move here is like using Copy trait
  // as opposed to using a reference (&)
fn create () -> Box<Fn()> {
  Box::new(move || println!("this is a closure in a box!"))
}


pub fn generate_workout(intensity: u32, random_number: u32) {

  let expensive_closure = |num| {
    println!("calculating slowly...");
    thread::sleep(Duration::from_secs(2));
    num
  };

  if intensity < 25 {
    println!("Today do {} pushups!", expensive_closure(intensity));
    println!("Next, do {} situps!", expensive_closure(intensity));
  } 
  else {
    if random_number == 3 {
      println!("Take a break today! Remember to stay hydrated!");
    } 
    else {
      println!("Today, run for {} minutes!", expensive_closure(intensity));
    }
  }

}<file_sep>/solo/src/minigrep.rs
use std::io;

pub fn run() {

  let mut args: Vec<String> = Vec::new();
  let mut age = String::new();


  println!("What is your age?");

  io::stdin().read_line(&mut age)
    .expect("Failed to read line");

  args.push(age);

  println!("{:?}", &args[0]);


}<file_sep>/solo/src/lifetimes.rs

// lifetimes are specified with '
fn pr<'a> (x: &'a str, y: &'a str) -> &'a str {
  if x.len() == y.len() {
    x 
  } else {
    y    
  }
}

pub fn run() {
  let a = "a string";
  let b = "b string";

  // Static lifetimes live for program entirety
    // Should avoid in most cases. Slows program
  let s: &'static str = "The long lasting string";

  let c = pr(a, b);

  println!("{}", c);
}<file_sep>/solo/src/loops.rs

pub fn run () {
  for_loops();
}

fn for_loops () {
  let a = vec![10,20,30,40,50];

  for i in a { 
    println!("i: {}", i);
  }

  // Exclusive ranges
    // ..= -> Inclusive ranges (experimental)
  for i in 1..11 {
    println!("i: {}", i);
  }
}

fn while_loops () {
  let mut n = 10;

  while n != 0 {
    println!("{}!", n);
    n = n - 1;
  }
}

fn named_loops () {
  'a: loop {
    println!("loop a");
    'b: loop {
      println!("loop b");
      'c: loop {
        println!("loop c");

        break 'b
      }
    }
    continue
  }
}

fn loop_value () {
  let x = loop {
    break 10;
  };

  println!("x: {}", x);
}<file_sep>/solo/src/vectors.rs
// Vecs
  // Resizable Arrays
  // Made up of three data points
    // 1) Pointer to the data
    // 2) length
    // 3) Capacity
  // Must have the same type
    // Can use Enums to circumvent

use std::cmp::PartialOrd;

pub fn run () {
  let mut numbers: Vec<i32> = vec![1,2,3,4,5];

  numbers.push(6);

  println!("Vec numbers = {:?}", numbers);
  println!("Vec numbers occupies {} bytes", std::mem::size_of_val(&numbers));

  // must use &(generic) before type [i32]
    // equals whatever size the array is that is set to it
  // &numbers[0(startINDEX)..5(numOfItems)]
  let slice: &[i32] = &numbers[1..3];
  println!("Slice of Vec numbers = {:?}", slice);

  for vec in numbers.iter_mut() {
    *vec *= 2;
  }

  println!("Vec numbers after iter_mut() {:?}", numbers);

  let number_list = vec![34, 50, 25, 100, 65];

  let result = largest(&number_list);
  println!("The largest number is {}", result);
  // let largest = largest(&numbers);
  // println!("Largest item in Vec = {}", largest);

}

#[derive(Debug)]
enum Example {
  Float(f64),
  Int(i32),
  Text(String),
}

pub fn run_2 () {
  let mut v: Vec<i32> = Vec::new();

  for i in &v {
    println!("{}", i);
  }

  println!("{:?} {} {}", &v, v.len(), v.capacity());
  println!("{:?}", v.pop());

  let r = vec![
    Example::Int(142),
    Example::Float(12.32),
    Example::Text(String::from("string")),
  ];
  println!("{:?}", &r);
}

pub fn largest <T: PartialOrd>(list: &[T]) -> &T {
  let mut largest = &list[0];

  for item in list.iter() {
    if &item > &largest {
      largest = &item;
    }
  }

  &largest
}

pub fn make_vecs() {
  println!("-- Making Vecs");
  let mut v = Vec::new();
  v.push("some value");
  v.push("another value");

  let mut v2 = vec![1,2,3];
  v2.push(4);

  println!("v = {:?} and v2 = {:?}", &v, &v2);
}

<file_sep>/apts_api/src/lib.rs
pub mod examples;

<file_sep>/solo/src/helpful_funcs.rs
pub fn run () {

}

fn count(v: &Vec<i32>, val: i32) -> usize {
  v.into_iter().filter(|&&x| x == val).count()
}

fn copy<T>(t: T) -> T
where // Guard
  T: Copy, // T must ba able to implement Trait Copy
{
  let x = t;
  x
}<file_sep>/apts_api/src/main_tst.rs

#[macro_use]
extern crate diesel;

// #[macro_use]
// extern crate diesel_codegen;
extern crate dotenv;

// use dotenv;

use std::env;

mod schema;
mod models;

fn main() {
    // check to see if dotenv file
    dotenv::dotenv().ok();

    let database_url = env::var("DATABASE_URL").expect("set DATABASE_URL");
    let conn = PgConnection::establish(&database_url).unwrap();

    let book = models::NewBook {
        title: String::from("Gravity's Rainbow"),
        author: String::from("<NAME>"),
        published: true,
    };

    if models::Book::insert(book, &conn) {
        println!("success");
    } else {
        println!("failed");
    }
}
<file_sep>/solo/src/arrays.rs
pub fn run () {
  
  let mut numbers: [i32; 5] = [1,2,3,4,5];

  println!("numbers array = {:?}", numbers);
  println!("numbers occupies {} bytes", std::mem::size_of_val(&numbers));

  numbers[2] = 20;

  // must use & (generic) before type [i32]
    // equals whatever size the array is that is set to it
  // &numbers[0(startINDEX)..5(numOfItems)]
  let slice: &[i32] = &numbers[0..5];
  println!("Slice of numbers = {:?}", slice);

}<file_sep>/solo/src/print.rs
pub fn run() {

  println!(
    "{name} likes to play {activity}",
    name = "Charles",
    activity = "lax"
  );

  println!(
    "Binary: {0:b} Hex: {0:x} Octal: {0:o}", 11
  );

  println!("{:?}", (12, true, "hello"));

}<file_sep>/solo/src/conditionals.rs
use std::io;

pub fn run () {

  loop {
    // Get string from input
    let mut age = String::new();
    let check_id: bool = true;
    let mut error: bool = false;

    println!("What is your age?");

    io::stdin().read_line(&mut age)
      .expect("Failed to read line");

    let age: u8 = match age.trim().parse() {
      Ok(num) => num,
      Err(_) => { error = true; 0 },
    };

    if error {
      println!("There was an error");
      continue;
    } 
    else {
      println!("The age you entered is {}", age);
      break;
    }
  }

  
}<file_sep>/apts_api/Cargo.toml
[package]
name = "apts_api"
version = "0.1.0"
authors = ["<NAME> <<EMAIL>>"]
edition = "2018"

# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html

[dependencies]

mysql = "*"

# Powerful date and time functionality
chrono = { version = "0.4.6", features = ["serde"] }

# For connecting with the MySQL database
# diesel = { version = "1.4.2", features = ["chrono"] }

# diesel_codegen = { version = "0.16.1", features = ["mysql"] }
# dotenv = "*"

# Lazy static initialization
lazy_static = "1.3.0"

# Rocket Webserver
# rocket = "0.4.2"
# rocket_contrib = { version = "0.4.0", features = ["json", "diesel_mysql_pool"] }
# rocket_codegen = "*"

rocket = "0.4.2"
rocket_codegen = "*"
rand = "*"

[dependencies.rocket_contrib]
version = "*" # "0.4.0-rc.2" # or use * 
default-features = false
features = ["handlebars_templates", "tera_templates"]



# Serialization/Deserialization
# serde_json = "1.0.39"
# serde = "1.0.90"
# serde_derive = "1.0.90"