Skip to content

Instantly share code, notes, and snippets.

Created July 7, 2016 07:22
Show Gist options
  • Save anonymous/c5217c518b43a326227e8882b09cb2fe to your computer and use it in GitHub Desktop.
Save anonymous/c5217c518b43a326227e8882b09cb2fe to your computer and use it in GitHub Desktop.
Shared via Rust Playground
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