forked from Jouzo/vsdb
-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathweb_server.rs
102 lines (86 loc) · 2.36 KB
/
web_server.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
//!
//! An example for stateless functions.
//!
use ruc::*;
use serde::{Deserialize, Serialize};
use std::{sync::mpsc::channel, thread};
use vsdb::{Mapx, ValueEnDe, Vecx};
#[derive(Debug, Deserialize, Serialize)]
struct Animal {
id: u64,
kind: AnimalKind,
owner: AnimalOwner,
}
#[derive(Debug, Deserialize, Serialize)]
enum AnimalKind {
Dog,
Cat,
Pig,
Monkey,
Donkey,
Unknown,
}
type AnimalID = u64;
type AnimalOwner = String;
#[derive(Default, Debug, Deserialize, Serialize)]
struct AnimalHospital {
owners: Mapx<AnimalOwner, Mapx<AnimalID, Animal>>,
discharge_history: Vecx<AnimalID>,
id_alloctor: u64,
}
impl AnimalHospital {
fn hospitalized(
&mut self,
kind: AnimalKind,
owner: AnimalOwner,
) -> Result<AnimalID> {
if matches!(kind, AnimalKind::Unknown) {
return Err(eg!("unsupported animal"));
}
let new_id = self.alloc_id();
let animal = Animal {
id: new_id,
kind,
owner: owner.clone(),
};
self.owners
.entry(&owner)
.or_insert(&Mapx::new())
.insert(&new_id, &animal);
Ok(new_id)
}
fn discharged(&mut self, owner: AnimalOwner, id: AnimalID) -> Result<()> {
if let Some(mut animals) = self.owners.get_mut(&owner) {
if animals.remove(&id).is_none() {
return Err(eg!("animal ID not found"));
}
self.discharge_history.push(&id);
Ok(())
} else {
Err(eg!("owner not found"))
}
}
fn alloc_id(&mut self) -> AnimalID {
self.id_alloctor += 1;
self.id_alloctor
}
}
fn main() {
let (sender, receiver) = channel();
thread::spawn(move || {
let mut ah = AnimalHospital::default();
let ids = (0..100)
.map(|i| ah.hospitalized(AnimalKind::Cat, format!("owner-{}", i)))
.collect::<Result<Vec<_>>>()
.unwrap();
sender.send((ah.encode(), ids)).unwrap();
});
let (ah_bytes, ids) = receiver.recv().unwrap();
// will be re-initilized when serializing
let mut ah: AnimalHospital = ValueEnDe::decode(&ah_bytes).unwrap();
(0..100)
.zip(ids.iter())
.map(|(i, id)| ah.discharged(format!("owner-{}", i), *id))
.collect::<Result<Vec<_>>>()
.unwrap();
}