1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
use std::string::ToString;

pub use daachorse::{errors::Result, CharwiseDoubleArrayAhoCorasick};

pub struct Mreplace {
  pub ac: CharwiseDoubleArrayAhoCorasick<usize>,
}

impl Mreplace {
  pub fn new<S: ToString>(from_string: impl IntoIterator<Item = S>) -> Result<Self> {
    let li: Vec<(String, usize)> = from_string
      .into_iter()
      .enumerate()
      .map(|(pos, i)| (i.to_string(), pos))
      .collect();

    Ok(Self {
      ac: CharwiseDoubleArrayAhoCorasick::with_values(li)?,
    })
  }
  pub fn replace<S: AsRef<str>>(
    &self,
    txt: impl AsRef<str>,
    to_string: impl std::ops::Index<usize, Output = S>,
  ) -> String {
    let txt = txt.as_ref();
    let mut r = String::new();
    let mut pre = 0;
    for i in self.ac.find_iter(txt) {
      r.push_str(&txt[pre..i.start()]);
      r.push_str(to_string[i.value()].as_ref());
      pre = i.end();
    }
    r.push_str(&txt[pre..txt.len()]);
    r
  }
}