parquet/util/interner.rs
1// Licensed to the Apache Software Foundation (ASF) under one
2// or more contributor license agreements. See the NOTICE file
3// distributed with this work for additional information
4// regarding copyright ownership. The ASF licenses this file
5// to you under the Apache License, Version 2.0 (the
6// "License"); you may not use this file except in compliance
7// with 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,
12// software distributed under the License is distributed on an
13// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
14// KIND, either express or implied. See the License for the
15// specific language governing permissions and limitations
16// under the License.
17
18use crate::data_type::AsBytes;
19use hashbrown::HashTable;
20
21const DEFAULT_DEDUP_CAPACITY: usize = 4096;
22
23/// Storage trait for [`Interner`]
24pub trait Storage {
25 type Key: Copy;
26
27 type Value: AsBytes + ?Sized;
28
29 /// Gets an element by its key
30 fn get(&self, idx: Self::Key) -> &Self::Value;
31
32 /// Adds a new element, returning the key
33 fn push(&mut self, value: &Self::Value) -> Self::Key;
34
35 /// Return an estimate of the memory used in this storage, in bytes
36 fn estimated_memory_size(&self) -> usize;
37}
38
39/// A generic value interner supporting various different [`Storage`]
40#[derive(Debug, Default)]
41pub struct Interner<S: Storage> {
42 state: ahash::RandomState,
43
44 /// Used to provide a lookup from value to unique value
45 dedup: HashTable<S::Key>,
46
47 storage: S,
48}
49
50impl<S: Storage> Interner<S> {
51 /// Create a new `Interner` with the provided storage
52 pub fn new(storage: S) -> Self {
53 Self {
54 state: Default::default(),
55 dedup: HashTable::with_capacity(DEFAULT_DEDUP_CAPACITY),
56 storage,
57 }
58 }
59
60 /// Intern the value, returning the interned key, and if this was a new value
61 pub fn intern(&mut self, value: &S::Value) -> S::Key {
62 let hash = self.state.hash_one(value.as_bytes());
63
64 *self
65 .dedup
66 .entry(
67 hash,
68 // Compare bytes rather than directly comparing values so NaNs can be interned
69 |index| value.as_bytes() == self.storage.get(*index).as_bytes(),
70 |key| self.state.hash_one(self.storage.get(*key).as_bytes()),
71 )
72 .or_insert_with(|| self.storage.push(value))
73 .get()
74 }
75
76 /// Return estimate of the memory used, in bytes
77 pub fn estimated_memory_size(&self) -> usize {
78 self.storage.estimated_memory_size() + self.dedup.allocation_size()
79 }
80
81 /// Returns the storage for this interner
82 pub fn storage(&self) -> &S {
83 &self.storage
84 }
85
86 /// Unwraps the inner storage
87 #[cfg(feature = "arrow")]
88 pub fn into_inner(self) -> S {
89 self.storage
90 }
91}