pub fn strip_mnemonic(s: &str) -> String {
let mut out = String::with_capacity(s.len());
let mut it = s.chars().peekable();
while let Some(c) = it.next() {
if c != '&' {
out.push(c);
} else if it.peek() == Some(&'&') {
it.next();
out.push('&');
}
}
out
}
#[allow(dead_code)] fn translate(s: &str, marker: char, literal: &str, escape_marker: bool) -> String {
let mut out = String::with_capacity(s.len() + 1);
let mut it = s.chars().peekable();
let mut used = false;
while let Some(c) = it.next() {
match c {
c if escape_marker && c == marker => {
out.push(marker);
out.push(marker);
}
'&' => match it.peek() {
Some('&') => {
it.next();
out.push_str(literal);
}
Some(_) if !used => {
used = true;
out.push(marker);
}
_ => {}
},
c => out.push(c),
}
}
out
}
#[allow(dead_code)] pub fn to_gtk_mnemonic(s: &str) -> String {
translate(s, '_', "&", true)
}
#[allow(dead_code)] pub fn to_win32_mnemonic(s: &str) -> String {
translate(s, '&', "&&", false)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::tests::fuzz_layout::Rng;
fn interpret(s: &str, marker: char) -> (String, Option<usize>) {
let mut out = String::new();
let mut index = None;
let mut it = s.chars().peekable();
while let Some(c) = it.next() {
if c != marker {
out.push(c);
continue;
}
match it.peek() {
Some(m) if *m == marker => {
it.next();
out.push(marker);
}
Some(_) => {
if index.is_none() {
index = Some(out.len());
}
}
None => {}
}
}
(out, index)
}
#[test]
fn examples() {
assert_eq!(strip_mnemonic("&Open && close"), "Open & close");
assert_eq!(strip_mnemonic("trailing &"), "trailing ");
assert_eq!(strip_mnemonic("&a &b"), "a b");
assert_eq!(strip_mnemonic("Fish && &Chips"), "Fish & Chips");
assert_eq!(to_gtk_mnemonic("&File"), "_File");
assert_eq!(to_gtk_mnemonic("snake_case && &x"), "snake__case & _x");
assert_eq!(to_gtk_mnemonic("&a &b"), "_a b");
assert_eq!(to_win32_mnemonic("&a &b && c &"), "&a b && c ");
assert_eq!(to_win32_mnemonic("日本&語"), "日本&語");
}
#[test]
fn translations_agree_with_each_other() {
let mut rng = Rng::new(14);
let alphabet = ["a", "b", "é", "😀", "&", "&", "&&", " ", "e\u{301}", "_"];
for _ in 0..5000 {
let s: String = (0..rng.below(8))
.map(|_| alphabet[rng.below(alphabet.len())])
.collect();
let stripped = strip_mnemonic(&s);
let (wt, wi) = interpret(&to_win32_mnemonic(&s), '&');
assert_eq!(wt, stripped, "win32 text of {s:?}");
let (src_text, src_index) = interpret(&s, '&');
assert_eq!((wt, wi), (src_text, src_index), "win32 of {s:?}");
let g = to_gtk_mnemonic(&s);
let (gt, gi) = interpret(&g, '_');
assert_eq!(gt, stripped, "gtk text of {s:?} = {g:?}");
let key_is_underscore = src_index.is_some_and(|i| stripped[i..].starts_with('_'));
if !key_is_underscore && !stripped.starts_with("__") {
assert_eq!(gi, src_index, "gtk mnemonic position of {s:?} = {g:?}");
}
}
}
}