cleanup
rodzic
5125a65e79
commit
e75c66e9c0
|
@ -1,22 +0,0 @@
|
|||
// Task : To explain assignment operations in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main(){
|
||||
// Arithmetic Operations
|
||||
println!("5 + 4 = {}", 5+4 );
|
||||
println!("5 - 4 = {}", 5-4 );
|
||||
println!("5 * 4 = {}", 5*4 );
|
||||
println!("5 / 4 = {}", 5/4 );
|
||||
println!("5 % 4 = {}", 5%4 );
|
||||
|
||||
println!("********************");
|
||||
// Assigning data types and mathematical Operations
|
||||
let neg_4 = -4i32;
|
||||
println!("abs(-4) = {}", neg_4.abs() );
|
||||
println!("abs(-4) = {}", neg_4.pow(2) );
|
||||
println!("round(1.2345) = {}", 1.2354f64.round() );
|
||||
println!("ceil(1.2345) = {}", 1.2345f64.ceil() );
|
||||
print!("sin 3.14 = {}", 3.14f64.sin() );
|
||||
}
|
|
@ -1,17 +0,0 @@
|
|||
// Task : To explain array in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
|
||||
// Defining an array
|
||||
let rand_array = [1,2,3];
|
||||
|
||||
println!("random array {:?}",rand_array );
|
||||
// indexing starts with 0
|
||||
println!("random array 1st element {}",rand_array[0] );
|
||||
println!("random array length {}",rand_array.len() );
|
||||
// last two elements
|
||||
println!("random array {:?}",&rand_array[1..3] );
|
||||
}
|
|
@ -1,31 +0,0 @@
|
|||
use std::io::{self, Write};
|
||||
use std::f64;
|
||||
|
||||
fn main() {
|
||||
println!("Let's print some lines:");
|
||||
println!();
|
||||
println!("Hello, world!");
|
||||
println!("{}, {}!", "Hello", "world");
|
||||
println!("Arguments can be referred to by their position: {0}, {1}! and {1}, {0}! are built from the same arguments", "Hello", "world");
|
||||
|
||||
println!("Furthermore the arguments can be named: \"{greeting}, {object}!\"", greeting = "Hello", object = "World");
|
||||
|
||||
println!("Number formatting: Pi is {0:.3} or {0:.0} for short", f64::consts::PI);
|
||||
|
||||
println!("... and there is more: {0:>0width$}={0:>width$}={0:#x}", 1535, width = 5);
|
||||
print!("Printing without newlines ... ");
|
||||
println!("is great");
|
||||
|
||||
let _ = write!(&mut io::stdout(), "Underneath, it's all writing to a stream...");
|
||||
println!();
|
||||
|
||||
println!("Write something!");
|
||||
let mut input = String::new();
|
||||
if let Ok(n) = io::stdin().read_line(&mut input) {
|
||||
println!("You wrote: {} ({} bytes) ", input, n);
|
||||
}
|
||||
else {
|
||||
eprintln!("There was an error :(");
|
||||
}
|
||||
}
|
||||
|
|
@ -1,14 +0,0 @@
|
|||
// Task : To explain boolean operations in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main(){
|
||||
//Setting boolean and character types
|
||||
let bool_val: bool = true;
|
||||
let x_char: char = 'a';
|
||||
|
||||
// Printing the character
|
||||
println!("x char is {}", x_char);
|
||||
println!("Bool value is {}", bool_val);
|
||||
}
|
|
@ -1,16 +0,0 @@
|
|||
|
||||
pub struct ArithmeticResults{
|
||||
sum: i32,
|
||||
difference: i32,
|
||||
product: i32,
|
||||
quotient: f32,
|
||||
}
|
||||
|
||||
pub fn print_basic_arithmetics(a: i32, b: i32) -> ArithmeticResults {
|
||||
ArithmeticResults {
|
||||
sum: a + b,
|
||||
difference: a - b,
|
||||
product: a * b,
|
||||
quotient: a / b
|
||||
}
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
// Task : To explain assignment operations in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main(){
|
||||
// Prints the first 2 numbers after the decimal points
|
||||
println!("{:.2}",1.2345 );
|
||||
|
||||
println!("================");
|
||||
// print the binary hex and octal format
|
||||
println!("B: {:b} H: {:x} O: {:o}",10,10,10 );
|
||||
|
||||
println!("================");
|
||||
// Shifts
|
||||
println!("{ten:>ws$}",ten=10, ws=5 );
|
||||
println!("{ten:>0ws$}",ten=10, ws=5 );
|
||||
}
|
|
@ -1,20 +0,0 @@
|
|||
mod variables
|
||||
mod mutablility
|
||||
mod numbers
|
||||
mod arithmetics
|
||||
mod strings
|
||||
|
||||
mod arrays
|
||||
mod vectors
|
||||
mod tuples
|
||||
|
||||
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
fn it_works() {
|
||||
assert_eq!(2 + 2, 4);
|
||||
}
|
||||
}
|
|
@ -1,12 +0,0 @@
|
|||
// Task : To explain assignment operations in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main(){
|
||||
let mut sample_var = 10;
|
||||
println!("Value of the sample variable is {}",sample_var);
|
||||
|
||||
let sample_var = 20;
|
||||
println!("New Value of the sample variable is {}",sample_var);
|
||||
}
|
|
@ -1,8 +0,0 @@
|
|||
// Task : Sample program in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
println!("Welcome to Rust Cookbook");
|
||||
}
|
|
@ -1,64 +0,0 @@
|
|||
// Task : To explain string in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
// declaring a random string
|
||||
let rand_string = "I love Rust cookbook <3";
|
||||
|
||||
// printing the length of the string
|
||||
println!("length of the string is {}",rand_string.len() );
|
||||
|
||||
// Splits in string
|
||||
let (first,second) = rand_string.split_at(7);
|
||||
println!("First part : {0} Second part : {1}", first,second );
|
||||
|
||||
// Count using iterator count
|
||||
let count = rand_string.chars().count();
|
||||
print!("count {}",count );
|
||||
|
||||
println!("__________________________");
|
||||
// printing all chars
|
||||
let mut chars = rand_string.chars();
|
||||
let mut indiv_chars = chars.next();
|
||||
|
||||
loop {
|
||||
// Its like switch in c++
|
||||
match indiv_chars {
|
||||
Some(x) => println!("{}",x ),
|
||||
None => break
|
||||
}
|
||||
indiv_chars = chars.next();
|
||||
}
|
||||
|
||||
println!("__________________________");
|
||||
// iterate over whitespaces
|
||||
let mut iter = rand_string.split_whitespace();
|
||||
let mut indiv_word = iter.next();
|
||||
|
||||
loop {
|
||||
// Its like switch in c++
|
||||
match indiv_word {
|
||||
Some(x) => println!("{}",x ),
|
||||
None => break
|
||||
}
|
||||
indiv_word = iter.next();
|
||||
}
|
||||
|
||||
println!("__________________________");
|
||||
// iterate over next line
|
||||
let rand_string2 = "I love \n everything about \n Rust <3";
|
||||
let mut iter_line = rand_string2.lines();
|
||||
let mut indiv_sent = iter_line.next();
|
||||
|
||||
loop {
|
||||
// Its like switch in c++
|
||||
match indiv_sent {
|
||||
Some(x) => println!("{}",x ),
|
||||
None => break
|
||||
}
|
||||
indiv_sent = iter_line.next();
|
||||
}
|
||||
|
||||
}
|
|
@ -1,18 +0,0 @@
|
|||
// Task : To explain tuples in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{i8};
|
||||
|
||||
fn main() {
|
||||
|
||||
// Declaring a tuple
|
||||
let rand_tuple = ("Mozilla Science Lab", 2016);
|
||||
let rand_tuple2 : (&str, i8) = ("Viki",4);
|
||||
|
||||
// tuple operations
|
||||
println!(" Name : {}", rand_tuple2.0);
|
||||
println!(" Lucky no : {}", rand_tuple2.1);
|
||||
|
||||
}
|
|
@ -1,24 +0,0 @@
|
|||
// Task : To explain vector in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
// declaring a vector
|
||||
let mut vec1 = vec![1,2,3,4,5];
|
||||
|
||||
// printing element 3 in vector
|
||||
println!("Item 3 : {}", vec1[2]);
|
||||
|
||||
// iterating in a vector
|
||||
for i in &vec1 {
|
||||
println!("{}",i );
|
||||
}
|
||||
|
||||
// push an element to vector
|
||||
vec1.push(6);
|
||||
println!("vector after push {:?}", vec1 );
|
||||
// pop an element from vector
|
||||
vec1.pop();
|
||||
println!("vector after pop {:?}", vec1 );
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,24 +0,0 @@
|
|||
// Task : To explain variable binding in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 19 Feb 2017
|
||||
|
||||
fn main() {
|
||||
// Simplest variable binding
|
||||
let a = 5;
|
||||
// pattern
|
||||
let (b, c) = (1, 2);
|
||||
// type annotation
|
||||
let x_val: i32 = 5;
|
||||
// shadow example
|
||||
let y_val: i32 = 8;
|
||||
{
|
||||
println!("Value assigned when entering the scope : {}", y_val); // Prints "8".
|
||||
let y_val = 12;
|
||||
println!("Value modified within scope :{}", y_val); // Prints "12".
|
||||
}
|
||||
println!("Value which was assigned first : {}", y_val); // Prints "8".
|
||||
let y_val = 42;
|
||||
println!("New value assigned : {}", y_val); // Prints "42".
|
||||
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,18 +0,0 @@
|
|||
// Task : To explain closures in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{i32};
|
||||
|
||||
fn main() {
|
||||
|
||||
// define a closure
|
||||
let sum_num = |x:i32 , y:i32| x+y;
|
||||
println!("7 + 8 ={}", sum_num(7,8));
|
||||
|
||||
// example 2
|
||||
let num_ten = 10;
|
||||
let add_ten = |x:i32| x+num_ten;
|
||||
println!("3 + 10 ={}", add_ten(3));
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,22 +0,0 @@
|
|||
// Task : To explain condition in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{i32};
|
||||
|
||||
fn main() {
|
||||
let age : i32= 10;
|
||||
|
||||
// If else statements
|
||||
if age <= 18{
|
||||
println!("Go to School");
|
||||
} else if (age >18) && (age <= 28){
|
||||
println!("Go to college");
|
||||
} else {
|
||||
println!("Do something with your life");
|
||||
}
|
||||
|
||||
let can_vote = if (age >= 18) {true} else {false};
|
||||
println!("Can vote {}",can_vote );
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,25 +0,0 @@
|
|||
// Task : To explain constants in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 19 Feb 2017
|
||||
|
||||
// Global variables are declared outside scopes of other function
|
||||
const UPPERLIMIT: i32 = 12;
|
||||
|
||||
// function to check if bunber
|
||||
fn is_big(n: i32) -> bool {
|
||||
// Access constant in some function
|
||||
n > UPPERLIMIT
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let random_number = 15;
|
||||
|
||||
// Access constant in the main thread
|
||||
println!("The threshold is {}", UPPERLIMIT);
|
||||
println!("{} is {}", random_number, if is_big(random_number) { "big" } else { "small" });
|
||||
|
||||
// Error! Cannot modify a `const`.
|
||||
// UPPERLIMIT = 5;
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "custom-iterators"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,366 @@
|
|||
//!
|
||||
//! A simple singly-linked list for the Rust-Cookbook by Packt Publishing.
|
||||
//!
|
||||
//! Recipes covered in this module:
|
||||
//! - Documenting your code
|
||||
//! - Testing your documentation
|
||||
//! - Writing tests and benchmarks
|
||||
//!
|
||||
|
||||
#![feature(test)]
|
||||
#![doc(
|
||||
html_logo_url = "https://blog.x5ff.xyz/img/main/logo.png",
|
||||
test(no_crate_inject, attr(allow(unused_variables), deny(warnings)))
|
||||
)]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Node<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
value: T,
|
||||
next: Link<T>,
|
||||
}
|
||||
|
||||
impl<T> Node<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
fn new(value: T) -> Rc<RefCell<Node<T>>> {
|
||||
Rc::new(RefCell::new(Node {
|
||||
value: value,
|
||||
next: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// A singly-linked list, with nodes allocated on the heap using `Rc`s and `RefCell`s. Here's an image illustrating a linked list:
|
||||
///
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// *Found on https://en.wikipedia.org/wiki/Linked_list*
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// let list = List::new_empty();
|
||||
/// ```
|
||||
///
|
||||
#[derive(Clone)]
|
||||
pub struct List<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
head: Link<T>,
|
||||
tail: Link<T>,
|
||||
|
||||
///
|
||||
/// The length of the list.
|
||||
///
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
impl<T> List<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
///
|
||||
/// Creates a new empty list.
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use custom_iterators::List;
|
||||
/// let list: List<i32> = List::new_empty();
|
||||
/// ```
|
||||
///
|
||||
pub fn new_empty() -> List<T> {
|
||||
List {
|
||||
head: None,
|
||||
tail: None,
|
||||
length: 0,
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Appends a node to the list at the end.
|
||||
///
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This never panics (probably).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No unsafe code was used.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use custom_iterators::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(10);
|
||||
/// ```
|
||||
///
|
||||
pub fn append(&mut self, value: T) {
|
||||
let new = Node::new(value);
|
||||
match self.tail.take() {
|
||||
Some(old) => old.borrow_mut().next = Some(new.clone()),
|
||||
None => self.head = Some(new.clone()),
|
||||
};
|
||||
self.length += 1;
|
||||
self.tail = Some(new);
|
||||
}
|
||||
|
||||
///
|
||||
/// Removes the list's head and returns the result.
|
||||
///
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Whenever when a node unexpectedly is `None`
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use custom_iterators::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(10);
|
||||
/// assert_eq!(list.pop_front(), Some(10));
|
||||
/// ```
|
||||
///
|
||||
pub fn pop_front(&mut self) -> Option<T> {
|
||||
self.head.take().map(|head| {
|
||||
if let Some(next) = head.borrow_mut().next.take() {
|
||||
self.head = Some(next);
|
||||
} else {
|
||||
self.tail.take();
|
||||
}
|
||||
self.length -= 1;
|
||||
Rc::try_unwrap(head)
|
||||
.ok()
|
||||
.expect("Something is terribly wrong")
|
||||
.into_inner()
|
||||
.value
|
||||
})
|
||||
}
|
||||
|
||||
///
|
||||
/// Splits off and returns `n` nodes as a `List<T>`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `n: usize` - The number of elements after which to split the list.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics when:
|
||||
/// - The list is empty
|
||||
/// - `n` is larger than the length
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use custom_iterators::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(12);
|
||||
/// list.append(11);
|
||||
/// list.append(10);
|
||||
/// let mut list2 = list.split(1);
|
||||
/// assert_eq!(list2.pop_front(), Some(12));
|
||||
/// assert_eq!(list.pop_front(), Some(11));
|
||||
/// assert_eq!(list.pop_front(), Some(10));
|
||||
/// ```
|
||||
///
|
||||
pub fn split(&mut self, n: usize) -> List<T> {
|
||||
// Don't do this in real life. Use Results, Options, or anything that
|
||||
// doesn't just kill the program
|
||||
if self.length == 0 || n >= self.length - 1 {
|
||||
panic!("That's not working");
|
||||
}
|
||||
|
||||
let mut n = n;
|
||||
let mut new_list = List::new_empty();
|
||||
while n > 0 {
|
||||
new_list.append(self.pop_front().unwrap());
|
||||
n -= 1;
|
||||
}
|
||||
new_list
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Drop for List<T>
|
||||
where
|
||||
T: Clone + Sized,
|
||||
{
|
||||
fn drop(&mut self) {
|
||||
while self.length > 0 {
|
||||
let n = self.pop_front();
|
||||
drop(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// An iterator for the linked list. Consumes the list.
|
||||
///
|
||||
pub struct ConsumingListIterator<T>
|
||||
where
|
||||
T: Clone + Sized,
|
||||
{
|
||||
list: List<T>,
|
||||
}
|
||||
|
||||
impl<T> ConsumingListIterator<T>
|
||||
where
|
||||
T: Clone + Sized,
|
||||
{
|
||||
///
|
||||
/// Create a new iterator for this list
|
||||
///
|
||||
fn new(list: List<T>) -> ConsumingListIterator<T> {
|
||||
ConsumingListIterator { list: list }
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Iterator for ConsumingListIterator<T>
|
||||
where
|
||||
T: Clone + Sized,
|
||||
{
|
||||
type Item = T;
|
||||
|
||||
fn next(&mut self) -> Option<T> {
|
||||
self.list.pop_front()
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> IntoIterator for List<T>
|
||||
where
|
||||
T: Clone + Sized,
|
||||
{
|
||||
type Item = T;
|
||||
type IntoIter = ConsumingListIterator<Self::Item>;
|
||||
|
||||
fn into_iter(self) -> Self::IntoIter {
|
||||
ConsumingListIterator::new(self)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
extern crate test;
|
||||
use test::Bencher;
|
||||
|
||||
#[bench]
|
||||
fn bench_list_append(b: &mut Bencher) {
|
||||
let mut list = List::new_empty();
|
||||
b.iter(|| {
|
||||
list.append(10);
|
||||
});
|
||||
}
|
||||
|
||||
fn new_list(n: usize, value: Option<usize>) -> List<usize> {
|
||||
let mut list = List::new_empty();
|
||||
for i in 1..=n {
|
||||
if let Some(v) = value {
|
||||
list.append(v);
|
||||
} else {
|
||||
list.append(i);
|
||||
}
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_iterator() {
|
||||
let list = new_list(4, None);
|
||||
assert_eq!(list.length, 4);
|
||||
|
||||
let mut iter = list.into_iter();
|
||||
assert_eq!(iter.next(), Some(1));
|
||||
assert_eq!(iter.next(), Some(2));
|
||||
assert_eq!(iter.next(), Some(3));
|
||||
assert_eq!(iter.next(), Some(4));
|
||||
assert_eq!(iter.next(), None);
|
||||
|
||||
let list = new_list(4, Some(1));
|
||||
assert_eq!(list.length, 4);
|
||||
|
||||
for item in list {
|
||||
assert_eq!(item, 1);
|
||||
}
|
||||
|
||||
let list = new_list(4, Some(1));
|
||||
assert_eq!(list.length, 4);
|
||||
assert_eq!(list.into_iter().fold(0, |s, e| s + e), 4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_new_empty() {
|
||||
let mut list: List<i32> = List::new_empty();
|
||||
assert_eq!(list.length, 0);
|
||||
assert_eq!(list.pop_front(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_append() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_pop_front() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
assert_eq!(list.pop_front(), Some(1));
|
||||
assert_eq!(list.pop_front(), Some(1));
|
||||
assert_eq!(list.pop_front(), Some(1));
|
||||
assert_eq!(list.pop_front(), Some(1));
|
||||
assert_eq!(list.pop_front(), Some(1));
|
||||
assert_eq!(list.length, 0);
|
||||
assert_eq!(list.pop_front(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_split() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
let list2 = list.split(3);
|
||||
assert_eq!(list.length, 2);
|
||||
assert_eq!(list2.length, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_list_split_panics() {
|
||||
let mut list: List<i32> = List::new_empty();
|
||||
let _ = list.split(3);
|
||||
}
|
||||
}
|
BIN
Chapter02/enum
BIN
Chapter02/enum
Plik binarny nie jest wyświetlany.
|
@ -1,32 +0,0 @@
|
|||
// Task : To explain enum in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
|
||||
let hulk = Hero::Strong(100);
|
||||
let fasty = Hero::Fast;
|
||||
//converting from
|
||||
let spiderman = Hero::Info {name:"spiderman".to_owned(),secret:"peter parker".to_owned()};
|
||||
|
||||
get_info(spiderman);
|
||||
get_info(hulk);
|
||||
get_info(fasty);
|
||||
}
|
||||
|
||||
// declaring the enum
|
||||
enum Hero {
|
||||
Fast,
|
||||
Strong(i32),
|
||||
Info {name : String, secret : String}
|
||||
}
|
||||
|
||||
// function to perform for each types
|
||||
fn get_info(h:Hero){
|
||||
match h {
|
||||
Hero::Fast => println!("Fast"),
|
||||
Hero::Strong(i) => println!("Lifts {} tons",i ),
|
||||
Hero::Info {name,secret} => { println!(" name is : {0} secret is : {1}", name,secret);} ,
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "enums"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,91 @@
|
|||
use std::io;
|
||||
|
||||
///
|
||||
/// An enum to encapsulate errors without too much code
|
||||
///
|
||||
pub enum ApplicationError {
|
||||
Code { full: usize, short: u16 },
|
||||
Message(String),
|
||||
IOWrapper(io::Error),
|
||||
Unknown
|
||||
}
|
||||
|
||||
// Even enums can have an implementation!
|
||||
impl ApplicationError {
|
||||
|
||||
///
|
||||
/// A function to quickly write the enum's name somewhere.
|
||||
///
|
||||
pub fn print_kind(&self, mut to: &mut impl io::Write) -> io::Result<()> {
|
||||
// A simple match clause to react to each enum variant
|
||||
let kind = match self {
|
||||
ApplicationError::Code { full: _, short: _ } => "Code",
|
||||
ApplicationError::Unknown => "Unknown",
|
||||
ApplicationError::IOWrapper(_) => "IOWrapper",
|
||||
ApplicationError::Message(_) => "Message"
|
||||
};
|
||||
// the write trait lets us use any implementation and the write! macro
|
||||
// using the question mark operator lets the function return early in
|
||||
// case of an Err() result
|
||||
write!(&mut to, "{}", kind)?;
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// An arbitrary function that simulates work and returns enum variants
|
||||
/// based on the input parameter.
|
||||
///
|
||||
pub fn do_work(choice: i32) -> Result<(), ApplicationError> {
|
||||
if choice < -100 {
|
||||
Err(ApplicationError::IOWrapper(io::Error::from(io::ErrorKind::Other)))
|
||||
} else if choice == 42 {
|
||||
Err(ApplicationError::Code { full: choice as usize, short: (choice % u16::max_value() as i32) as u16 } )
|
||||
} else if choice > 42 {
|
||||
Err(ApplicationError::Message(
|
||||
format!("{} lead to a terrible error", choice)
|
||||
))
|
||||
} else {
|
||||
Err(ApplicationError::Unknown)
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{ApplicationError, do_work};
|
||||
use std::io;
|
||||
|
||||
#[test]
|
||||
fn test_do_work() {
|
||||
let choice = 10;
|
||||
if let Err(error) = do_work(choice) {
|
||||
match error {
|
||||
ApplicationError::Code { full: code, short: _ } => assert_eq!(choice as usize, code),
|
||||
// the following arm matches both variants (OR)
|
||||
ApplicationError::Unknown | ApplicationError::IOWrapper(_) => assert!(choice < 42),
|
||||
ApplicationError::Message(msg) => assert_eq!(format!("{} lead to a terrible error", choice), msg)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_application_error_get_kind() {
|
||||
let mut target = vec![];
|
||||
let _ = ApplicationError::Code { full: 100, short: 100 }.print_kind(&mut target);
|
||||
assert_eq!(String::from_utf8(target).unwrap(), "Code".to_string());
|
||||
|
||||
let mut target = vec![];
|
||||
let _ = ApplicationError::Message("0".to_string()).print_kind(&mut target);
|
||||
assert_eq!(String::from_utf8(target).unwrap(), "Message".to_string());
|
||||
|
||||
let mut target = vec![];
|
||||
let _ = ApplicationError::Unknown.print_kind(&mut target);
|
||||
assert_eq!(String::from_utf8(target).unwrap(), "Unknown".to_string());
|
||||
|
||||
let mut target = vec![];
|
||||
let error = io::Error::from(io::ErrorKind::WriteZero);
|
||||
let _ = ApplicationError::IOWrapper(error).print_kind(&mut target);
|
||||
assert_eq!(String::from_utf8(target).unwrap(), "IOWrapper".to_string());
|
||||
|
||||
}
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,31 +0,0 @@
|
|||
// Task : To explain constants in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 19 Feb 2017
|
||||
|
||||
// main point of execution
|
||||
fn main() {
|
||||
|
||||
// expression
|
||||
let x_val = 5u32;
|
||||
|
||||
// y block
|
||||
let y_val = {
|
||||
let x_squared = x_val * x_val;
|
||||
let x_cube = x_squared * x_val;
|
||||
|
||||
// This expression will be assigned to `y_val`
|
||||
x_cube + x_squared + x_val
|
||||
};
|
||||
|
||||
// z block
|
||||
let z_val = {
|
||||
// The semicolon suppresses this expression and `()` is assigned to `z`
|
||||
2 * x_val;
|
||||
};
|
||||
|
||||
// printing the final outcomes
|
||||
println!("x is {:?}", x_val);
|
||||
println!("y is {:?}", y_val);
|
||||
println!("z is {:?}", z_val);
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "generics"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,183 @@
|
|||
use std::boxed::Box;
|
||||
use std::cmp;
|
||||
use std::ops::Index;
|
||||
|
||||
///
|
||||
/// Minimum size of a dynamic array.
|
||||
///
|
||||
const MIN_SIZE: usize = 10;
|
||||
|
||||
///
|
||||
/// Type declaration for readability.
|
||||
///
|
||||
type Node<T> = Option<T>;
|
||||
|
||||
///
|
||||
/// A dynamic array that can increase in capacity and behaves like
|
||||
/// a list.
|
||||
///
|
||||
pub struct DynamicArray<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
buf: Box<[Node<T>]>,
|
||||
cap: usize,
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
impl<T> DynamicArray<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
///
|
||||
/// Create a new empty dynamic array.
|
||||
///
|
||||
pub fn new_empty() -> DynamicArray<T> {
|
||||
DynamicArray {
|
||||
buf: vec![None; MIN_SIZE].into_boxed_slice(),
|
||||
length: 0,
|
||||
cap: MIN_SIZE,
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// A simple growth strategy, that at least doubles the size
|
||||
/// whenever expansion is needed. Clones old content into the
|
||||
/// new memory.
|
||||
///
|
||||
fn grow(&mut self, min_cap: usize) {
|
||||
let old_cap = self.buf.len();
|
||||
let mut new_cap = old_cap + (old_cap >> 1);
|
||||
|
||||
new_cap = cmp::max(new_cap, min_cap);
|
||||
new_cap = cmp::min(new_cap, usize::max_value());
|
||||
let current = self.buf.clone();
|
||||
self.cap = new_cap;
|
||||
|
||||
self.buf = vec![None; new_cap].into_boxed_slice();
|
||||
self.buf[..current.len()].clone_from_slice(¤t);
|
||||
}
|
||||
|
||||
///
|
||||
/// Append a value to the dynamic array.
|
||||
///
|
||||
pub fn append(&mut self, value: T) {
|
||||
if self.length == self.cap {
|
||||
self.grow(self.length + 1);
|
||||
}
|
||||
self.buf[self.length] = Some(value);
|
||||
self.length += 1;
|
||||
}
|
||||
|
||||
///
|
||||
/// Retrieve an element from a specific position.
|
||||
/// Clones the element.
|
||||
///
|
||||
pub fn at(&mut self, index: usize) -> Node<T> {
|
||||
if self.length > index {
|
||||
self.buf[index].clone()
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T> Index<usize> for DynamicArray<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
type Output = Node<T>;
|
||||
|
||||
fn index(&self, index: usize) -> &Self::Output {
|
||||
if self.length > index {
|
||||
&self.buf[index]
|
||||
} else {
|
||||
&None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Deep copy of the dynamic array.
|
||||
///
|
||||
impl<T> Clone for DynamicArray<T>
|
||||
where
|
||||
T: Sized + Clone,
|
||||
{
|
||||
fn clone(&self) -> Self {
|
||||
DynamicArray {
|
||||
buf: self.buf.clone(),
|
||||
cap: self.cap,
|
||||
length: self.length,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
|
||||
#[test]
|
||||
fn dynamic_array_clone() {
|
||||
let mut list = DynamicArray::new_empty();
|
||||
list.append(3.14);
|
||||
let mut list2 = list.clone();
|
||||
list2.append(42.0);
|
||||
assert_eq!(list[0], Some(3.14));
|
||||
assert_eq!(list[1], None);
|
||||
|
||||
assert_eq!(list2[0], Some(3.14));
|
||||
assert_eq!(list2[1], Some(42.0));
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn dynamic_array_index() {
|
||||
let mut list = DynamicArray::new_empty();
|
||||
list.append(3.14);
|
||||
|
||||
assert_eq!(list[0], Some(3.14));
|
||||
let mut list = DynamicArray::new_empty();
|
||||
list.append("Hello");
|
||||
assert_eq!(list[0], Some("Hello"));
|
||||
assert_eq!(list[1], None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_array_2d_array() {
|
||||
let mut list = DynamicArray::new_empty();
|
||||
let mut sublist = DynamicArray::new_empty();
|
||||
sublist.append(3.14);
|
||||
list.append(sublist);
|
||||
|
||||
assert_eq!(list.at(0).unwrap().at(0), Some(3.14));
|
||||
assert_eq!(list[0].as_ref().unwrap()[0], Some(3.14));
|
||||
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn dynamic_array_append() {
|
||||
let mut list = DynamicArray::new_empty();
|
||||
let max: usize = 1_000;
|
||||
for i in 0..max {
|
||||
list.append(i as u64);
|
||||
}
|
||||
assert_eq!(list.length, max);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn dynamic_array_at() {
|
||||
let mut list = DynamicArray::new_empty();
|
||||
let max: usize = 1_000;
|
||||
for i in 0..max {
|
||||
list.append(i as u64);
|
||||
}
|
||||
assert_eq!(list.length, max);
|
||||
for i in 0..max {
|
||||
assert_eq!(list.at(i), Some(i as u64));
|
||||
}
|
||||
assert_eq!(list.at(max + 1), None);
|
||||
}
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,31 +0,0 @@
|
|||
// Task : To explain struct in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{f64};
|
||||
|
||||
fn main() {
|
||||
// create a struct variable
|
||||
let mut circle1 = Circle {
|
||||
x:10.0,radius : 10.0
|
||||
};
|
||||
|
||||
println!("x:{},radius : {}", circle1.x, circle1.radius );
|
||||
|
||||
println!("x : {}", circle1.get_x());
|
||||
}
|
||||
|
||||
// define your custom user datatype
|
||||
struct Circle {
|
||||
x : f64,
|
||||
radius : f64,
|
||||
}
|
||||
|
||||
// recommended way of creating structs
|
||||
impl Circle {
|
||||
// pub makes this function public which makes it accessible outsite the scope {}
|
||||
pub fn get_x(&self) -> f64 {
|
||||
self.x
|
||||
}
|
||||
}
|
|
@ -0,0 +1,10 @@
|
|||
[package]
|
||||
name = "iteration"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "^0.5"
|
|
@ -0,0 +1,93 @@
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
#[test]
|
||||
fn getting_the_iterator() {
|
||||
let v = vec![10, 10, 10];
|
||||
|
||||
// borrowed iterator (v remains as is)
|
||||
let mut iter = v.iter();
|
||||
assert_eq!(iter.next(), Some(&10));
|
||||
assert_eq!(iter.next(), Some(&10));
|
||||
assert_eq!(iter.next(), Some(&10));
|
||||
assert_eq!(iter.next(), None);
|
||||
|
||||
// owned iterator (consumes v)
|
||||
// this is the same as calling into_iter()
|
||||
for i in v {
|
||||
assert_eq!(i, 10);
|
||||
}
|
||||
}
|
||||
|
||||
fn count_files(path: &String) -> usize {
|
||||
path.len()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_transformations() {
|
||||
let v = vec![10, 10, 10];
|
||||
let hexed = v.iter().map(|i| format!("{:x}", i));
|
||||
assert_eq!(
|
||||
hexed.collect::<Vec<String>>(),
|
||||
vec!["a".to_string(), "a".to_string(), "a".to_string()]
|
||||
);
|
||||
assert_eq!(v.iter().fold(0, |p, c| p + c), 30);
|
||||
|
||||
// as an example: directories and their file count
|
||||
let dirs = vec![
|
||||
"/home/alice".to_string(),
|
||||
"/home/bob".to_string(),
|
||||
"/home/carl".to_string(),
|
||||
"/home/debra".to_string(),
|
||||
];
|
||||
|
||||
// get the no of files with some function
|
||||
// based on the directory name
|
||||
let file_counter = dirs.iter().map(count_files);
|
||||
|
||||
// for easier handling, merge both collections into one
|
||||
let dir_file_counts: Vec<(&String, usize)> = dirs.iter().zip(file_counter).collect();
|
||||
|
||||
// sorry for the messy string handling here ...
|
||||
// "hello" is a &str (a slice) so either we work
|
||||
// with &&str (slice reference) or &String (String reference)
|
||||
// We opted for the latter.
|
||||
assert_eq!(
|
||||
dir_file_counts,
|
||||
vec![
|
||||
(&"/home/alice".to_string(), 11),
|
||||
(&"/home/bob".to_string(), 9),
|
||||
(&"/home/carl".to_string(), 10),
|
||||
(&"/home/debra".to_string(), 11)
|
||||
]
|
||||
)
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn data_filtering() {
|
||||
let data = vec![1, 2, 3, 4, 5, 6, 7, 8];
|
||||
// a simple filter to only get the even elements.
|
||||
// confirmed by an "all" function where a predicate has to apply to all elements
|
||||
assert!(data.iter().filter(|&n| n % 2 == 0).all(|&n| n % 2 == 0));
|
||||
// similarly, find and position can be used to find the *first* occurance of an element
|
||||
assert_eq!(data.iter().find(|&&n| n == 5), Some(&5));
|
||||
assert_eq!(data.iter().find(|&&n| n == 0), None);
|
||||
assert_eq!(data.iter().position(|&n| n == 5), Some(4));
|
||||
|
||||
// we can also simply skip a number of elements
|
||||
assert_eq!(data.iter().skip(1).next(), Some(&2));
|
||||
let mut data_iter = data.iter().take(2);
|
||||
assert_eq!(data_iter.next(), Some(&1));
|
||||
assert_eq!(data_iter.next(), Some(&2));
|
||||
assert_eq!(data_iter.next(), None);
|
||||
|
||||
// another handy use is for splitting data (e.g. for machine learning)
|
||||
// this splits the original Vec<T> into a training (~80%) and validation set (~20%)
|
||||
let (validation, train): (Vec<i32>, Vec<i32>) = data
|
||||
.iter()
|
||||
.partition(|&_| (rand::random::<f32>() % 1.0) > 0.8);
|
||||
|
||||
assert!(train.len() > validation.len());
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "lifetimes"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,163 @@
|
|||
|
||||
///
|
||||
/// Our almost generic statistics toolkit
|
||||
///
|
||||
pub struct StatisticsToolkit<'a> {
|
||||
base: &'a [f64],
|
||||
}
|
||||
|
||||
impl<'a> StatisticsToolkit<'a> {
|
||||
|
||||
///
|
||||
/// Create a new instance if the slice is larger than 2 elements
|
||||
///
|
||||
pub fn new(base: &'a [f64]) -> Option<StatisticsToolkit> {
|
||||
if base.len() < 3 {
|
||||
None
|
||||
} else {
|
||||
Some(StatisticsToolkit { base: base })
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// Computes the variance
|
||||
///
|
||||
pub fn var(&self) -> f64 {
|
||||
let mean = self.mean();
|
||||
|
||||
let ssq: f64 = self.base.iter().map(|i| (i - mean).powi(2)).sum();
|
||||
return ssq / self.base.len() as f64;
|
||||
}
|
||||
|
||||
|
||||
///
|
||||
/// Computes the standard deviation
|
||||
///
|
||||
pub fn std(&self) -> f64 {
|
||||
self.var().sqrt()
|
||||
}
|
||||
|
||||
///
|
||||
/// Computes the arithmetic mean
|
||||
///
|
||||
pub fn mean(&self) -> f64 {
|
||||
let sum: f64 = self.base.iter().sum();
|
||||
|
||||
sum / self.base.len() as f64
|
||||
}
|
||||
|
||||
///
|
||||
/// Computes the median, but clones the base slice for this.
|
||||
///
|
||||
pub fn median(&self) -> f64 {
|
||||
let mut clone = self.base.to_vec();
|
||||
|
||||
// .sort() is not implemented for floats
|
||||
clone.sort_by(|a, b| a.partial_cmp(b).unwrap());
|
||||
|
||||
let m = clone.len() / 2;
|
||||
if clone.len() % 2 == 0 {
|
||||
clone[m]
|
||||
} else {
|
||||
(clone[m] + clone[m - 1]) / 2.0
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// declaring a lifetime is optional here, since the compiler automates this
|
||||
|
||||
///
|
||||
/// Compute the arithmetic mean
|
||||
///
|
||||
pub fn mean<'a>(numbers: &'a [f32]) -> Option<f32> {
|
||||
if numbers.len() > 0 {
|
||||
let sum: f32 = numbers.iter().sum();
|
||||
Some(sum / numbers.len() as f32)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
|
||||
use super::*;
|
||||
|
||||
///
|
||||
/// a normal distribution created with numpy, with mu = 42 and sigma = 3.14
|
||||
///
|
||||
fn numpy_normal_distribution() -> Vec<f64> {
|
||||
vec![
|
||||
43.67221552, 46.40865622, 43.44603147, 43.16162571, 40.94815816,
|
||||
44.585914 , 45.84833022, 37.77765835, 40.23715928, 48.08791899,
|
||||
44.80964938, 42.13753315, 38.80713956, 39.16183586, 42.61511209,
|
||||
42.25099062, 41.2240736 , 44.59644304, 41.27516889, 36.21238554
|
||||
]
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mean_tests() {
|
||||
// testing some aspects of the mean function
|
||||
assert_eq!(mean(&vec![1.0, 2.0, 3.0]), Some(2.0));
|
||||
assert_eq!(mean(&vec![]), None);
|
||||
assert_eq!(mean(&vec![0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0]), Some(0.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statisticstoolkit_new() {
|
||||
// require >= 3 elements in an array for a plausible normal distribution
|
||||
assert!(StatisticsToolkit::new(&vec![]).is_none());
|
||||
assert!(StatisticsToolkit::new(&vec![2.0, 2.0]).is_none());
|
||||
|
||||
// a working example
|
||||
assert!(StatisticsToolkit::new(&vec![1.0, 2.0, 1.0]).is_some());
|
||||
|
||||
// not a normal distribution, but we don't mind
|
||||
assert!(StatisticsToolkit::new(&vec![2.0, 1.0, 2.0]).is_some());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn statisticstoolkit_statistics() {
|
||||
// simple best case test
|
||||
let a_sample = vec![1.0, 2.0, 1.0];
|
||||
let nd = StatisticsToolkit::new(&a_sample).unwrap();
|
||||
assert_eq!(nd.var(), 0.2222222222222222);
|
||||
assert_eq!(nd.std(), 0.4714045207910317);
|
||||
assert_eq!(nd.mean(), 1.3333333333333333);
|
||||
assert_eq!(nd.median(), 1.0);
|
||||
|
||||
// no variance
|
||||
let a_sample = vec![1.0, 1.0, 1.0];
|
||||
let nd = StatisticsToolkit::new(&a_sample).unwrap();
|
||||
assert_eq!(nd.var(), 0.0);
|
||||
assert_eq!(nd.std(), 0.0);
|
||||
assert_eq!(nd.mean(), 1.0);
|
||||
assert_eq!(nd.median(), 1.0);
|
||||
|
||||
|
||||
// double check with a real libray
|
||||
let a_sample = numpy_normal_distribution();
|
||||
let nd = StatisticsToolkit::new(&a_sample).unwrap();
|
||||
assert_eq!(nd.var(), 8.580276516670548);
|
||||
assert_eq!(nd.std(), 2.9292109034124785);
|
||||
assert_eq!(nd.mean(), 42.36319998250001);
|
||||
assert_eq!(nd.median(), 42.61511209);
|
||||
|
||||
|
||||
// skewed distribution
|
||||
let a_sample = vec![1.0, 1.0, 5.0];
|
||||
let nd = StatisticsToolkit::new(&a_sample).unwrap();
|
||||
assert_eq!(nd.var(), 3.555555555555556);
|
||||
assert_eq!(nd.std(), 1.8856180831641267);
|
||||
assert_eq!(nd.mean(), 2.3333333333333335);
|
||||
assert_eq!(nd.median(), 1.0);
|
||||
|
||||
// median with even collection length
|
||||
let a_sample = vec![1.0, 2.0, 3.0, 4.0] ;
|
||||
let nd = StatisticsToolkit::new(&a_sample).unwrap();
|
||||
assert_eq!(nd.var(), 1.25);
|
||||
assert_eq!(nd.std(), 1.118033988749895);
|
||||
assert_eq!(nd.mean(), 2.5);
|
||||
assert_eq!(nd.median(), 3.0);
|
||||
}
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,43 +0,0 @@
|
|||
// Task : To explain looping in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
fn main() {
|
||||
|
||||
// mutuable variable whose value can be changed
|
||||
let mut x =1;
|
||||
println!(" Loop even numbers ");
|
||||
// Continously loops
|
||||
loop {
|
||||
// Check if x is an even number or not
|
||||
if (x % 2 == 0){
|
||||
println!("{}",x);
|
||||
x += 1;
|
||||
// goes to the loop again
|
||||
continue;
|
||||
}
|
||||
// exit if the number is greater than 10
|
||||
if (x > 10) {
|
||||
break;
|
||||
}
|
||||
// increment the number when not even
|
||||
x+=1;
|
||||
}
|
||||
|
||||
let mut y = 1;
|
||||
// while loop
|
||||
println!("while 1 to 9 ");
|
||||
while y < 10 {
|
||||
println!("{}",y );
|
||||
y +=1;
|
||||
}
|
||||
|
||||
let mut z = 1;
|
||||
//for loop
|
||||
println!(" For 1 to 9");
|
||||
for z in 1 .. 10 {
|
||||
println!("{}",z );
|
||||
}
|
||||
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "mut-sharing-ownership"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,149 @@
|
|||
#![feature(test)]
|
||||
|
||||
//pub mod list;
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
extern crate test;
|
||||
use test::Bencher;
|
||||
|
||||
#[bench]
|
||||
fn bench_regular_push(b: &mut Bencher) {
|
||||
let mut v = vec![];
|
||||
b.iter(|| {
|
||||
for _ in 0..1_000 {
|
||||
v.push(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_refcell_push(b: &mut Bencher) {
|
||||
let v = RefCell::new(vec![]);
|
||||
b.iter(|| {
|
||||
for _ in 0..1_000 {
|
||||
v.borrow_mut().push(10);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_cell_push(b: &mut Bencher) {
|
||||
let v = Cell::new(vec![]);
|
||||
b.iter(|| {
|
||||
for _ in 0..1_000 {
|
||||
let mut vec = v.take();
|
||||
vec.push(10);
|
||||
v.set(vec);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
use std::borrow::Cow;
|
||||
use std::ptr::eq;
|
||||
|
||||
fn min_sum_cow(min: i32, v: &mut Cow<[i32]>) {
|
||||
let sum: i32 = v.iter().sum();
|
||||
if sum < min {
|
||||
v.to_mut().push(min - sum);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn handling_cows() {
|
||||
let v = vec![10, 20, 30];
|
||||
|
||||
// cows - Copy on Writes - encapsulate the cloning process
|
||||
// we'll wrap the Vec<T> into a Cow
|
||||
let mut cow = Cow::from(&v);
|
||||
|
||||
// the memory locations are now the same
|
||||
assert!(eq(&v[..], &*cow));
|
||||
|
||||
// ... until we pass it mutably into a mutating function
|
||||
min_sum_cow(70, &mut cow);
|
||||
|
||||
// on some cases, the Cow will NOT contain the
|
||||
// original value!
|
||||
assert_eq!(v, vec![10, 20, 30]);
|
||||
assert_eq!(cow, vec![10, 20, 30, 10]);
|
||||
|
||||
// both pointers are not equal either
|
||||
assert!(!eq(&v[..], &*cow));
|
||||
|
||||
// retrieve the owned value. this is a clone operation
|
||||
let v2 = cow.into_owned();
|
||||
|
||||
// let's repeat without mutation
|
||||
let mut cow2 = Cow::from(&v2);
|
||||
min_sum_cow(70, &mut cow2);
|
||||
|
||||
// they are now equal ...
|
||||
assert_eq!(cow2, v2);
|
||||
|
||||
// ... and point to the same memory location
|
||||
assert!(eq(&v2[..], &*cow2));
|
||||
}
|
||||
|
||||
use std::cell::{Cell, RefCell};
|
||||
|
||||
fn min_sum_refcell(min: i32, v: &RefCell<Vec<i32>>) {
|
||||
let sum: i32 = v.borrow().iter().sum();
|
||||
if sum < min {
|
||||
v.borrow_mut().push(min - sum);
|
||||
}
|
||||
}
|
||||
|
||||
fn min_sum_cell(min: i32, v: &Cell<Vec<i32>>) {
|
||||
// we first take the Vec<T> ownership
|
||||
let mut vec = v.take();
|
||||
|
||||
// work with it ...
|
||||
let sum: i32 = vec.iter().sum();
|
||||
|
||||
// change if needed
|
||||
if sum < min {
|
||||
vec.push(min - sum);
|
||||
}
|
||||
// then we put it back! no mut required
|
||||
v.set(vec);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn about_cells() {
|
||||
// we allocate memory and use a RefCell to dynamically
|
||||
// manage ownership
|
||||
let ref_cell = RefCell::new(vec![10, 20, 30]);
|
||||
|
||||
// mutable borrows are fine,
|
||||
min_sum_refcell(70, &ref_cell);
|
||||
|
||||
// they are equal!
|
||||
assert!(ref_cell.borrow().eq(&vec![10, 20, 30, 10]));
|
||||
|
||||
// cells are a bit different
|
||||
let cell = Cell::from(vec![10, 20, 30]);
|
||||
|
||||
// pass the immutable cell into the function
|
||||
min_sum_cell(70, &cell);
|
||||
|
||||
// unwrap
|
||||
let v = cell.into_inner();
|
||||
|
||||
// check the contents, and they changed!
|
||||
assert_eq!(v, vec![10, 20, 30, 10]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn failing_cells() {
|
||||
let ref_cell = RefCell::new(vec![10, 20, 30]);
|
||||
|
||||
// multiple borrows are fine
|
||||
let _v = ref_cell.borrow();
|
||||
min_sum_refcell(60, &ref_cell);
|
||||
|
||||
// ... until they are mutable borrows
|
||||
min_sum_refcell(70, &ref_cell); // panics!
|
||||
}
|
||||
}
|
|
@ -0,0 +1,261 @@
|
|||
//!
|
||||
//! A simple singly-linked list for the Rust-Cookbook by Packt Publishing.
|
||||
//!
|
||||
//! Recipes covered in this module:
|
||||
//! - Documenting your code
|
||||
//! - Testing your documentation
|
||||
//! - Writing tests and benchmarks
|
||||
//!
|
||||
|
||||
|
||||
#![doc(html_logo_url = "https://blog.x5ff.xyz/img/main/logo.png",
|
||||
test(no_crate_inject, attr(allow(unused_variables), deny(warnings))))]
|
||||
|
||||
use std::cell::RefCell;
|
||||
use std::rc::Rc;
|
||||
|
||||
type Link<T> = Option<Rc<RefCell<Node<T>>>>;
|
||||
|
||||
#[derive(Clone)]
|
||||
struct Node<T> where T: Sized + Clone {
|
||||
value: T,
|
||||
next: Link<T>,
|
||||
}
|
||||
|
||||
|
||||
impl<T> Node<T> where T: Sized + Clone {
|
||||
fn new(value: T) -> Rc<RefCell<Node<T>>> {
|
||||
Rc::new(RefCell::new(Node {
|
||||
value: value,
|
||||
next: None,
|
||||
}))
|
||||
}
|
||||
}
|
||||
|
||||
///
|
||||
/// A singly-linked list, with nodes allocated on the heap using `Rc`s and `RefCell`s. Here's an image illustrating a linked list:
|
||||
///
|
||||
///
|
||||
/// 
|
||||
///
|
||||
/// *Found on https://en.wikipedia.org/wiki/Linked_list*
|
||||
///
|
||||
/// # Usage
|
||||
///
|
||||
/// ```ignore
|
||||
/// let list = List::new_empty();
|
||||
/// ```
|
||||
///
|
||||
#[derive(Clone)]
|
||||
pub struct List<T> where T: Sized + Clone {
|
||||
head: Link<T>,
|
||||
tail: Link<T>,
|
||||
|
||||
///
|
||||
/// The length of the list.
|
||||
///
|
||||
pub length: usize,
|
||||
}
|
||||
|
||||
impl<T> List<T> where T: Sized + Clone {
|
||||
|
||||
///
|
||||
/// Creates a new empty list.
|
||||
///
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use mut_sharing_ownership::list::List;
|
||||
/// let list: List<i32> = List::new_empty();
|
||||
/// ```
|
||||
///
|
||||
pub fn new_empty() -> List<T> {
|
||||
List { head: None, tail: None, length: 0 }
|
||||
}
|
||||
|
||||
///
|
||||
/// Appends a node to the list at the end.
|
||||
///
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// This never panics (probably).
|
||||
///
|
||||
/// # Safety
|
||||
///
|
||||
/// No unsafe code was used.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// use mut_sharing_ownership::list::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(10);
|
||||
/// ```
|
||||
///
|
||||
pub fn append(&mut self, value: T) {
|
||||
let new = Node::new(value);
|
||||
match self.tail.take() {
|
||||
Some(old) => old.borrow_mut().next = Some(new.clone()),
|
||||
None => self.head = Some(new.clone())
|
||||
};
|
||||
self.length += 1;
|
||||
self.tail = Some(new);
|
||||
}
|
||||
|
||||
///
|
||||
/// Removes the list's head and returns the result.
|
||||
///
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Whenever when a node unexpectedly is `None`
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use mut_sharing_ownership::list::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(10);
|
||||
/// assert_eq!(list.pop(), Some(10));
|
||||
/// ```
|
||||
///
|
||||
pub fn pop(&mut self) -> Option<T> {
|
||||
self.head.take().map(|head| {
|
||||
if let Some(next) = head.borrow_mut().next.take() {
|
||||
self.head = Some(next);
|
||||
} else {
|
||||
self.tail.take();
|
||||
}
|
||||
self.length -= 1;
|
||||
Rc::try_unwrap(head)
|
||||
.ok()
|
||||
.expect("Something is terribly wrong")
|
||||
.into_inner()
|
||||
.value
|
||||
})
|
||||
}
|
||||
|
||||
|
||||
///
|
||||
/// Splits off and returns `n` nodes as a `List<T>`.
|
||||
///
|
||||
/// # Arguments
|
||||
///
|
||||
/// `n: usize` - The number of elements after which to split the list.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics when:
|
||||
/// - The list is empty
|
||||
/// - `n` is larger than the length
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use mut_sharing_ownership::list::List;
|
||||
///
|
||||
/// let mut list = List::new_empty();
|
||||
/// list.append(12);
|
||||
/// list.append(11);
|
||||
/// list.append(10);
|
||||
/// let mut list2 = list.split(1);
|
||||
/// assert_eq!(list2.pop(), Some(12));
|
||||
/// assert_eq!(list.pop(), Some(11));
|
||||
/// assert_eq!(list.pop(), Some(10));
|
||||
/// ```
|
||||
///
|
||||
pub fn split(&mut self, n: usize) -> List<T> {
|
||||
|
||||
// Don't do this in real life. Use Results, Options, or anything that
|
||||
// doesn't just kill the program
|
||||
if self.length == 0 || n >= self.length - 1 {
|
||||
panic!("That's not working");
|
||||
}
|
||||
|
||||
let mut n = n;
|
||||
let mut new_list = List::new_empty();
|
||||
while n > 0 {
|
||||
new_list.append(self.pop().unwrap());
|
||||
n -= 1;
|
||||
}
|
||||
new_list
|
||||
}
|
||||
}
|
||||
|
||||
impl <T>Drop for List<T> where T: Clone + Sized {
|
||||
|
||||
fn drop(&mut self) {
|
||||
while self.length > 0 {
|
||||
let n = self.pop();
|
||||
drop(n);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn test_list_new_empty() {
|
||||
let mut list: List<i32> = List::new_empty();
|
||||
assert_eq!(list.length, 0);
|
||||
assert_eq!(list.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_append() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn test_list_pop() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.pop(), Some(1));
|
||||
assert_eq!(list.length, 0);
|
||||
assert_eq!(list.pop(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_list_split() {
|
||||
let mut list = List::new_empty();
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
list.append(1);
|
||||
assert_eq!(list.length, 5);
|
||||
let list2 = list.split(3);
|
||||
assert_eq!(list.length, 2);
|
||||
assert_eq!(list2.length, 3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn test_list_split_panics() {
|
||||
let mut list: List<i32> = List::new_empty();
|
||||
let _ = list.split(3);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "not-null"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,81 @@
|
|||
#[cfg(test)]
|
||||
mod tests {
|
||||
#[test]
|
||||
#[should_panic]
|
||||
fn option_unwrap() {
|
||||
// Options to unwrap Options
|
||||
assert_eq!(Some(10).unwrap(), 10);
|
||||
assert_eq!(None.unwrap_or(10), 10);
|
||||
assert_eq!(None.unwrap_or_else(|| 5 * 2), 10);
|
||||
|
||||
// panic ensues
|
||||
// Explicitly type None to an Option<i32>
|
||||
// expect is always preferred since it has a message attached
|
||||
Option::<i32>::None.unwrap();
|
||||
Option::<i32>::None.expect("Better say something when panicking");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_working_with_values() {
|
||||
let mut o = Some(42);
|
||||
|
||||
// take the value out and replace it with None
|
||||
let nr = o.take();
|
||||
assert!(o.is_none());
|
||||
// nr now holds an option containing the value
|
||||
assert_eq!(nr, Some(42));
|
||||
|
||||
let mut o = Some(42);
|
||||
// sometimes it's better to replace the value right away
|
||||
assert_eq!(o.replace(1535), Some(42));
|
||||
assert_eq!(o, Some(1535));
|
||||
|
||||
let o = Some(1535);
|
||||
// the map() function works only on Some() values (not None)
|
||||
assert_eq!(o.map(|v| format!("{:#x}", v)), Some("0x5ff".to_owned()));
|
||||
|
||||
let o = Some(1535);
|
||||
// Options can be transformed into a Result easily. "Nope" is the Err()
|
||||
// value for the new Result.
|
||||
match o.ok_or("Nope") {
|
||||
Ok(nr) => assert_eq!(nr, 1535),
|
||||
Err(_) => assert!(false),
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_sequentials() {
|
||||
// Options have a range of abilities and sometimes even behave like sequences
|
||||
let a = Some(42);
|
||||
let b = Some(1535);
|
||||
// boolean logic with options. Note the returned values
|
||||
assert_eq!(a.and(b), Some(1535));
|
||||
assert_eq!(a.and(Option::<i32>::None), None);
|
||||
assert_eq!(a.or(None), Some(42));
|
||||
assert_eq!(a.or(b), Some(42));
|
||||
assert_eq!(None.or(a), Some(42));
|
||||
|
||||
// chain together Option instances to skip tedious unwrapping
|
||||
let new_a = a.and_then(|v| Some(v + 100)).filter(|&v| v != 42);
|
||||
|
||||
// iterate over Options
|
||||
assert_eq!(new_a, Some(142));
|
||||
let mut a_iter = new_a.iter();
|
||||
assert_eq!(a_iter.next(), Some(&142));
|
||||
assert_eq!(a_iter.next(), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn option_pattern_matching() {
|
||||
match Some(100) {
|
||||
Some(v) => assert_eq!(v, 100),
|
||||
None => assert!(false),
|
||||
};
|
||||
|
||||
if let Some(v) = Some(42) {
|
||||
assert_eq!(v, 42);
|
||||
} else {
|
||||
assert!(false);
|
||||
}
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "pattern-matching"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,136 @@
|
|||
|
||||
enum Background {
|
||||
Color(u8, u8, u8),
|
||||
Image(&'static str),
|
||||
}
|
||||
|
||||
enum UserType {
|
||||
Casual,
|
||||
Power
|
||||
}
|
||||
|
||||
struct MyApp {
|
||||
theme: Background,
|
||||
user_type: UserType,
|
||||
secret_user_id: usize
|
||||
}
|
||||
|
||||
fn guarded_match(app: MyApp) -> String {
|
||||
match app {
|
||||
MyApp { secret_user_id: uid, .. } if uid <= 100 => "You are an early bird!".to_owned(),
|
||||
MyApp { .. } => "Thank you for also joining".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn destructuring_match(app: MyApp) -> String {
|
||||
match app {
|
||||
MyApp { user_type: UserType::Power,
|
||||
secret_user_id: uid,
|
||||
theme: Background::Color(b1, b2, b3) } =>
|
||||
format!("A power user with id >{}< and color background (#{:02x}{:02x}{:02x})", uid, b1, b2, b3),
|
||||
MyApp { user_type: UserType::Power,
|
||||
secret_user_id: uid,
|
||||
theme: Background::Image(path) } =>
|
||||
format!("A power user with id >{}< and image background (path: {})", uid, path),
|
||||
MyApp { user_type: _, secret_user_id: uid, .. } => format!("A regular user with id >{}<, individual backgrounds not supported", uid),
|
||||
}
|
||||
}
|
||||
|
||||
fn literal_match(choice: usize) -> String {
|
||||
match choice {
|
||||
0 | 1 => "zero or one".to_owned(),
|
||||
2 ... 9 => "two to nine".to_owned(),
|
||||
10 => "ten".to_owned(),
|
||||
_ => "anything else".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
fn literal_str_match(choice: &str) -> String {
|
||||
match choice {
|
||||
"🏋️" => "Power lifting".to_owned(),
|
||||
"🏈" => "Football".to_owned(),
|
||||
"🥋" => "BJJ".to_owned(),
|
||||
_ => "Competitive BBQ".to_owned()
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn reference_match(m: &Option<&str>) -> String {
|
||||
match m {
|
||||
Some(ref s) => s.to_string(),
|
||||
_ => "Nothing".to_string()
|
||||
}
|
||||
}
|
||||
|
||||
fn tuple_match(choices: (i32, i32, i32, i32)) -> String {
|
||||
match choices {
|
||||
(_, second, _, fourth) => format!("Numbers at positions 1 and 3 are {} and {} respectively", second, fourth)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
pub fn main() {
|
||||
let opt = Some(42);
|
||||
// the most common match:
|
||||
match opt {
|
||||
Some(nr) => println!("Got {}", nr),
|
||||
// _ matches everything else as a placeholder for
|
||||
// don't care.
|
||||
_ => println!("Found None")
|
||||
}
|
||||
println!();
|
||||
println!("Literal match for 0: {}", literal_match(0));
|
||||
println!("Literal match for 10: {}", literal_match(10));
|
||||
println!("Literal match for 100: {}", literal_match(100));
|
||||
|
||||
println!();
|
||||
println!("Literal match for 0: {}", tuple_match((0, 10, 0, 100)));
|
||||
|
||||
println!();
|
||||
let mystr = Some("Hello");
|
||||
println!("Mathing on a reference: {}", reference_match(&mystr));
|
||||
println!("It's still owned here: {:?}", mystr);
|
||||
|
||||
println!();
|
||||
let power = MyApp {
|
||||
secret_user_id: 99,
|
||||
theme: Background::Color(255, 255, 0),
|
||||
user_type: UserType::Power
|
||||
};
|
||||
println!("Destructuring a power user: {}", destructuring_match(power));
|
||||
|
||||
let casual = MyApp {
|
||||
secret_user_id: 10,
|
||||
theme: Background::Image("my/fav/image.png"),
|
||||
user_type: UserType::Casual
|
||||
};
|
||||
println!("Destructuring a casual user: {}", destructuring_match(casual));
|
||||
|
||||
let power2 = MyApp {
|
||||
secret_user_id: 150,
|
||||
theme: Background::Image("a/great/landscape.png"),
|
||||
user_type: UserType::Power
|
||||
};
|
||||
println!("Destructuring another power user: {}", destructuring_match(power2));
|
||||
|
||||
println!();
|
||||
let early = MyApp {
|
||||
secret_user_id: 4,
|
||||
theme: Background::Color(255, 255, 0),
|
||||
user_type: UserType::Power
|
||||
};
|
||||
println!("Guarded matching (early): {}", guarded_match(early));
|
||||
|
||||
let not_so_early = MyApp {
|
||||
secret_user_id: 1003942,
|
||||
theme: Background::Color(255, 255, 0),
|
||||
user_type: UserType::Power
|
||||
};
|
||||
println!("Guarded matching (late): {}", guarded_match(not_so_early));
|
||||
println!();
|
||||
|
||||
println!("Literal match for 🥋: {}", literal_str_match("🥋"));
|
||||
println!("Literal match for 🏈: {}", literal_str_match("🏈"));
|
||||
println!("Literal match for 🏋️: {}", literal_str_match("🏋️"));
|
||||
println!("Literal match for ⛳: {}", literal_str_match("⛳"));
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,31 +0,0 @@
|
|||
// Task : To explain pointers in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{i32};
|
||||
|
||||
fn main() {
|
||||
|
||||
let vect1 = vec![1,2,3];
|
||||
|
||||
// Error in case you are doing this in case of non primitive value
|
||||
// let vec2 = vec1
|
||||
// println!("vec1[0] : {:?}", vec1[0]);
|
||||
|
||||
let prim_val = 1;
|
||||
let prim_val2 = prim_val;
|
||||
println!("primitive value :- {}", prim_val);
|
||||
|
||||
// passing the ownership to the function
|
||||
println!("Sum of vects : {}", sum_vects(&vect1));
|
||||
// Able to pass the non primitive data type
|
||||
println!("vector 1 {:?}", vect1);
|
||||
}
|
||||
|
||||
// Added a reference in the argument
|
||||
fn sum_vects (v1: &Vec<i32>) -> i32 {
|
||||
// apply a closure and iterator
|
||||
let sum = v1.iter().fold(0, |mut sum, &x | {sum += x; sum});
|
||||
return sum;
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "sharing-ownership"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,68 @@
|
|||
#![feature(test)]
|
||||
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
extern crate test;
|
||||
use std::rc::Rc;
|
||||
use test::{black_box, Bencher};
|
||||
|
||||
///
|
||||
/// A length function that takes ownership of the input variable
|
||||
///
|
||||
fn length(s: String) -> usize {
|
||||
s.len()
|
||||
}
|
||||
|
||||
///
|
||||
/// The same length function, taking ownership of a Rc
|
||||
///
|
||||
fn rc_length(s: Rc<String>) -> usize {
|
||||
s.len() // calls to the wrapped object require no additions
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_string_clone(b: &mut Bencher) {
|
||||
let s: String = (0..100_000).map(|_| 'a').collect();
|
||||
b.iter(|| {
|
||||
black_box(length(s.clone()));
|
||||
});
|
||||
}
|
||||
|
||||
#[bench]
|
||||
fn bench_string_rc(b: &mut Bencher) {
|
||||
let s: String = (0..100_000).map(|_| 'a').collect();
|
||||
let rc_s = Rc::new(s);
|
||||
b.iter(|| {
|
||||
black_box(rc_length(rc_s.clone()));
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
#[test]
|
||||
fn cloning() {
|
||||
let s = "abcdef".to_owned();
|
||||
assert_eq!(length(s), 6);
|
||||
// s is now "gone", we can't use it anymore
|
||||
// therefore we can't use it in a loop either!
|
||||
// ... unless we clone s - at a cost! (see benchmark)
|
||||
let s = "abcdef".to_owned();
|
||||
|
||||
for _ in 0..10 {
|
||||
// clone is typically an expensive deep copy
|
||||
assert_eq!(length(s.clone()), 6);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn refcounting() {
|
||||
let s = Rc::new("abcdef".to_owned());
|
||||
// we can clone Rc (reference counters) with low cost
|
||||
assert_eq!(rc_length(s.clone()), 6);
|
||||
|
||||
for _ in 0..10 {
|
||||
// clone is typically an expensive deep copy
|
||||
assert_eq!(rc_length(s.clone()), 6);
|
||||
}
|
||||
}
|
||||
}
|
BIN
Chapter02/struct
BIN
Chapter02/struct
Plik binarny nie jest wyświetlany.
|
@ -1,29 +0,0 @@
|
|||
// Task : To explain struct in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{f64};
|
||||
|
||||
fn main() {
|
||||
// create a struct variable
|
||||
let mut circle1 = Circle {
|
||||
x:10.0,radius : 10.0
|
||||
};
|
||||
|
||||
println!("x:{},radius : {}", circle1.x, circle1.radius );
|
||||
|
||||
println!("Radius : {}", get_radius(&circle1) );
|
||||
|
||||
}
|
||||
|
||||
// define your custom user datatype
|
||||
struct Circle {
|
||||
x : f64,
|
||||
radius : f64,
|
||||
}
|
||||
|
||||
// function which return radius
|
||||
fn get_radius(c1 : &Circle) -> f64{
|
||||
c1.radius
|
||||
}
|
BIN
Chapter02/trait
BIN
Chapter02/trait
Plik binarny nie jest wyświetlany.
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "trait-bounds"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,40 @@
|
|||
use std::fmt::Debug;
|
||||
|
||||
///
|
||||
/// An interface that can be used for quick and easy logging
|
||||
///
|
||||
pub trait Loggable: Debug + Sized {
|
||||
fn log(self) {
|
||||
println!("{:?}", &self)
|
||||
}
|
||||
}
|
||||
///
|
||||
/// A simple print function for printing debug formatted variables
|
||||
///
|
||||
fn log_debug<T: Debug>(t: T) {
|
||||
println!("{:?}", t);
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct ArbitraryType {
|
||||
v: Vec<i32>
|
||||
}
|
||||
|
||||
impl ArbitraryType {
|
||||
pub fn new() -> ArbitraryType {
|
||||
ArbitraryType {
|
||||
v: vec![1,2,3,4]
|
||||
}
|
||||
}
|
||||
}
|
||||
impl Loggable for ArbitraryType {}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct AnotherType(usize);
|
||||
|
||||
fn main() {
|
||||
let a = ArbitraryType::new();
|
||||
a.log();
|
||||
let b = AnotherType(2);
|
||||
log_debug(b);
|
||||
}
|
|
@ -1,51 +0,0 @@
|
|||
// Task : To explain trait in rust
|
||||
// Author : Vigneshwer
|
||||
// Version : 1.0
|
||||
// Date : 3 Dec 2016
|
||||
|
||||
use std::{f64};
|
||||
|
||||
fn main() {
|
||||
|
||||
// variable of circle datatype
|
||||
let mut circle1 = Circle {
|
||||
r : 10.0
|
||||
};
|
||||
println!("Area of circle {}", circle1.area() );
|
||||
|
||||
// variable of rectangle datatype
|
||||
let mut rect = Rectangle {
|
||||
h:10.0,b : 10.0
|
||||
};
|
||||
println!("Area of rectangle {}", rect.area() );
|
||||
}
|
||||
|
||||
// userdefined datatype rectangle
|
||||
struct Rectangle {
|
||||
h: f64,
|
||||
b: f64,
|
||||
}
|
||||
|
||||
// userdefined datatype circle
|
||||
struct Circle {
|
||||
r: f64,
|
||||
}
|
||||
|
||||
// create a functionality for the datatypes
|
||||
trait HasArea {
|
||||
fn area(&self) -> f64;
|
||||
}
|
||||
|
||||
// implement area for circle
|
||||
impl HasArea for Circle {
|
||||
fn area(&self) -> f64 {
|
||||
3.14 * (self.r *self.r)
|
||||
}
|
||||
}
|
||||
|
||||
// implement area for rectangle
|
||||
impl HasArea for Rectangle {
|
||||
fn area(&self) -> f64 {
|
||||
self.h *self.b
|
||||
}
|
||||
}
|
Plik binarny nie jest wyświetlany.
|
@ -1,34 +0,0 @@
|
|||
// Task: Performing type casting in rust
|
||||
// Date: 11 Feb 2016
|
||||
// Version: 0.0.1
|
||||
// Author: Vigneshwer
|
||||
|
||||
use std::{i32,f32};
|
||||
|
||||
// Sample function for assigning values to confusion matrix
|
||||
fn main() {
|
||||
|
||||
// assigning random values to the confusion matrix
|
||||
let(true_positive,true_negative,false_positive,false_negative)=(100,50,10,5);
|
||||
|
||||
// define a total closure
|
||||
let total = true_positive + true_negative + false_positive + false_negative;
|
||||
|
||||
println!("The total predictions {}",total);
|
||||
|
||||
// Calculating the accuracy of the model
|
||||
println!("Accuracy of the model {:.2}",percentage(accuracy(true_positive,true_negative,total)));
|
||||
|
||||
}
|
||||
|
||||
// Accuracy Measures the overall performance of the model
|
||||
fn accuracy(tp:i32,tn:i32,total:i32) -> f32 {
|
||||
// if semi-colon is not put then that returns
|
||||
// No automatic type cast in rust
|
||||
(tp as f32 + tn as f32 )/(total as f32)
|
||||
}
|
||||
|
||||
// Converting to percentage
|
||||
fn percentage(value:f32) -> f32 {
|
||||
value as f32 *100.0
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "unsafe-ways"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,44 @@
|
|||
#![allow(dead_code)]
|
||||
use std::slice;
|
||||
|
||||
fn split_into_equal_parts<T>(slice: &mut [T], parts: usize) -> Vec<&mut [T]> {
|
||||
let len = slice.len();
|
||||
assert!(parts <= len);
|
||||
let step = len / parts;
|
||||
unsafe {
|
||||
let ptr = slice.as_mut_ptr();
|
||||
|
||||
(0..step + 1)
|
||||
.map(|i| {
|
||||
let offset = (i * step) as isize;
|
||||
let a = ptr.offset(offset);
|
||||
slice::from_raw_parts_mut(a, step)
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
#[test]
|
||||
fn test_str_to_bytes_horribly_unsafe() {
|
||||
let bytes = unsafe { std::mem::transmute::<&str, &[u8]>("Going off the menu") };
|
||||
assert_eq!(
|
||||
bytes,
|
||||
&[
|
||||
71, 111, 105, 110, 103, 32, 111, 102, 102, 32, 116, 104, 101, 32, 109, 101, 110,
|
||||
117
|
||||
]
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_split_into_equal_parts() {
|
||||
let mut v = vec![1, 2, 3, 4, 5, 6];
|
||||
assert_eq!(
|
||||
split_into_equal_parts(&mut v, 3),
|
||||
&[&[1, 2], &[3, 4], &[5, 6]]
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,7 @@
|
|||
[package]
|
||||
name = "cargo-hello"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
println!("Hello, world!");
|
||||
}
|
|
@ -0,0 +1,12 @@
|
|||
[cargo-new]
|
||||
# This is your name/email to place in the `authors` section of a new Cargo.toml
|
||||
# that is generated. If not present, then `git` will be probed, and if that is
|
||||
# not present then `$USER` and `$EMAIL` will be used.
|
||||
name = "..."
|
||||
email = "..."
|
||||
|
||||
|
||||
[build]
|
||||
jobs = 4
|
||||
target = "wasm32-unknown-unknown"
|
||||
target-dir = "out"
|
|
@ -0,0 +1,14 @@
|
|||
[package]
|
||||
name = "custom-build"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
|
||||
|
||||
# Let's modify the release build
|
||||
[profile.release]
|
||||
opt-level = 2
|
||||
incremental = true # default is false
|
||||
overflow-checks = true
|
|
@ -0,0 +1 @@
|
|||
{"rustc_fingerprint":2823603757898662870,"outputs":{"6217262102979750783":["___.wasm\nlib___.rlib\n___.wasm\nlib___.a\n/home/cm/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu\ndebug_assertions\nproc_macro\ntarget_arch=\"wasm32\"\ntarget_endian=\"little\"\ntarget_env=\"\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"cas\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"unknown\"\ntarget_pointer_width=\"32\"\ntarget_vendor=\"unknown\"\n","warning: dropping unsupported crate type `dylib` for target `wasm32-unknown-unknown`\n\nwarning: dropping unsupported crate type `proc-macro` for target `wasm32-unknown-unknown`\n\n"],"1617349019360157463":["___\nlib___.rlib\nlib___.so\nlib___.so\nlib___.a\nlib___.so\n/home/cm/.rustup/toolchains/nightly-x86_64-unknown-linux-gnu\ndebug_assertions\nproc_macro\ntarget_arch=\"x86_64\"\ntarget_endian=\"little\"\ntarget_env=\"gnu\"\ntarget_family=\"unix\"\ntarget_feature=\"fxsr\"\ntarget_feature=\"mmx\"\ntarget_feature=\"sse\"\ntarget_feature=\"sse2\"\ntarget_has_atomic=\"16\"\ntarget_has_atomic=\"32\"\ntarget_has_atomic=\"64\"\ntarget_has_atomic=\"8\"\ntarget_has_atomic=\"cas\"\ntarget_has_atomic=\"ptr\"\ntarget_os=\"linux\"\ntarget_pointer_width=\"64\"\ntarget_thread_local\ntarget_vendor=\"unknown\"\nunix\n",""],"1164083562126845933":["rustc 1.35.0-nightly (aa99abeb2 2019-04-14)\nbinary: rustc\ncommit-hash: aa99abeb262307d5e9aa11a792312fd620b7f89a\ncommit-date: 2019-04-14\nhost: x86_64-unknown-linux-gnu\nrelease: 1.35.0-nightly\nLLVM version: 8.0\n",""]},"successes":{}}
|
|
@ -0,0 +1 @@
|
|||
6103dbe66b1c1499
|
|
@ -0,0 +1 @@
|
|||
{"rustc":6657857933646595371,"features":"[]","target":8081900203599542089,"profile":14996655781355331481,"path":1036222786711178230,"deps":[],"local":[{"MtimeBased":[[1555702721,688522520],"/home/cm/workspace/Mine/Rust-Cookbook/Chapter03/custom-build/out/wasm32-unknown-unknown/debug/.fingerprint/custom-build-0354a0e8029ace12/dep-bin-custom-build"]}],"rustflags":[],"metadata":14007051628862413002}
|
Plik binarny nie jest wyświetlany.
|
@ -0,0 +1 @@
|
|||
This file has an mtime of when this was started.
|
|
@ -0,0 +1 @@
|
|||
/home/cm/workspace/Mine/Rust-Cookbook/Chapter03/custom-build/out/wasm32-unknown-unknown/debug/custom-build.wasm: /home/cm/workspace/Mine/Rust-Cookbook/Chapter03/custom-build/src/main.rs
|
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
|
@ -0,0 +1,5 @@
|
|||
/home/cm/workspace/Mine/Rust-Cookbook/Chapter03/custom-build/out/wasm32-unknown-unknown/debug/deps/custom_build.wasm: src/main.rs
|
||||
|
||||
/home/cm/workspace/Mine/Rust-Cookbook/Chapter03/custom-build/out/wasm32-unknown-unknown/debug/deps/custom_build.d: src/main.rs
|
||||
|
||||
src/main.rs:
|
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
Plik binarny nie jest wyświetlany.
|
@ -0,0 +1,3 @@
|
|||
fn main() {
|
||||
println!("Overflow! {}", 128 + 129);
|
||||
}
|
|
@ -0,0 +1,21 @@
|
|||
[package]
|
||||
name = "external-deps"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
regex = { git = "https://github.com/rust-lang/regex" } # bleeding edge libraries
|
||||
|
||||
# specifying crate features
|
||||
serde = { version = "1", features = ["derive"] }
|
||||
serde_json = "*" # pick whatever version
|
||||
|
||||
|
||||
[dev-dependencies]
|
||||
criterion = "0.2.11"
|
||||
|
||||
|
||||
[[bench]]
|
||||
name = "cooking_with_rust"
|
||||
harness = false
|
|
@ -0,0 +1,32 @@
|
|||
#[macro_use]
|
||||
extern crate criterion;
|
||||
|
||||
use criterion::black_box;
|
||||
use criterion::Criterion;
|
||||
|
||||
pub fn bubble_sort<T: PartialOrd + Clone>(collection: &[T]) -> Vec<T> {
|
||||
let mut result: Vec<T> = collection.into();
|
||||
for _ in 0..result.len() {
|
||||
let mut swaps = 0;
|
||||
for i in 1..result.len() {
|
||||
if result[i - 1] > result[i] {
|
||||
result.swap(i - 1, i);
|
||||
swaps += 1;
|
||||
}
|
||||
}
|
||||
if swaps == 0 {
|
||||
break;
|
||||
}
|
||||
}
|
||||
result
|
||||
}
|
||||
|
||||
fn bench_bubble_sort_1k_asc(c: &mut Criterion) {
|
||||
c.bench_function("Bubble sort 1k descending numbers", |b| {
|
||||
let items: Vec<i32> = (0..1_000).rev().collect();
|
||||
b.iter(|| black_box(bubble_sort(&items)))
|
||||
});
|
||||
}
|
||||
|
||||
criterion_group!(benches, bench_bubble_sort_1k_asc);
|
||||
criterion_main!(benches);
|
|
@ -0,0 +1,28 @@
|
|||
use regex::Regex;
|
||||
use serde::Serialize;
|
||||
|
||||
#[derive(Serialize)]
|
||||
struct Person {
|
||||
pub full_name: String,
|
||||
pub call_me: String,
|
||||
pub age: usize,
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let a_person = Person {
|
||||
full_name: "John Smith".to_owned(),
|
||||
call_me: "Smithy".to_owned(),
|
||||
age: 42,
|
||||
};
|
||||
let serialized = serde_json::to_string(&a_person).unwrap();
|
||||
println!("A serialized Person instance: {}", serialized);
|
||||
|
||||
let re = Regex::new(r"(?x)(?P<year>\d{4})-(?P<month>\d{2})-(?P<day>\d{2})").unwrap();
|
||||
println!("Some regex parsing:");
|
||||
let d = "2019-01-31";
|
||||
println!(" Is {} valid? {}", d, re.captures(d).is_some());
|
||||
let d = "9999-99-00";
|
||||
println!(" Is {} valid? {}", d, re.captures(d).is_some());
|
||||
let d = "2019-1-10";
|
||||
println!(" Is {} valid? {}", d, re.captures(d).is_some());
|
||||
}
|
|
@ -0,0 +1,3 @@
|
|||
[workspace]
|
||||
|
||||
members = [ "a-lib", "a-project" ]
|
|
@ -0,0 +1,3 @@
|
|||
/target
|
||||
**/*.rs.bk
|
||||
Cargo.lock
|
|
@ -0,0 +1,8 @@
|
|||
[package]
|
||||
name = "a-lib"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dev-dependencies]
|
||||
rand = "*"
|
|
@ -0,0 +1,30 @@
|
|||
use std::fmt::Debug;
|
||||
|
||||
pub fn stringify<T: Debug>(v: &T) -> String {
|
||||
format!("{:#?}", v)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use rand::prelude::*;
|
||||
use super::stringify;
|
||||
|
||||
#[test]
|
||||
fn test_numbers() {
|
||||
let a_nr: f64 = random();
|
||||
assert_eq!(stringify(&a_nr), format!("{:#?}", a_nr));
|
||||
assert_eq!(stringify(&1i32), "1");
|
||||
assert_eq!(stringify(&1usize), "1");
|
||||
assert_eq!(stringify(&1u32), "1");
|
||||
assert_eq!(stringify(&1i64), "1");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_sequences() {
|
||||
assert_eq!(stringify(&vec![0, 1, 2]), "[\n 0,\n 1,\n 2,\n]");
|
||||
assert_eq!(
|
||||
stringify(&(1, 2, 3, 4)),
|
||||
"(\n 1,\n 2,\n 3,\n 4,\n)"
|
||||
);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,2 @@
|
|||
/target
|
||||
**/*.rs.bk
|
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "a-project"
|
||||
version = "0.1.0"
|
||||
authors = ["Claus Matzinger <claus.matzinger+kb@gmail.com>"]
|
||||
edition = "2018"
|
||||
|
||||
[dependencies]
|
||||
a-lib = { path = "../a-lib" }
|
||||
rand = "0.5"
|
|
@ -0,0 +1,6 @@
|
|||
use a_lib::stringify;
|
||||
use rand::prelude::*;
|
||||
|
||||
fn main() {
|
||||
println!("{{ \"values\": {}, \"sensor\": {} }}", stringify(&vec![random::<f64>(); 6]), stringify(&"temperature"));
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
Subproject commit 4d7f00bfeb252c6ecfc8ad3b107c9260396bc046
|
|
@ -1,21 +0,0 @@
|
|||
[root]
|
||||
name = "rand"
|
||||
version = "0.3.15"
|
||||
dependencies = [
|
||||
"libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
"log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)",
|
||||
]
|
||||
|
||||
[[package]]
|
||||
name = "libc"
|
||||
version = "0.2.20"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[[package]]
|
||||
name = "log"
|
||||
version = "0.3.6"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
|
||||
[metadata]
|
||||
"checksum libc 0.2.20 (registry+https://github.com/rust-lang/crates.io-index)" = "684f330624d8c3784fb9558ca46c4ce488073a8d22450415c5eb4f4cfb0d11b5"
|
||||
"checksum log 0.3.6 (registry+https://github.com/rust-lang/crates.io-index)" = "ab83497bf8bf4ed2a74259c1c802351fcd67a65baa86394b6ba73c36f4838054"
|
|
@ -1,21 +0,0 @@
|
|||
[package]
|
||||
|
||||
name = "rand"
|
||||
version = "0.3.15"
|
||||
authors = ["The Rust Project Developers"]
|
||||
license = "MIT/Apache-2.0"
|
||||
readme = "README.md"
|
||||
repository = "https://github.com/rust-lang/rand"
|
||||
documentation = "https://doc.rust-lang.org/rand"
|
||||
homepage = "https://github.com/rust-lang/rand"
|
||||
description = """
|
||||
Random number generators and other randomness functionality.
|
||||
"""
|
||||
keywords = ["random", "rng"]
|
||||
categories = ["algorithms"]
|
||||
|
||||
[dependencies]
|
||||
libc = "0.2"
|
||||
|
||||
[dev-dependencies]
|
||||
log = "0.3.0"
|
|
@ -1,201 +0,0 @@
|
|||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
of your accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work.
|
||||
|
||||
To apply the Apache License to your work, attach the following
|
||||
boilerplate notice, with the fields enclosed by brackets "[]"
|
||||
replaced with your own identifying information. (Don't include
|
||||
the brackets!) The text should be enclosed in the appropriate
|
||||
comment syntax for the file format. We also recommend that a
|
||||
file or class name and description of purpose be included on the
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
|
@ -1,25 +0,0 @@
|
|||
Copyright (c) 2014 The Rust Project Developers
|
||||
|
||||
Permission is hereby granted, free of charge, to any
|
||||
person obtaining a copy of this software and associated
|
||||
documentation files (the "Software"), to deal in the
|
||||
Software without restriction, including without
|
||||
limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of
|
||||
the Software, and to permit persons to whom the Software
|
||||
is furnished to do so, subject to the following
|
||||
conditions:
|
||||
|
||||
The above copyright notice and this permission notice
|
||||
shall be included in all copies or substantial portions
|
||||
of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF
|
||||
ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED
|
||||
TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A
|
||||
PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT
|
||||
SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
|
||||
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
|
||||
OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR
|
||||
IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
|
||||
DEALINGS IN THE SOFTWARE.
|
Some files were not shown because too many files have changed in this diff Show More
Ładowanie…
Reference in New Issue