risingwave_expr_impl/scalar/
replace.rs

1// Copyright 2025 RisingWave Labs
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15use 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}