clean-up & updating passwordgenerator

This commit is contained in:
Ananke 2018-07-01 20:15:28 +02:00
parent 813150211a
commit b5000277b4
16 changed files with 141 additions and 694 deletions

2
.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
target
Cargo.lock

17
Cargo.toml Normal file
View file

@ -0,0 +1,17 @@
[package]
name = "Rust_Playground"
version = "0.0.1"
authors = [ "Clara Benedicta Maria Mueller <clara.mueller@vilera.de>" ]
[[bin]]
name = "stuff"
path = "/media/win_e/Clara_Daten/etc/Programmierung/Rust/src/passwordgenerator.rs"
[dependencies]
regex = "0.2"
rand = "0.3.15"
getopts = "0.2"
text_io = "0.1.7"

View file

@ -1,49 +0,0 @@
// ownership
// Happy Jesus Respawn! ;D
// main function
fn main() {
// assign vectors
let v1 = vec![1, 2, 3];
let v2 = vec![1, 2, 3];
// use functions
let (v1, v2, answer) = foo(v1, v2);
let answer2 = boo(&v1, &v2);
println!("Answer is: {}", answer);
println!("Second answer is: {}", answer2);
// playing with mutable references
let mut x = 5;
{ // needed for error free compiling
let y = &mut x; // y borrows x here
*y += 1; // '*' needed to access references
}
println!("{}", x); // tries to borrow x here -> only 1 &mut x allowed!
let y = &5; // the same as 'let _y = 5; let y = &_y'
let f = Foo {x: y };
println!("{}", f.x);
}
// functions
fn foo(v1: Vec<i32>, v2: Vec<i32>) -> (Vec<i32>, Vec<i32>, i32) {
// return answer // give back ownership of vectors
(v1, v2, 42)
}
//better version of 'foo' using advantage of borrowing
fn boo(v1: &Vec<i32>, v2: &Vec<i32>) -> i32 {
// give back answer
42
}
// struct -> way for creating more complex data types
struct Foo<'a> { // declaring lifetime 'a
x: &'a i32, // using lifetime 'a
}

35
enum.rs
View file

@ -1,35 +0,0 @@
// enum
//
// main function
fn main() {
// use enums
let x: Message = Message::Move { x: 3, y: 4 };
let y: BoardGameTurn = BoardGameTurn::Move { squares: 1 };
// enum working like function
let m = Message::Write("Hello World".to_string());
let x = foo("Hello World".to_string()); // same as above, using function 'foo()'
// convert vector of strings into vector of Message::Write
let v = vec!["Hello".to_string(), "World".to_string()];
let v1: Vec<Message> = v.into_iter().map(Message::Write).collect();
}
// enmus
enum Message {
Quit,
ChangeColor(i32, i32, i32), // tulpe
Move { x: i32, y: i32 }, // struct
Write(String),
}
enum BoardGameTurn {
Move { squares: i32 },
Pass,
}
//functions
fn foo(x: String) -> Message {
Message::Write(x)
}

View file

@ -1,60 +0,0 @@
// here plays the music!
// Syntax & Semantic
// main function
fn main() {
let x: i32 = 5; // set x unmutable, integer 5
let mut y = 7; // set y mutable 5 (here an integer)
println!("The value of y is: {}", y);
y = 4; // change y
println!("The value of y is: {}", y);
{
println!("The value of x is: {}", x);
let x: i32 = 7; // changing x, only inside loop
println!("The value of x is: {}", x);
}
let y = "I'm a text now!"; // change y again (here as text)
println!("The value of y is: {} ", y);
println!("The value of x is: {}", x);
print_number(88); // call function
sum(3, 5);
let a = add_one(x);
let z = (x + 2);
println!("New values a: {}, z: {}", a, z);
// variable bindings with point to function
let f: fn(i32) -> i32 = add_one; // without type inference
//let f = add_one; // with type inference
let six = f(5); // call function
println!("called function says: {}", six);
}
// declaring function
// function for printing numbers
fn print_number(x: i32) {
println!("x is: {}", x);
}
// function for adding two numbers
fn sum(x: i32, y: i32) {
println!("sum is: {}", x + y); // print sum of numbers
}
// adding 1 to number
fn add_one(i: i32) -> i32 { // -> i32 declairs return of function
i + 1 // here no ';' -> Rust = expression based language
// x + 1; doesn't retourn value
}
// never returning function
fn diverges() -> ! {
panic!("This function never returns!"); // macro -> causes the current thread of execution to crash
}

View file

