use std::ascii::AsciiExt;
use std::ops::DerefMut;
use std::mem::transmute;
pub trait AsciiReplaceInPlace {
fn ascii_replace_in_place(&mut self, needle: char, haystack: char);
}
pub trait AsciiReplace: Sized {
fn ascii_replace(self, needle: char, haystack: char) -> Self;
}
impl<T: DerefMut<Target=str>> AsciiReplace for T {
fn ascii_replace(mut self, needle: char, haystack: char) -> Self {
self.ascii_replace_in_place(needle, haystack);
self
}
}
impl AsciiReplaceInPlace for str {
fn ascii_replace_in_place(&mut self, needle: char, haystack: char) {
assert!(
needle.is_ascii(),
"AsciiReplace functions can only be used for ascii characters"
);
assert!(
haystack.is_ascii(),
"AsciiReplace functions can only be used for ascii characters"
);
let (needle, haystack): (u32, u32) = (needle.into(), haystack.into());
let (needle, haystack) = (needle as u8, haystack as u8);
let mut_bytes: &mut [u8] = unsafe { transmute(self) };
for chr in mut_bytes.iter_mut() {
if *chr == needle {
*chr = haystack;
}
}
}
}