Skip to main content

string_wizard/magic_string/
replace.rs

1use crate::{CowStr, UpdateOptions};
2
3use super::MagicString;
4
5#[derive(Debug)]
6pub struct ReplaceOptions {
7  /// The maximum number of times to replace the pattern. Default is `1`.
8  pub count: usize,
9  /// This will store the original content in the `name` field of the generated sourcemap.
10  ///
11  /// Default is `false`.
12  pub store_original_in_sourcemap: bool,
13}
14
15impl Default for ReplaceOptions {
16  fn default() -> Self {
17    Self { count: 1, store_original_in_sourcemap: false }
18  }
19}
20
21impl<'text> MagicString<'text> {
22  pub fn replace(&mut self, from: &str, to: impl Into<CowStr<'text>>) -> Result<&mut Self, String> {
23    self.replace_with(from, to, Default::default())
24  }
25
26  pub fn replace_all(
27    &mut self,
28    from: &str,
29    to: impl Into<CowStr<'text>>,
30  ) -> Result<&mut Self, String> {
31    self.replace_with(from, to, ReplaceOptions { count: usize::MAX, ..Default::default() })
32  }
33
34  pub fn replace_with(
35    &mut self,
36    from: &str,
37    to: impl Into<CowStr<'text>>,
38    options: ReplaceOptions,
39  ) -> Result<&mut Self, String> {
40    let to: CowStr<'text> = to.into();
41    let matches = memchr::memmem::find_iter(self.source.as_bytes(), from.as_bytes())
42      .take(options.count)
43      .map(|start| (start as u32, (start + from.len()) as u32))
44      .collect::<Vec<_>>();
45    for (match_start, end) in matches {
46      self.update_with(
47        match_start,
48        end,
49        to.clone(),
50        UpdateOptions { overwrite: true, keep_original: options.store_original_in_sourcemap },
51      )?;
52    }
53
54    Ok(self)
55  }
56}