risingwave_expr_impl/scalar/crc.rs
1// Copyright 2026 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/// Computes the CRC-32 value of the given bytes.
18///
19/// ```slt
20/// query I
21/// select crc32('\x00'::bytea);
22/// ----
23/// 3523407757
24///
25/// query I
26/// select crc32(''::bytea);
27/// ----
28/// 0
29///
30/// query I
31/// select crc32('The quick brown fox jumps over the lazy dog'::bytea);
32/// ----
33/// 1095738169
34/// ```
35#[function("crc32(bytea) -> int8")]
36pub fn crc32(data: &[u8]) -> i64 {
37 crc32fast::hash(data) as i64
38}
39
40/// Computes the CRC-32C value of the given bytes.
41///
42/// ```slt
43/// query I
44/// select crc32c(''::bytea);
45/// ----
46/// 0
47///
48/// query I
49/// select crc32c('\x00'::bytea);
50/// ----
51/// 1383945041
52/// ```
53#[function("crc32c(bytea) -> int8")]
54pub fn crc32c(data: &[u8]) -> i64 {
55 crc32c::crc32c(data) as i64
56}
57
58#[cfg(test)]
59mod tests {
60 use super::*;
61
62 #[test]
63 fn test_crc32() {
64 assert_eq!(crc32(b""), 0);
65 assert_eq!(crc32(b"\x00"), 3523407757);
66 assert_eq!(crc32(b"123456789"), 3421780262); // standard CRC-32 check value
67 assert_eq!(
68 crc32(b"The quick brown fox jumps over the lazy dog"),
69 1095738169
70 );
71 }
72
73 #[test]
74 fn test_crc32c() {
75 assert_eq!(crc32c(b""), 0);
76 assert_eq!(crc32c(b"\x00"), 1383945041);
77 assert_eq!(crc32c(b"123456789"), 3808858755); // standard CRC-32C check value
78 }
79}