@ -1,56 +0,0 @@
// another rust programm
// let's get started ^.^
extern crate rand; // actually using rand (declared in dependencies of 'Cargo.toml')
// rust only uses few things by default ('prelude') -> add your needs!
use std::io; // use io library from the standard library
use std::cmp::Ordering; // use ordering type
use rand::Rng; // using rands function rand::thread_rng()
// main function
fn main() {
println!("guess a number!"); // macro, prints string
let secret_number = rand::thread_rng() // get copy of random number generator
.gen_range(1, 101); // methods takes 2 arguments -> generate random number between (inclusive on the lower bound, but exclusive on the upper bound -> 1 - 100)
// println!("The secret number is: {}", secret_number); // print out secret number // just for testing -> runs the game!
loop { // building infinity loop
println!("please input your guess!."); // macro, prints string
let mut guess = String::new(); // let -> create 'variable bindings'; String -> string type (UTF-8 encoded bit of text); '::' -> associate function; 'new()' -> created empty
let foo = 5; // 'foo' is immutable
let mut bar = 5; //'bar' is mutable
io::stdin().read_line(&mut guess) // calling associated function // without std::io -> written 'std::io::stdin()' //returns handle to standard input
// read_line() -> calling method (like associate function, only on parcticular instant of type) an handle
// read_line():&mut guess -> passing argument to mutable reference of guess
.expect("failed to read line"); // io::Result encodes error handling information // not successful -> panic! with message "failed to read line"
// alternative written: 'io::stdin().read_line(&mut guess).expect("failed to read line");'
// let guess: u32 = guess.trim().parse() // 'shadow' guess with new one -> convert string into u32 // 'trim()' eliminates whitespace // 'prase()' -> parses string into number
// .expect("Please type a number!"); // stop programm if not a number
let guess: u32 = match guess.trim().parse() { // 'handling error' -> 'match' instead 'expect()' // result returned by prase()
Ok(num) => num, // success -> set name num on unwrapped Ok value (integer)
Err(_) => continue, // failure -> don't care of kind of error -> catch all _(everything not ok) // 'continue' -> move to next iteration of loop (aka ignore all errors)
};
println!("you guessed: {}", guess); // print out saved string from STDIN
println!("FOO: {} & BAR: {}", foo, bar); // print out string variables
match guess.cmp(&secret_number) { // cmp can called on anything comparable, takes references to thing to compare // returns odering type // match -> determine exactly what typ of ordering (ordering = enum (enumeration)) // guess + secret_number have to be same type for comparision!
Ordering::Less => println!("To small!"), // ordering enum -> 3 possible variants (less/greater/equal)
Ordering::Greater => println!("To big!"),
Ordering::Equal => {
println!("You win!");
break;
}
}
}
}

View file

@ -1,54 +0,0 @@
// loops
//
// main function
fn main() {
// infinity loop
// loop {
// println!("neverending looping!");
// }
let mut x = 5; // mut x: i32
let mut done = false; // mut done: bool
while !done { // looping as long as done == true
x += x - 3; // adding 2 to x
println!("{}", x);
if x % 5 == 0 { // stop looping if x is multiple of 5
done = true;
}
}
// redone of upper while loop -> better way
loop {
x += x - 3; // adding 2 to x
println!("{}", x);
if x % 5 == 0 { // stop looping if x is multiple of 5
break; // break out loop
// return; // will do the same as 'break'
}
}
// for loop
'outer: for y in 0..10 {
'inner: for mut x in 0..10 { // from 0 to 9, 10 (upper bound is exclusive)
x += 1 + x;
if x % 2 == 0 { continue 'inner; } // go to next step inner loop -> only print odd numbers
if y % 2 == 0 { continue 'outer; } // go to next step outer loop
println!("now x is: {} and y is: {}", x, y); // x: i32
}
}
for (index, value) in (5..10).enumerate() {
println!("index = {} value = {}", index, value);
}
let line = "Hello\nWorld!".lines();
for (linenumber, line) in line.enumerate() {
println!("{}: {}", linenumber, line);
}
}

20
main.rs
View file

@ -1,20 +0,0 @@
// don't rust -> restart
#[macro_use] extern crate text_io;
// rust only uses few things by default ('prelude') -> add your needs!
use std::io; // use io library from the standard library
fn main() {
//let n: i32 = read!();
//println!("Read in: {}", n);
//fib (n);
let n: i32 = 1;
fib (n);
}
// Write a function fib which takes a single i32 argument n < 10 and returns n's Fibonacci number (also i32).
fn fib (n:i32) {
println!("{} \n", n);
}

