Skip to content

Instantly share code, notes, and snippets.

@swizard0
Created November 20, 2017 19:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save swizard0/9ad5175d31f60646315ec77674a7d4c8 to your computer and use it in GitHub Desktop.
Save swizard0/9ad5175d31f60646315ec77674a7d4c8 to your computer and use it in GitHub Desktop.
MUV sketch for Rust
use std::io::{self, Write};
// messages
struct MsgLogin(String);
struct MsgGreet;
struct MsgLogout;
// models
struct ModelLogouted;
struct ModelLogined(String);
// update
struct Update<ML, MG> {
model: ML,
msg: MG,
}
impl<ML, MG> Update<ML, MG> {
fn new(model: ML, msg: MG) -> Update<ML, MG> {
Update { model, msg, }
}
}
impl Update<ModelLogouted, MsgLogin> {
fn update(self) -> ModelLogined {
ModelLogined(self.msg.0)
}
}
impl Update<ModelLogined, MsgGreet> {
fn update(self) -> ModelLogined {
self.model
}
}
impl Update<ModelLogined, MsgLogout> {
fn update(self) -> ModelLogouted {
ModelLogouted
}
}
// view
impl ModelLogouted {
fn view(self) {
print!("Login: ");
io::stdout().flush().unwrap();
let login = getline().unwrap_or_else(|| "anon".to_string());
let model = Update::new(self, MsgLogin(login)).update();
model.view();
}
}
impl ModelLogined {
fn view(self) {
println!("Hello, {}!", self.0);
println!("Input empty string for logout or nonempty for greeting.");
match getline() {
None => {
let model = Update::new(self, MsgLogout).update();
model.view();
},
Some(..) => {
let model = Update::new(self, MsgGreet).update();
model.view();
}
}
}
}
// util
fn getline() -> Option<String> {
let mut input = String::new();
io::stdin().read_line(&mut input).unwrap();
let trimmed = input.trim();
if trimmed.is_empty() { None } else { Some(trimmed.to_string()) }
}
// main
fn main() {
let init_model = ModelLogouted;
init_model.view();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment