rocketmq_common/common/hasher/string_hasher.rs
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one or more
3 * contributor license agreements. See the NOTICE file distributed with
4 * this work for additional information regarding copyright ownership.
5 * The ASF licenses this file to You under the Apache License, Version 2.0
6 * (the "License"); you may not use this file except in compliance with
7 * the License. You may obtain a copy of the License at
8 *
9 * http://www.apache.org/licenses/LICENSE-2.0
10 *
11 * Unless required by applicable law or agreed to in writing, software
12 * distributed under the License is distributed on an "AS IS" BASIS,
13 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14 * See the License for the specific language governing permissions and
15 * limitations under the License.
16 */
17pub struct JavaStringHasher;
18
19impl JavaStringHasher {
20 pub fn hash_str(s: &str) -> i32 {
21 let mut state = 0i32;
22 if !s.is_empty() {
23 for c in s.chars() {
24 state = state.wrapping_mul(31).wrapping_add(c as i32);
25 }
26 }
27 state
28 }
29}
30
31#[cfg(test)]
32mod tests {
33 use super::*;
34 #[test]
35 fn hash_str_with_non_empty_string() {
36 let result = JavaStringHasher::hash_str("hello");
37 assert_eq!(result, 99162322);
38 }
39
40 #[test]
41 fn hash_str_with_empty_string() {
42 let result = JavaStringHasher::hash_str("");
43 assert_eq!(result, 0);
44 }
45
46 #[test]
47 fn hash_str_with_special_characters() {
48 let result = JavaStringHasher::hash_str("!@#");
49 assert_eq!(result, 33732);
50 }
51
52 #[test]
53 fn hash_str_with_long_string() {
54 let result = JavaStringHasher::hash_str("a".repeat(1000).as_str());
55 assert_eq!(result, 904019584);
56 }
57}