-
-
Save iddm/d8b2fa5fa5a2ed2257b5098272eb83b1 to your computer and use it in GitHub Desktop.
Shared via Rust Playground
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
enum MachineState { | |
Normal, | |
Comment, | |
Upper, | |
Lower, | |
} | |
fn machine_cycle(state: &MachineState, character: char) -> (Option<char>, MachineState) { | |
use std::ascii::AsciiExt; | |
let mut return_char = None; | |
let return_state; | |
match *state { | |
MachineState::Normal => { | |
match character { | |
'#' => { | |
return_state = MachineState::Comment; | |
} | |
'^' => { | |
return_state = MachineState::Upper; | |
} | |
'_' => { | |
return_state = MachineState::Lower; | |
} | |
_ => { | |
return_char = Some(character); | |
return_state = MachineState::Normal; | |
} | |
} | |
} | |
MachineState::Comment => { | |
if character == '#' { | |
return_state = MachineState::Normal; | |
} | |
else { | |
return_state = MachineState::Comment; | |
} | |
} | |
MachineState::Upper => { | |
if character == '^' { | |
return_state = MachineState::Normal; | |
} | |
else { | |
return_char = Some(character.to_ascii_uppercase()); | |
return_state = MachineState::Upper; | |
} | |
} | |
MachineState::Lower => { | |
if character == '_' { | |
return_state = MachineState::Normal; | |
} | |
else { | |
return_char = Some(character.to_ascii_lowercase()); | |
return_state = MachineState::Lower; | |
} | |
} | |
} | |
(return_char, return_state) | |
} | |
fn main() { | |
let mut state = MachineState::Normal; | |
let input = "this is some _LoWER CASe_ text,#this is a comment,# ^and this part is upper casE^."; | |
let mut processed_string = String::new(); | |
for character in input.chars() { | |
let (output, new_state) = machine_cycle(&state, character); | |
// No match needed here, as it's either Some(character), or None, and we don't care about | |
// None. | |
if let Some(c) = output { | |
processed_string.push(c); | |
} | |
state = new_state; | |
} | |
println!("Input:\t{}\nOutput:\t{}", input, processed_string); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment