mreplace/
lib.rs

1#![feature(doc_cfg)]
2#![feature(slice_index_methods)]
3
4pub use daachorse::{errors::Result, CharwiseDoubleArrayAhoCorasick};
5
6pub struct Mreplace {
7  pub ac: CharwiseDoubleArrayAhoCorasick<usize>,
8}
9
10impl Mreplace {
11  pub fn new<S: ToString>(from_string: impl IntoIterator<Item = S>) -> Result<Self> {
12    let li: Vec<(String, usize)> = from_string
13      .into_iter()
14      .enumerate()
15      .map(|(pos, i)| (i.to_string(), pos))
16      .collect();
17
18    Ok(Self {
19      ac: CharwiseDoubleArrayAhoCorasick::with_values(li)?,
20    })
21  }
22  pub fn replace<S: AsRef<str>>(&self, txt: impl AsRef<str>, to_string: impl AsRef<[S]>) -> String {
23    let to_string = to_string.as_ref();
24    let txt = txt.as_ref();
25    let mut r = String::new();
26    let mut pre = 0;
27    for i in self.ac.find_iter(txt) {
28      r.push_str(&txt[pre..i.start()]);
29      r.push_str(to_string[i.value()].as_ref());
30      pre = i.end();
31    }
32    r.push_str(&txt[pre..txt.len()]);
33    r
34  }
35}
36
37#[cfg(feature = "macro")]
38pub use const_str;
39
40#[cfg(feature = "macro")]
41#[doc(cfg(feature = "macro"))]
42#[macro_export]
43macro_rules! mreplace {
44  ($($var:ident : $($k:ident)+);*) => {
45  $(
46  #[static_init::dynamic]
47  static $var: $crate::Mreplace = $crate::Mreplace::new([
48    $($crate::const_str::concat!("${",stringify!($k),"}")),+
49  ]).unwrap();
50  )*
51  };
52  ($($var:ident : $($k:ident)+;)*) => {
53    $crate::mreplace!($($var:$($k)+);*);
54  };
55}