aatree/map/
mod.rs

1use crate::{
2	iter::{AAIntoIter, AAIter},
3	node::{AANode, TraverseStep}
4};
5use alloc::vec::Vec;
6use core::{
7	borrow::Borrow,
8	cmp::Ordering,
9	fmt::{self, Debug},
10	iter::FromIterator,
11	mem
12};
13
14mod entry;
15mod get;
16mod kv;
17
18pub use entry::{Entry, OccupiedEntry, VacantEntry};
19use kv::KeyValue;
20
21#[derive(Clone)]
22pub struct AATreeMap<K, V> {
23	root: AANode<KeyValue<K, V>>,
24	len: usize
25}
26
27impl<K, V> Default for AATreeMap<K, V> {
28	fn default() -> Self {
29		Self::new()
30	}
31}
32
33impl<K: Debug, V: Debug> Debug for AATreeMap<K, V> {
34	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35		f.write_str("{")?;
36		for (i, (k, v)) in self.iter().enumerate() {
37			if i > 0 {
38				f.write_str(", ")?;
39			}
40			k.fmt(f)?;
41			f.write_str(": ")?;
42			v.fmt(f)?;
43		}
44		f.write_str("}")
45	}
46}
47
48impl<K: PartialEq, V: PartialEq> PartialEq for AATreeMap<K, V> {
49	fn eq(&self, other: &Self) -> bool {
50		self.len() == other.len() && self.iter().zip(other).all(|(a, b)| a == b)
51	}
52}
53
54impl<K: Eq, V: Eq> Eq for AATreeMap<K, V> {}
55
56impl<K: PartialOrd, V: PartialOrd> PartialOrd for AATreeMap<K, V> {
57	fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
58		self.iter().partial_cmp(other.iter())
59	}
60}
61
62impl<K: Ord, V: Ord> Ord for AATreeMap<K, V> {
63	fn cmp(&self, other: &Self) -> Ordering {
64		self.iter().cmp(other.iter())
65	}
66}
67
68impl<K, V> AATreeMap<K, V> {
69	/// Construct a new, empty AA-Tree based map.
70	///
71	/// # Example
72	///
73	/// ```rust
74	/// # type AATreeMap = aatree::AATreeMap<i64, ()>;
75	/// let map = AATreeMap::new();
76	/// assert!(map.is_empty());
77	/// ```
78	pub const fn new() -> Self {
79		Self {
80			root: AANode::new(),
81			len: 0
82		}
83	}
84
85	/// Returns the number of elements in the map.
86	///
87	/// # Example
88	///
89	/// ```rust
90	/// # use aatree::AATreeMap;
91	/// let mut map = AATreeMap::new();
92	/// assert_eq!(map.len(), 0);
93	/// map.insert(1, "a");
94	/// assert_eq!(map.len(), 1);
95	/// ```
96	pub fn len(&self) -> usize {
97		self.len
98	}
99
100	/// Returns `true` if the map contains no elements.
101	///
102	/// # Example
103	///
104	/// ```rust
105	/// # use aatree::AATreeMap;
106	/// let mut map = AATreeMap::new();
107	/// assert!(map.is_empty());
108	/// map.insert(1, "a");
109	/// assert!(!map.is_empty());
110	/// ```
111	pub fn is_empty(&self) -> bool {
112		self.len == 0
113	}
114
115	/// Clears the map, removing all elements.
116	///
117	/// # Example
118	///
119	/// ```rust
120	/// # use aatree::AATreeMap;
121	/// let mut map = AATreeMap::new();
122	/// map.insert(1, "a");
123	/// map.clear();
124	/// assert!(map.is_empty());
125	/// ```
126	pub fn clear(&mut self) {
127		self.root = AANode::new();
128		self.len = 0;
129	}
130
131	/// Creates an iterator over this map that visits all entries with the keys in ascending order.
132	pub fn iter(&self) -> AAIter<'_, KeyValue<K, V>, (&K, &V)> {
133		self.into_iter()
134	}
135
136	/// Creates an iterator visiting all the keys, in sorted order.
137	pub fn keys(&self) -> impl Iterator<Item = &K> {
138		// TODO is there a better way to implement this?
139		self.iter().map(|(k, _)| k)
140	}
141
142	/// Creates an iterator visiting all the values, in sorted order.
143	pub fn values(&self) -> impl Iterator<Item = &V> {
144		// TODO is there a better way to implement this?
145		self.iter().map(|(_, v)| v)
146	}
147
148	/// Creates a consuming iterator visiting all the keys, in sorted order. The map
149	/// cannot be used after calling this.
150	pub fn into_keys(self) -> impl Iterator<Item = K> {
151		// TODO is there a better way to implement this?
152		self.into_iter().map(|(k, _)| k)
153	}
154
155	/// Creates a consuming iterator visiting all the values, in order by key. The map
156	/// cannot be used after calling this.
157	pub fn into_values(self) -> impl Iterator<Item = V> {
158		// TODO is there a better way to implement this?
159		self.into_iter().map(|(_, v)| v)
160	}
161
162	/// Insert a new element into the map, or overwrite an existing element
163	/// with the same key. If a value was overwritten, the old value will be
164	/// returned.
165	///
166	/// # Example
167	///
168	/// ```rust
169	/// # use aatree::AATreeMap;
170	/// let mut map = AATreeMap::new();
171	/// map.insert(1, "a");
172	/// assert_eq!(map.get(&1), Some(&"a"));
173	/// map.insert(1, "b");
174	/// assert_eq!(map.get(&1), Some(&"b"));
175	/// ```
176	pub fn insert(&mut self, key: K, value: V) -> Option<V>
177	where
178		K: Ord
179	{
180		let inserted = self.root.insert_or_replace(KeyValue { key, value });
181		match inserted {
182			None => {
183				self.len += 1;
184				None
185			},
186			Some(entry) => Some(entry.value)
187		}
188	}
189
190	/// Moves all elements from `other` into `self`, leaving `other` empty.
191	///
192	/// # Examples
193	///
194	/// ```
195	/// use std::collections::BTreeMap;
196	///
197	/// let mut a = BTreeMap::new();
198	/// a.insert(1, "a");
199	/// a.insert(2, "b");
200	/// a.insert(3, "c");
201	///
202	/// let mut b = BTreeMap::new();
203	/// b.insert(3, "d");
204	/// b.insert(4, "e");
205	/// b.insert(5, "f");
206	///
207	/// a.append(&mut b);
208	///
209	/// assert_eq!(a.len(), 5);
210	/// assert_eq!(b.len(), 0);
211	///
212	/// assert_eq!(a[&1], "a");
213	/// assert_eq!(a[&2], "b");
214	/// assert_eq!(a[&3], "d");
215	/// assert_eq!(a[&4], "e");
216	/// assert_eq!(a[&5], "f");
217	/// ```
218	pub fn append(&mut self, other: &mut Self)
219	where
220		K: Ord
221	{
222		self.extend(mem::take(other));
223	}
224
225	/// Check if a key is contained within this map.
226	///
227	/// # Example
228	///
229	/// ```rust
230	/// # use aatree::AATreeMap;
231	/// let mut map = AATreeMap::new();
232	/// assert!(!map.contains_key(&1));
233	/// map.insert(1, "a");
234	/// assert!(map.contains_key(&1));
235	/// ```
236	pub fn contains_key<Q>(&self, k: &Q) -> bool
237	where
238		K: Borrow<Q> + Ord,
239		Q: Ord + ?Sized
240	{
241		self.root
242			.traverse(
243				|content| match content.key.borrow().cmp(k) {
244					Ordering::Greater => TraverseStep::Left,
245					Ordering::Less => TraverseStep::Right,
246					Ordering::Equal => TraverseStep::Value(Some(()))
247				},
248				|_, sub| sub
249			)
250			.is_some()
251	}
252
253	/// Remove a key from the map if it exists, and return the value that was previously stored
254	/// in the map for that key.
255	///
256	/// # Example
257	///
258	/// ```rust
259	/// # use aatree::AATreeMap;
260	/// let mut map = AATreeMap::new();
261	/// map.insert(1, "a");
262	/// map.insert(2, "b");
263	/// assert_eq!(map.get(&1), Some(&"a"));
264	/// let value = map.remove(&1);
265	/// assert_eq!(value, Some("a"));
266	/// assert_eq!(map.get(&1), None);
267	/// ```
268	pub fn remove<Q>(&mut self, k: &Q) -> Option<V>
269	where
270		K: Borrow<Q> + Ord,
271		Q: Ord + ?Sized
272	{
273		self.root.remove::<Q, K>(k).map(|entry| entry.value)
274	}
275
276	/// Remove a key from the map if it exists, and return the key and the value that was
277	/// previously stored in the map for that key.
278	///
279	/// # Example
280	///
281	/// ```rust
282	/// # use aatree::AATreeMap;
283	/// let mut map = AATreeMap::new();
284	/// map.insert(1, "a");
285	/// map.insert(2, "b");
286	/// assert_eq!(map.get(&1), Some(&"a"));
287	/// let value = map.remove(&1);
288	/// assert_eq!(value, Some("a"));
289	/// assert_eq!(map.get(&1), None);
290	/// ```
291	pub fn remove_entry<Q>(&mut self, k: &Q) -> Option<(K, V)>
292	where
293		K: Borrow<Q> + Ord,
294		Q: Ord + ?Sized
295	{
296		self.root.remove::<Q, K>(k).map(KeyValue::into_tuple)
297	}
298}
299
300impl<K: Ord, V> FromIterator<(K, V)> for AATreeMap<K, V> {
301	fn from_iter<I>(iter: I) -> Self
302	where
303		I: IntoIterator<Item = (K, V)>
304	{
305		let mut map = Self::new();
306		for (key, value) in iter {
307			map.insert(key, value);
308		}
309		map
310	}
311}
312
313impl<K: Ord, V, const N: usize> From<[(K, V); N]> for AATreeMap<K, V> {
314	fn from(array: [(K, V); N]) -> Self {
315		array.into_iter().collect()
316	}
317}
318
319impl<K: Ord, V> From<Vec<(K, V)>> for AATreeMap<K, V> {
320	fn from(vec: Vec<(K, V)>) -> Self {
321		vec.into_iter().collect()
322	}
323}
324
325impl<K: Ord, V> Extend<(K, V)> for AATreeMap<K, V> {
326	fn extend<I: IntoIterator<Item = (K, V)>>(&mut self, iter: I) {
327		for (key, value) in iter {
328			self.insert(key, value);
329		}
330	}
331}
332
333impl<'a, K: Ord + Copy + 'a, V: Ord + Copy + 'a> Extend<(&'a K, &'a V)>
334	for AATreeMap<K, V>
335{
336	fn extend<I: IntoIterator<Item = (&'a K, &'a V)>>(&mut self, iter: I) {
337		self.extend(iter.into_iter().map(|(k, v)| (*k, *v)))
338	}
339}
340
341impl<K, V> IntoIterator for AATreeMap<K, V> {
342	type Item = (K, V);
343	type IntoIter = AAIntoIter<KeyValue<K, V>, (K, V)>;
344
345	fn into_iter(self) -> Self::IntoIter {
346		AAIntoIter::new(self.root, self.len)
347	}
348}
349
350impl<'a, K, V> IntoIterator for &'a AATreeMap<K, V> {
351	type Item = (&'a K, &'a V);
352	type IntoIter = AAIter<'a, KeyValue<K, V>, (&'a K, &'a V)>;
353
354	fn into_iter(self) -> Self::IntoIter {
355		AAIter::new(&self.root, self.len)
356	}
357}