common_base/
hash.rs

1// Copyright 2023 Greptime Team
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::hash::BuildHasher;
16
17use ahash::RandomState;
18use serde::{Deserialize, Serialize};
19
20/// A random state with fixed seeds.
21///
22/// This is used to ensure that the hash values are consistent across
23/// different processes, and easy to serialize and deserialize.
24#[derive(Debug)]
25pub struct FixedRandomState {
26    state: RandomState,
27}
28
29impl FixedRandomState {
30    // some random seeds
31    const RANDOM_SEED_0: u64 = 0x517cc1b727220a95;
32    const RANDOM_SEED_1: u64 = 0x428a2f98d728ae22;
33    const RANDOM_SEED_2: u64 = 0x7137449123ef65cd;
34    const RANDOM_SEED_3: u64 = 0xb5c0fbcfec4d3b2f;
35
36    pub fn new() -> Self {
37        Self {
38            state: ahash::RandomState::with_seeds(
39                Self::RANDOM_SEED_0,
40                Self::RANDOM_SEED_1,
41                Self::RANDOM_SEED_2,
42                Self::RANDOM_SEED_3,
43            ),
44        }
45    }
46}
47
48impl Default for FixedRandomState {
49    fn default() -> Self {
50        Self::new()
51    }
52}
53
54impl BuildHasher for FixedRandomState {
55    type Hasher = ahash::AHasher;
56
57    fn build_hasher(&self) -> Self::Hasher {
58        self.state.build_hasher()
59    }
60
61    fn hash_one<T: std::hash::Hash>(&self, x: T) -> u64 {
62        self.state.hash_one(x)
63    }
64}
65
66impl Serialize for FixedRandomState {
67    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
68    where
69        S: serde::Serializer,
70    {
71        serializer.serialize_unit()
72    }
73}
74
75impl<'de> Deserialize<'de> for FixedRandomState {
76    fn deserialize<D>(_deserializer: D) -> Result<Self, D::Error>
77    where
78        D: serde::Deserializer<'de>,
79    {
80        Ok(Self::new())
81    }
82}
83
84pub fn partition_expr_version(expr_json: Option<&str>) -> u64 {
85    let expr = expr_json.unwrap_or_default();
86    if expr.is_empty() {
87        return 0;
88    }
89    FixedRandomState::new().hash_one(expr)
90}