mutability and pure functions

master
Andrew Johnson 6 years ago
parent de931dbe20
commit 91aad7d83d

@ -4,6 +4,8 @@ version = "1.0.0"
build = "build.rs"
[dependencies]
lazy_static = "1"
cached = "0.5"
floating-duration = "0.1.2"
termion = "1.0"
timebomb = "0.1"
@ -11,3 +13,11 @@ serde = "1.0"
serde_json = "1.0"
serde_derive = "1.0"
libc = "0.2"
[[bin]]
name = "mutability"
path = "mutability.rs"
[[bin]]
name = "pure_functions"
path = "pure_functions.rs"

@ -0,0 +1,47 @@
use std::sync::{Mutex, Arc};
fn f(x: &mut i32) {
*x = 2;
}
#[derive(Clone)]
struct TimeBomb {
countdown: Arc<Mutex<i32>>
}
impl Drop for TimeBomb
{
fn drop(&mut self) {
let mut c = self.countdown.lock().unwrap();
*c -= 1;
if *c <= 0 {
panic!("BOOM!!")
}
}
}
fn main()
{
let a = 5;
let mut b = 5;
//a = 4; not valid
b = 4;
//*(&mut a) = 3; not valid
*(&mut b) = 3;
let a = 5;
let mut b = 5;
//f(&mut a); not valid
f(&mut b);
{
let t3 = TimeBomb {
countdown: Arc::new(Mutex::new(3))
};
let t2 = t3.clone();
let t1 = t2.clone();
let t0 = t1.clone();
}
}

@ -0,0 +1,102 @@
#[macro_use] extern crate lazy_static;
#[macro_use] extern crate cached;
use std::collections::HashMap;
use std::sync::{Arc,Mutex};
use std::cell::Cell;
fn p0() {}
fn p1() -> u64 {
444
}
fn p2(x: u64) -> u64 {
x * 444
}
fn p3(x: u64, y: u64) -> u64 {
x * 444 + y
}
static mut blah: u64 = 3;
fn ip0() {
unsafe {
blah = 444;
}
}
fn ip1(c: &Cell<u64>) {
c.set(333);
}
cached!{
FIB;
fn fib(n: u64) -> u64 = {
if n == 0 || n == 1 { return n }
fib(n-1) + fib(n-2)
}
}
lazy_static! {
static ref BUCKET_COUNTER: Mutex<HashMap<u64, u64>> = {
Mutex::new(HashMap::new())
};
}
cached!{
BUCK;
fn bucket_count(n: u64) -> u64 = {
let mut counter = BUCKET_COUNTER.lock().unwrap();
let r = match counter.get(&n) {
Some(c) => { c+1 }
None => { 1 }
};
counter.insert(n, r);
r
}
}
#[derive(Clone)]
pub struct TimeBomb {
countdown: Arc<Mutex<i32>>
}
impl Drop for TimeBomb
{
fn drop(&mut self) {
let mut c = self.countdown.lock().unwrap();
*c -= 1;
if *c <= 0 {
panic!("BOOM!!")
}
}
}
cached!{
TICKING_BOX;
fn tick_tock(v: i32) -> TimeBomb = {
TimeBomb {
countdown: Arc::new(Mutex::new(v))
}
}
}
fn main()
{
p0();
p1();
p2(3);
p3(3,4);
ip0();
let r = Cell::new(3);
ip1(&r);
ip1(&r);
fib(30); //call 1, generates correct value and returns it
fib(30); //call 2, finds correct value and returns it
bucket_count(30); //call 1, generates correct value and returns it
bucket_count(30); //call 2, finds stale value and returns it
tick_tock(3);
tick_tock(3);
tick_tock(3);
}
Loading…
Cancel
Save