risingwave_expr_impl/scalar/
md5.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 std::fmt::Write;
16
17use md5::{Digest as _, Md5};
18use risingwave_expr::function;
19
20#[function("md5(varchar) -> varchar")]
21pub fn md5(s: &str, writer: &mut impl Write) {
22    write!(writer, "{:x}", Md5::digest(s)).unwrap();
23}
24
25#[function("md5(bytea) -> varchar")]
26pub fn md5_from_bytea(s: &[u8], writer: &mut impl Write) {
27    writer.write_str(&::hex::encode(Md5::digest(s))).unwrap();
28}
29
30#[cfg(test)]
31mod tests {
32    use super::*;
33
34    #[test]
35    fn test_md5() {
36        let cases = [
37            ("hello world", "5eb63bbbe01eeed093cb22bb8f5acdc3"),
38            ("hello RUST", "917b821a0a5f23ab0cfdb36056d2eb9d"),
39            (
40                "abcdefghijklmnopqrstuvwxyz",
41                "c3fcd3d76192e4007dfb496cca67e13b",
42            ),
43        ];
44
45        for (s, expected) in cases {
46            let mut writer = String::new();
47            md5(s, &mut writer);
48            assert_eq!(writer, expected);
49        }
50    }
51
52    #[test]
53    fn test_md5_bytea() {
54        let cases = [
55            ("hello world".as_bytes(), "5eb63bbbe01eeed093cb22bb8f5acdc3"),
56            ("hello RUST".as_bytes(), "917b821a0a5f23ab0cfdb36056d2eb9d"),
57            (
58                "abcdefghijklmnopqrstuvwxyz".as_bytes(),
59                "c3fcd3d76192e4007dfb496cca67e13b",
60            ),
61        ];
62
63        for (s, expected) in cases {
64            let mut writer = String::new();
65            md5_from_bytea(s, &mut writer);
66            assert_eq!(writer, expected);
67        }
68    }
69}