Skip to main content

rocketmq_model/common/hasher/
string_hasher.rs

1// Copyright 2023 The RocketMQ Rust Authors
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
15pub struct JavaStringHasher;
16
17impl JavaStringHasher {
18    pub fn hash_str(s: &str) -> i32 {
19        let mut h = 0i32;
20        if !s.is_empty() {
21            for c in s.encode_utf16() {
22                h = h.wrapping_mul(31).wrapping_add(c as i32);
23            }
24        }
25        h
26    }
27}
28
29#[cfg(test)]
30mod tests {
31    use super::*;
32    #[test]
33    fn hash_str_with_non_empty_string() {
34        let result = JavaStringHasher::hash_str("hello");
35        assert_eq!(result, 99162322);
36    }
37
38    #[test]
39    fn hash_str_with_empty_string() {
40        let result = JavaStringHasher::hash_str("");
41        assert_eq!(result, 0);
42    }
43
44    #[test]
45    fn hash_str_with_special_characters() {
46        let result = JavaStringHasher::hash_str("!@#");
47        assert_eq!(result, 33732);
48    }
49
50    #[test]
51    fn hash_str_with_long_string() {
52        let result = JavaStringHasher::hash_str("a".repeat(1000).as_str());
53        assert_eq!(result, 904019584);
54    }
55}