pub trait CharFns {
fn char_len(&self) -> usize;
fn char_split(&self, index: usize) -> (&str, &str);
fn char_replace(&self, index: usize, len: usize, text: &str) -> String;
}
impl CharFns for str {
fn char_len(&self) -> usize {
self.chars().count()
}
fn char_split(&self, index: usize) -> (&str, &str) {
self.split_at(byte_index(self, index))
}
fn char_replace(&self, index: usize, len: usize, text: &str) -> String {
let (pre, remaining) = self.char_split(index);
let (_, post) = remaining.char_split(len);
format!("{}{}{}", pre, text, post)
}
}
#[inline]
fn byte_index(string: &str, char_index: usize) -> usize {
let mut bidx = 0;
let mut cidx = 0;
for b in string.bytes() {
if (b as i8) >= -0x40 {
if cidx == char_index { break }
cidx += 1;
}
bidx += 1
}
bidx
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_len() {
assert!("".char_len() == 0);
assert!("hello".char_len() == 5);
assert!("๐๐".char_len() == 2);
}
#[test]
fn test_split() {
assert!("".char_split(0) == ("", ""));
assert!("hello".char_split(2) == ("he", "llo"));
assert!("๐ค๐๐ รฑXwowโฎ".char_split(5) == ("๐ค๐๐ รฑX","wowโฎ"));
}
#[test]
fn test_replace_empty() {
assert!("".char_replace(0, 0, "") == "");
assert!("".char_replace(0, 0, "โขโธ") == "โขโธ");
}
#[test]
fn test_replace_delete_only() {
assert!("heโ
โโo".char_replace(0, 3, "") == "โโo");
assert!("heโ
โโo".char_replace(2, 2, "") == "heโo");
assert!("heโ
โโo".char_replace(4, 2, "") == "heโ
โ");
}
#[test]
fn test_replace_insert_only() {
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(0, 0, "โโo") == "โโo๐ค๐๐ รฑXwowโฎ");
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(1, 0, "โโo") == "๐คโโo๐๐ รฑXwowโฎ");
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(9, 0, "โโo") == "๐ค๐๐ รฑXwowโฎโโo");
}
#[test]
fn test_replace_delete_and_insert() {
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(0, 2, "โโo") == "โโo๐ รฑXwowโฎ");
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(4, 4, "โโo") == "๐ค๐๐ รฑโโoโฎ");
assert!("๐ค๐๐ รฑXwowโฎ".char_replace(1, 8, "โโo") == "๐คโโo");
}
}