From 5cb66d932f838e282d9edf84eb37000e2a50fce2 Mon Sep 17 00:00:00 2001 From: Eryn Wells Date: Sun, 23 Apr 2017 10:02:39 -0700 Subject: [PATCH] [lexer] Clean up named_char module --- lexer/src/named_char.rs | 69 +++++++++++++++++++++++++---------------- 1 file changed, 42 insertions(+), 27 deletions(-) diff --git a/lexer/src/named_char.rs b/lexer/src/named_char.rs index 36675e9..b07e6f0 100644 --- a/lexer/src/named_char.rs +++ b/lexer/src/named_char.rs @@ -2,8 +2,8 @@ * Eryn Wells */ -use std::collections::HashSet; -use sibiltypes::Char; +use std::collections::HashMap; +use std::sync::{Once, ONCE_INIT}; const ALARM: &'static str = "alarm"; const BACKSPACE: &'static str = "backspace"; @@ -15,31 +15,46 @@ const RETURN: &'static str = "return"; const SPACE: &'static str = "space"; const TAB: &'static str = "tab"; -pub fn set() -> HashSet<&'static str> { - let mut set: HashSet<&'static str> = HashSet::new(); - set.insert(ALARM); - set.insert(BACKSPACE); - set.insert(DELETE); - set.insert(ESCAPE); - set.insert(NEWLINE); - set.insert(NULL); - set.insert(RETURN); - set.insert(SPACE); - set.insert(TAB); - set +/// Mapping of names to `char` values. Returns the name of the given character, if a name exists. +/// Otherwise, returns `None`. +fn char_for(named: &str) -> Option { + static ONCE = ONCE_INIT; + static mut names_to_chars: HashMap<&'static str, char>; + unsafe { + ONCE.call_once(|| { + names_to_chars = HashMap::new(); + names_to_chars.insert(ALARM, '\x07'); + names_to_chars.insert(BACKSPACE, '\x08'); + names_to_chars.insert(DELETE, '\x7F'); + names_to_chars.insert(ESCAPE, '\x1B'); + names_to_chars.insert(NEWLINE, '\n'); + names_to_chars.insert(NULL, '\0'); + names_to_chars.insert(RETURN, '\r'); + names_to_chars.insert(SPACE, ' '); + names_to_chars.insert(TAB, '\t'); + }); + names_to_chars.get(named) + } } -pub fn char_named_by(named: &str) -> Char { - Char(match named { - ALARM => '\x07', - BACKSPACE => '\x08', - DELETE => '\x7F', - ESCAPE => '\x1B', - NEWLINE => '\n', - NULL => '\0', - RETURN => '\r', - SPACE => ' ', - TAB => '\t', - _ => panic!("char_named_by called with invalid named char string") - }) +/// Mapping of `char` values to names. Returns the name of the given character, if a name exists. +/// Otherwise, returns `None`. +fn name_of(c: char) -> Option<&'static str> { + static ONCE = ONCE_INIT; + static mut chars_to_names: HashMap; + unsafe { + ONCE.call_once(|| { + chars_to_names = HashMap::new(); + chars_to_names.insert('\x07', ALARM); + chars_to_names.insert('\x08', BACKSPACE); + chars_to_names.insert('\x7F', DELETE); + chars_to_names.insert('\x1B', ESCAPE); + chars_to_names.insert('\n', NEWLINE); + chars_to_names.insert('\0', NULL); + chars_to_names.insert('\r', RETURN); + chars_to_names.insert(' ', SPACE); + chars_to_names.insert('\t', TAB); + }); + chars_to_names.get(c) + } }