simple_states/
simple_states.rs

1// this is the example from the README.md
2//! This example demonstrates how to use the `linear_type` crate to model a linear state machine
3//! that reads the content of a file.
4use linear_type::Linear;
5use std::fs::File;
6use std::io::{Read, Result};
7
8// define some newtypes for the states
9struct Filename(&'static str);
10#[derive(Debug)]
11struct ReadonlyFile(File);
12#[derive(Debug)]
13struct FileContent(String);
14
15// define functions that transition from one state to the next
16fn open_file(Filename(name): Filename) -> Result<ReadonlyFile> {
17    Ok(ReadonlyFile(File::open(name)?))
18}
19
20fn read_text(ReadonlyFile(mut file): ReadonlyFile) -> Result<FileContent> {
21    let mut text = String::new();
22    file.read_to_string(&mut text)?;
23    Ok(FileContent(text))
24}
25
26fn main() {
27    // Create a linear type and transition through the states
28    let file_content = Linear::new(Filename("README.md"))
29        .map(open_file)
30        .map_ok(read_text)
31        .unwrap_ok();
32
33    // destructure the file content
34    let FileContent(text) = file_content.into_inner();
35    assert!(text.contains("# Example"));
36}