View file

@ -1,67 +0,0 @@
// match
//
// main function
fn main() {
let x = 2;
let a = 1;
match a {
b => println!("a: {} b: {}", a, b), // catches '_' 'any case'
}
match x { // more powerful than if/else
1 => println!("one"), //
2 => println!("two"),
3 => println!("three"),
4 => println!("four"),
_ => println!("something else"), // exhaustiveness checking -> error if not used
}
let number = match x { // use match for variable bindings
1 => "one", // integer converted into string
2 => "two",
3 => "three",
4 => "four",
5 => "five",
_ => "something else",
};
println!("number is: {}", number);
struct Point {
x: i32,
y: i32,
}
let origin = Point { x: 0, y: 0 }
match origin { // deconstruct compound data type
Point { x, y } => println!("({},{})", x, y),
}
}
// enmus
enum Message {
Quit,
ChangeColor(i32, i32, i32), // tulpe
Move { x: i32, y: i32 }, // struct
Write(String),
}
// funtions
fn quit() { /* ... */ }
fn change_color(r: i32, g: i32, b: i32) { /* ... */ }
fn move_cursor(x: i32, y: i32) { /* ... */ }
// process possible variants of enum with match
fn process_message(msg: Message) {
match msg {
Message::Quit => quit(),
Message::ChangeColor(r, g, b) => change_color(r, g, b),
Message::Move { x, y: new_name_for_y } => move_cursor(x, new_name_for_y),
Message::Write(s) => println!("{}", s),
};
}

View file

@ -1,78 +1,135 @@
#![allow(unstable)] // allow unstable libraries
// programm for password generation
// cargo run -- -l 10 -n 2 -s 50
// To-Do
// variable for strength of password
// points for length of pw
// malus for same character, more often -> higher malus
// no special character -> malus
// same case -> malus
// length, special character, different characters, non redundance
// savety check of password
// password strenght by user input
extern crate rand;
extern crate getopts;
use rand::Rng;
// use std::__rand::thread_rng;
use getopts::Options;
use std::env; // use parameters
// functions
// print help menu
fn print_usage(program: &str, opts: Options) {
let brief = format!("Usage: {} FILE [options]", program);
print!("{}", opts.usage(&brief));
}
// create vector containing signs for password
fn filler () -> Vec<char> {
let mut signs : Vec<char> = vec![]; // assign empty vector
// fill vector
for i in 33u8..126u8 {
match i as char { // filtering I, l
'l' => continue,
'I' => continue,
'O' => continue,
'°' => continue,
'²' => continue,
'³' => continue,
'€' => continue,
_ => signs.push(i as char)
}
}
return signs
}
// creation of passward with certain length
fn pw (pass_length: &i32, signs: &Vec<char>) -> String {
let mut password = String::new(); // assign password as empty string
let mut rng = rand::thread_rng(); // instance of thread; rng = random number generator (object)
for _ in 0..*pass_length {
//password.push(rng.choose(&signs).unwrap()); // get only password
let w = (*(rng.choose(&signs).unwrap()));
//password.push(*(rng.choose(&signs).unwrap())); // * for derefernces for processing
password.push(w);
}
return password
}
// main function
fn main() {
// variables
let mut pass_length: i32 = 8; // length of password
let mut number: i32 = 1; // set number of created passwords
let mut limit = 20; // set score threshold for password
let mut score = 0; // score for password quality
// variable for length of password
let pass_length: i32 = 8;
let mut password = String::new(); // assign password as empty string
let mut rng = rand::thread_rng(); // instance of thread; rng = random number generator (object)
// parameters
//let args: Vec<String> = std::env::args().skip(1).collect(); // skip() -> skip programm call
let args: Vec<String> = std::env::args().collect();
let program = args[0].clone();
// variable for strength of password
// length, special character, different characters, non redundance
// create new option object
let mut opts = Options::new();
opts.optopt("l", "length", "set length of password [default: 8]", "LENGTH");
opts.optopt("n", "number", "set number of created passwords [default: 1]", "NUMBER");
opts.optopt("s", "score", "set score of password", "SCORE");
opts.optflag("h", "help", "print this help menu");
let matches = match opts.parse(&args[1..]) {
Ok(m) => { m }
Err(f) => { panic!(f.to_string()) }
};
// print help menu??
if matches.opt_present("h") {
print_usage(&program, opts);
return;
}
pass_length = matches.opt_str("l").unwrap().parse::<i32>().unwrap(); // unwrap Options<String> from opt_str -> convert into int // unwrap_or(String::from())
number = matches.opt_str("n").unwrap().parse::<i32>().unwrap();
score = matches.opt_str("s").unwrap().parse::<i32>().unwrap();
println!("Password length: {}, Number of passwords: {}, Score of Password: {}", pass_length, number, score);
score += pass_length;
// assign array with (ascii) signs
let mut signs : Vec<char> = vec![];
let mut signs : Vec<char> = filler();
// fill vector
for i in 33u8..126u8 {
signs.push(i as char);
// create n passwords
for x in 0..number {
// create password
let password = pw(&pass_length, &signs);
//let mut control = String::new();
let mut control: char = password.chars().next().unwrap(); // get first element of string
println!("first {}", control);
for c in password.chars() {
// c already used?
match c {
control => println!("{} is already in use -> {}", c, control),
_ => println!("{} is new, not {}", c, control),
}
// same character more times in a row?
// different cases
println!("{} vs {}", control, c);
//control.push(c.clone());
control = c;
}
// we have a password
println!("password is: {}", password);
}
// looping -> creation of password
for _ in 0..pass_length {
//password.push(rng.choose(&signs).unwrap()); // get only password
password.push(*(rng.choose(&signs).unwrap())); // * for derefernces for processing
}
// we have a password
println!("password is: {}", password);
// create random number between (range array elements)
// from number of array element -> password
// create password
// let s = rand::thread_rng()
// .gen_ascii_chars() // generate ASCII signs
// .take(pass_length) // take signs for password
// .collect::<String>();
// print out password
// println!("random string: {}", s);
// assign variable for password
// let mut str = String::new();
// create password
// for _ in () {
// str.push(rand::random::<u8>() as char); // push character to string str
// }
// assing counter
// let mut i: i32 = 0;
// for (i = 0, i < pass_length, i++) {
// str.push(rand::random::<u8>() as char);
// }
// let choices = [33..126];
// let mut rstr = String::new();
// let mut rng = rand::thread_rng();
// for _ in 0..8 {
// rstr.push((rng.choose(&choices).unwrap() as u8) as char); // Return a random element from values
// }
}

View file

@ -1,44 +0,0 @@
// patterns
// f*up life..
// main function
fn main() {
// assign tuple
let tuple: (u32, String) = (5, String::from("five"));
// move string -> move tiple
let (x, _s) = tuple;
// gives error because tuple is moved
// println!("Tuple is: {:?}", tuple);
let tuple = (5, String::from("five"));
// tuple is not moved -> u32 is a copy
let (x, _) = tuple;
// works
println!("Tuple is: {:?}", tuple);
let x = 1;
match x { // bind values to names
e @ 1 ... 5 => println!("got a range element {}", e),
_ => println!("anything"),
}
#[derive(Debug)] // compiler -> basic implementations for some traits via the #[derive] attribute, traits can manually implemented
struct Person {
name: Option<String>,
}
let name = "Steve".to_string();
let x: Option<Person> = Some(Person { name: Some(name) };
match x {
Some(Person { name: ref a @ Some(_), .. }) => println!("{:?}", a),
_ => {}
}
}

View file

@ -1,79 +0,0 @@
// struct
// snowy eastern oO
// main function
fn main() {
// creating complex data type
let origin_x = 0;
let origin_y = 0;
let origin = Point { x: 0, y: 0 }; // origin: Point
println!("The origin is at ({}, {})", origin.x, origin.y);
let mut point = Point { x: 0, y: 0 };
point.x = 5; // excess field by name
println!("The point is at ({}, {})", point.x, point.y);
{
let r = PointRef { x: &mut point.x, y: &mut point.y };
*r.x = 5;
*r.y = 6;
}
assert_eq!(5, point.x); // 'assert_eq' -> assert two expression are equal
assert_eq!(6, point.y);
let mut point3d = Point3d { x: 0, y: 0, z: 0 };
// point3d = { x: 1, .. point3d }; // gives point a new y, but keeps x and z // doesn't work anymore
// making new point
// let point_new = Point3d { z: 1, x: 2, .. origin };
// assigning color black (tuple struct)
let black = Color(0, 0, 0); // not the same type as 'let origin = Point(0, 0, 0)'
let origin = Point2(0, 0, 0);
// tuple struct with only one element -> 'newtype'
let length = Inches(10);
let Inches(inter_length) = length; // extract inner integer typ
let inter_length2 = length.0; // does the same as aboves
println!("length is {} inches", inter_length);
}
// combine two single data types into one
struct Point { // struct for creatiting 2D point
x: i32, // could use 'let' here
y: i32,
}
// structure with reference pointer
struct PointRef<'a> {
x: &'a mut i32,
y: &'a mut i32,
}
// structure for 3D points
struct Point3d {
x: i32,
y: i32,
z: i32,
}
// tuple struct
//struct Color(i32, i32, i32);
struct Point2(i32, i32, i32);
struct Inches(i32);
// struct -> clearer
struct Color {
red: i32, // actually names instead positions
blue: i32,
green: i32,
}

View file

@ -1,60 +0,0 @@
// here plays the music!
// Syntax & Semantic
// main function
fn main() {
let x: i32 = 5; // set x unmutable, integer 5
let mut y = 7; // set y mutable 5 (here an integer)
println!("The value of y is: {}", y);
y = 4; // change y
println!("The value of y is: {}", y);
{
println!("The value of x is: {}", x);
let x: i32 = 7; // changing x, only inside loop
println!("The value of x is: {}", x);
}
let y = "I'm a text now!"; // change y again (here as text)
println!("The value of y is: {} ", y);
println!("The value of x is: {}", x);
print_number(88); // call function
sum(3, 5);
let a = add_one(x);
let z = (x + 2);
println!("New values a: {}, z: {}", a, z);
// variable bindings with point to function
let f: fn(i32) -> i32 = add_one; // without type inference
//let f = add_one; // with type inference
let six = f(5); // call function
println!("called function says: {}", six);
}
// declaring function
// function for printing numbers
fn print_number(x: i32) {
println!("x is: {}", x);
}
// function for adding two numbers
fn sum(x: i32, y: i32) {
println!("sum is: {}", x + y); // print sum of numbers
}
// adding 1 to number
fn add_one(i: i32) -> i32 { // -> i32 declairs return of function
i + 1 // here no ';' -> Rust = expression based language
// x + 1; doesn't retourn value
}
// never returning function
fn diverges() -> ! {
panic!("This function never returns!"); // macro -> causes the current thread of execution to crash
}

View file

@ -1,9 +0,0 @@
// play & learning with rust
// aka "rust playground"
// main function
fn main() {
}

View file

@ -1,45 +0,0 @@
// 'primitive' types
// what a sunny easter day - best for programming!
// main function
fn main() {
// assigning tulpes
let mut x = (1, 2); // x: (i32, i32)
let y = (2, 3); // y: (i32, i32)
x = y; // assign tulpe into another
let x1 = x.0; // access first field of tulpe x
let x2 = x.1; // access second field of tulpe x
println!("the first element of x is: {}", x1);
let (a, b, c) = (1, 2, 3,); // access tulpe by destructuring
println!("the value of a is: {}", a);
let d =(0,); // single element tulpe
let z = 7;
// some looping
if z == 5 {
println!("z is five!");
} else if z == 3 {
println!("z is three!");
}
else {
println!("z is not five and not three! :(");
}
// more looping, written differently
let z = 9;
let y = if z == 5 {
10
} else {
15
}; // y: i32
println!("y is defined as: {}", y);
}

View file

@ -1,51 +0,0 @@
// vectors
// jesus respawn is near!
// main function
fn main() {
// assigning vectors
let mut v = vec![1, 2, 3, 4, 5]; // v: vec<i32>
let w = vec![10; 0]; // vector of 10 zeroes
// print particular element of v
println!("the 3. element of v is:{}", v[2]); // counting elements beginning at 0
// index
let i: usize = 0;
// let j: i32 = 0; // doesn't work!
println!("ite element: {}", v[i]);
// handling out of bound errors
match w.get(8) { // use 'get()' or 'get_mut()'
Some(x) => println!("item 7 is: {}", x),
None => println!("Sorry, this vectori is to short!")
}
// iteration of vectors
for i in &v { // using unmutable references
println!("A reference to {}", i);
}
for i in &mut v {
println!("A mutable reference to {}", i);
}
for i in v { // note: you cannot use vector again!
println!("Take ownership of the vector and its elements {}", i);
}
let a = 5; // a: i32
let b = true; // b: bool
let a2 = double(a);
let b2 = change_truth(b);
println!("{}", a); // works, because i32 has no pointer -> copy trait implemented
println!("{}", b); // works -> bool has copy trait
}
// function
fn double(x: i32) -> i32 {
x * 2
}
fn change_truth(x: bool) -> bool {
!x
}