risingwave_expr_impl/scalar/
replace.rs1use risingwave_expr::function;
16
17#[function("replace(varchar, varchar, varchar) -> varchar")]
18pub fn replace(s: &str, from_str: &str, to_str: &str, writer: &mut impl std::fmt::Write) {
19 if from_str.is_empty() {
20 writer.write_str(s).unwrap();
21 return;
22 }
23 let mut last = 0;
24 while let Some(mut start) = s[last..].find(from_str) {
25 start += last;
26 writer.write_str(&s[last..start]).unwrap();
27 writer.write_str(to_str).unwrap();
28 last = start + from_str.len();
29 }
30 writer.write_str(&s[last..]).unwrap();
31}
32
33#[cfg(test)]
34mod tests {
35 use super::*;
36
37 #[test]
38 fn test_replace() {
39 let cases = vec![
40 ("hello, word", "我的", "world", "hello, word"),
41 ("hello, word", "", "world", "hello, word"),
42 ("hello, word", "word", "world", "hello, world"),
43 ("hello, world", "world", "", "hello, "),
44 ("你是❤️,是暖,是希望", "是", "非", "你非❤️,非暖,非希望"),
45 ("👴笑了", "👴", "爷爷", "爷爷笑了"),
46 ];
47
48 for (s, from_str, to_str, expected) in cases {
49 let mut writer = String::new();
50 replace(s, from_str, to_str, &mut writer);
51 assert_eq!(writer, expected);
52 }
53 }
54}