rustworkx_core/
dictmap.rs

1// Licensed under the Apache License, Version 2.0 (the "License"); you may
2// not use this file except in compliance with the License. You may obtain
3// a copy of the License at
4//
5//     http://www.apache.org/licenses/LICENSE-2.0
6//
7// Unless required by applicable law or agreed to in writing, software
8// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
9// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
10// License for the specific language governing permissions and limitations
11// under the License.
12
13//! This module contains the [`DictMap`] type alias which is a combination of
14//! [`IndexMap`] and [`Foldhash`].
15//!
16//! It is used as a return type for rustworkx for compatibility
17//! with Python's dict which preserves insertion order.
18//!
19//! [`Foldhash`]: https://crates.io/crates/foldhash
20
21use indexmap::IndexMap;
22
23/// Convenient alias to build an [`IndexMap`] using a custom hasher.
24/// For the moment, we use foldhash which is the default hasher
25/// for [`HashMap`], another hashmap we use.
26///
27/// [`HashMap`]: https://docs.rs/hashbrown/0.11.2/hashbrown/hash_map/struct.HashMap.html
28pub type DictMap<K, V> = IndexMap<K, V, foldhash::fast::RandomState>;
29
30pub trait InitWithHasher {
31    fn new() -> Self
32    where
33        Self: Sized;
34
35    fn with_capacity(n: usize) -> Self
36    where
37        Self: Sized;
38}
39
40impl<K, V> InitWithHasher for DictMap<K, V> {
41    #[inline]
42    fn new() -> Self {
43        indexmap::IndexMap::with_capacity_and_hasher(0, foldhash::fast::RandomState::default())
44    }
45
46    #[inline]
47    fn with_capacity(n: usize) -> Self {
48        indexmap::IndexMap::with_capacity_and_hasher(n, foldhash::fast::RandomState::default())
49    }
50}