hextree 0.3.2

Location to value mapping.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
//! A HexTreeMap is a structure for mapping geographical regions to values.

pub use crate::entry::{Entry, OccupiedEntry, VacantEntry};
use crate::{
    cell::CellStack,
    compaction::{Compactor, NullCompactor},
    digits::Digits,
    node::Node,
    Cell,
};
use std::{cmp::PartialEq, iter::FromIterator};

/// A HexTreeMap is a structure for mapping geographical regions to
/// values.
///
///
/// [serde]: https://docs.rs/serde/latest/serde/
///
/// # Usage
///
/// <iframe src="https://kepler.gl/demo?mapUrl=https://gist.githubusercontent.com/JayKickliter/8f91a8437b7dd89321b22cde50e71c3a/raw/a60c83cb15e75aba660fb6535d8e0061fa504205/monaco.kepler.json" width="100%" height="600"></iframe>
///
/// ----
///
/// Let's create a HexTreeMap for Monaco as visualized in the map
///
/// ```
/// # fn main() -> Result<(), Box<dyn std::error::Error>> {
/// use hextree::{Cell, compaction::EqCompactor, HexTreeMap};
/// #
/// #    use byteorder::{LittleEndian as LE, ReadBytesExt};
/// #    let idx_bytes = include_bytes!("../assets//monaco.res12.h3idx");
/// #    let rdr = &mut idx_bytes.as_slice();
/// #    let mut cells = Vec::new();
/// #    while let Ok(idx) = rdr.read_u64::<LE>() {
/// #        cells.push(Cell::from_raw(idx)?);
/// #    }
///
/// #[derive(Debug, Copy, Clone, PartialEq, Eq)]
/// enum Region {
///     Monaco,
/// }
///
/// // Construct map with a compactor that automatically combines
/// // cells with the same save value.
/// let mut monaco = HexTreeMap::with_compactor(EqCompactor);
///
/// // Now extend the map with cells and a region value.
/// monaco.extend(cells.iter().copied().zip(std::iter::repeat(Region::Monaco)));
///
/// // You can see in the map above that our set covers Point 1 (green
/// // check) but not Point 2 (red x), let's test that.
/// // Lat/lon 43.73631, 7.42418 @ res 12
/// let point_1 = Cell::from_raw(0x8c3969a41da15ff)?;
/// // Lat/lon 43.73008, 7.42855 @ res 12
/// let point_2 = Cell::from_raw(0x8c3969a415065ff)?;
///
/// assert_eq!(monaco.get(point_1).unzip().1, Some(&Region::Monaco));
/// assert_eq!(monaco.get(point_2).unzip().1, None);
///
/// #     Ok(())
/// # }
/// ```
#[derive(Clone, PartialEq, Eq)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct HexTreeMap<V, C = NullCompactor> {
    /// All h3 0 base cell indices in the tree
    pub(crate) nodes: Box<[Option<Box<Node<V>>>]>,
    /// User-provided compator. Defaults to the null compactor.
    compactor: C,
}

impl<V> HexTreeMap<V, NullCompactor> {
    /// Constructs a new, empty `HexTreeMap` with the no-op
    /// `NullCompactor`.
    ///
    /// Incurs a single heap allocation to store all 122 resolution-0
    /// H3 cells.
    pub fn new() -> Self {
        Self {
            nodes: std::iter::repeat_with(|| None)
                .take(122)
                .collect::<Box<[Option<Box<Node<V>>>]>>(),
            compactor: NullCompactor,
        }
    }
}

impl<V, C: Compactor<V>> HexTreeMap<V, C> {
    /// Adds a cell/value pair to the set.
    pub fn insert(&mut self, cell: Cell, value: V) {
        let base_cell = cell.base();
        let digits = Digits::new(cell);
        match self.nodes[base_cell as usize].as_mut() {
            Some(node) => node.insert(cell, 0_u8, digits, value, &mut self.compactor),
            None => {
                let mut node = Box::new(Node::new());
                node.insert(cell, 0_u8, digits, value, &mut self.compactor);
                self.nodes[base_cell as usize] = Some(node);
            }
        }
    }
}

impl<V, C> HexTreeMap<V, C> {
    /// Constructs a new, empty `HexTreeMap` with the provided
    /// [compactor][crate::compaction].
    ///
    /// Incurs a single heap allocation to store all 122 resolution-0
    /// H3 cells.
    pub fn with_compactor(compactor: C) -> Self {
        Self {
            nodes: std::iter::repeat_with(|| None)
                .take(122)
                .collect::<Box<[Option<Box<Node<V>>>]>>(),
            compactor,
        }
    }

    /// Replace the current compactor with the new one, consuming
    /// `self`.
    ///
    /// This method is useful if you want to use one compaction
    /// strategy for creating an initial, then another one for updates
    /// later.
    pub fn replace_compactor<NewC>(self, new_compactor: NewC) -> HexTreeMap<V, NewC> {
        HexTreeMap {
            nodes: self.nodes,
            compactor: new_compactor,
        }
    }

    /// Returns the number of H3 cells in the set.
    ///
    /// This method only considers complete, or leaf, cells in the
    /// set. Due to automatic compaction, this number may be
    /// significantly smaller than the number of source cells used to
    /// create the set.
    pub fn len(&self) -> usize {
        self.nodes.iter().flatten().map(|node| node.len()).sum()
    }

    /// Returns `true` if the set contains no cells.
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns `true` if the set fully contains `cell`.
    ///
    /// This method will return `true` if any of the following are
    /// true:
    ///
    /// 1. There was an earlier [insert][Self::insert] call with
    ///    precisely this target cell.
    /// 2. Several previously inserted cells coalesced into
    ///    precisely this target cell.
    /// 3. The set contains a complete (leaf) parent of this target
    ///    cell due to 1 or 2.
    pub fn contains(&self, cell: Cell) -> bool {
        let base_cell = cell.base();
        match self.nodes[base_cell as usize].as_ref() {
            Some(node) => {
                let digits = Digits::new(cell);
                node.contains(digits)
            }
            None => false,
        }
    }

    /// Returns a reference to the value corresponding to the given
    /// target cell or one of its parents.
    ///
    /// Note that this method also returns a Cell, which may be a
    /// parent of the target cell provided.
    #[inline]
    pub fn get(&self, cell: Cell) -> Option<(Cell, &V)> {
        match self.get_raw(cell) {
            Some((cell, Node::Leaf(val))) => Some((cell, val)),
            _ => None,
        }
    }

    #[inline]
    pub(crate) fn get_raw(&self, cell: Cell) -> Option<(Cell, &Node<V>)> {
        let base_cell = cell.base();
        match self.nodes[base_cell as usize].as_ref() {
            Some(node) => {
                let digits = Digits::new(cell);
                node.get(0, cell, digits)
            }
            None => None,
        }
    }

    /// Returns a mutable reference to the value corresponding to the
    /// given target cell or one of its parents.
    ///
    /// Note that this method also returns a Cell, which may be a
    /// parent of the target cell provided.
    #[inline]
    pub fn get_mut(&mut self, cell: Cell) -> Option<(Cell, &mut V)> {
        match self.get_raw_mut(cell) {
            Some((cell, &mut Node::Leaf(ref mut val))) => Some((cell, val)),
            _ => None,
        }
    }

    #[inline]
    pub(crate) fn get_raw_mut(&mut self, cell: Cell) -> Option<(Cell, &mut Node<V>)> {
        let base_cell = cell.base();
        match self.nodes[base_cell as usize].as_mut() {
            Some(node) => {
                let digits = Digits::new(cell);
                node.get_mut(0, cell, digits)
            }
            None => None,
        }
    }

    /// Gets the entry in the map for the corresponding cell.
    pub fn entry(&'_ mut self, cell: Cell) -> Entry<'_, V, C> {
        if self.get(cell).is_none() {
            return Entry::Vacant(VacantEntry {
                target_cell: cell,
                map: self,
            });
        }
        Entry::Occupied(OccupiedEntry {
            target_cell: cell,
            cell_value: self.get_mut(cell).unwrap(),
        })
    }

    /// An iterator visiting all cell-value pairs in arbitrary order.
    pub fn iter(&self) -> impl Iterator<Item = (Cell, &V)> {
        crate::iteration::Iter::new(&self.nodes, CellStack::new())
    }

    /// An iterator visiting all cell-value pairs in arbitrary order
    /// with mutable references to the values.
    pub fn iter_mut(&mut self) -> impl Iterator<Item = (Cell, &mut V)> {
        crate::iteration::IterMut::new(&mut self.nodes, CellStack::new())
    }

    /// An iterator visiting the specified cell or its children
    /// references to the values.
    pub fn subtree_iter(&self, cell: Cell) -> impl Iterator<Item = (Cell, &V)> {
        let base_cell = cell.base();
        match self.nodes[base_cell as usize].as_ref() {
            Some(node) => {
                let digits = Digits::new(cell);
                match node.get(0, cell, digits) {
                    Some((cell, Node::Leaf(val))) => Some((cell, val))
                        .into_iter()
                        .chain(crate::iteration::Iter::empty()),
                    Some((cell, Node::Parent(children))) => None
                        .into_iter()
                        .chain(crate::iteration::Iter::new(children, CellStack::from(cell))),
                    None => None.into_iter().chain(crate::iteration::Iter::empty()),
                }
            }
            None => None.into_iter().chain(crate::iteration::Iter::empty()),
        }
    }

    /// An iterator visiting the specified cell or its children with
    /// mutable references to the values.
    pub fn subtree_iter_mut(&mut self, cell: Cell) -> impl Iterator<Item = (Cell, &mut V)> {
        let base_cell = cell.base();
        match self.nodes[base_cell as usize].as_mut() {
            Some(node) => {
                let digits = Digits::new(cell);
                match node.get_mut(0, cell, digits) {
                    Some((cell, Node::Leaf(val))) => Some((cell, val))
                        .into_iter()
                        .chain(crate::iteration::IterMut::empty()),
                    Some((cell, Node::Parent(children))) => None.into_iter().chain(
                        crate::iteration::IterMut::new(children, CellStack::from(cell)),
                    ),
                    None => None.into_iter().chain(crate::iteration::IterMut::empty()),
                }
            }
            None => None.into_iter().chain(crate::iteration::IterMut::empty()),
        }
    }
}

impl<V: PartialEq> Default for HexTreeMap<V, NullCompactor> {
    fn default() -> Self {
        HexTreeMap::new()
    }
}

impl<V> FromIterator<(Cell, V)> for HexTreeMap<V, NullCompactor> {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (Cell, V)>,
    {
        let mut map = HexTreeMap::new();
        for (cell, value) in iter {
            map.insert(cell, value);
        }
        map
    }
}

impl<'a, V: Copy + 'a> FromIterator<(&'a Cell, &'a V)> for HexTreeMap<V, NullCompactor> {
    fn from_iter<I>(iter: I) -> Self
    where
        I: IntoIterator<Item = (&'a Cell, &'a V)>,
    {
        let mut map = HexTreeMap::new();
        for (cell, value) in iter {
            map.insert(*cell, *value);
        }
        map
    }
}

impl<V, C: Compactor<V>> Extend<(Cell, V)> for HexTreeMap<V, C> {
    fn extend<I: IntoIterator<Item = (Cell, V)>>(&mut self, iter: I) {
        for (cell, val) in iter {
            self.insert(cell, val)
        }
    }
}

impl<'a, V: Copy + 'a, C: Compactor<V>> Extend<(&'a Cell, &'a V)> for HexTreeMap<V, C> {
    fn extend<I: IntoIterator<Item = (&'a Cell, &'a V)>>(&mut self, iter: I) {
        for (cell, val) in iter {
            self.insert(*cell, *val)
        }
    }
}

impl<V, C> std::ops::Index<Cell> for HexTreeMap<V, C> {
    type Output = V;

    /// Returns a reference to the value corresponding to the supplied
    /// key.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> hextree::Result<()> {;
    /// use hextree::{Cell, HexTreeMap};
    ///
    /// let mut map = HexTreeMap::new();
    /// let eiffel_tower_res12 = Cell::from_raw(0x8c1fb46741ae9ff)?;
    ///
    /// map.insert(eiffel_tower_res12, "France");
    /// assert_eq!(map[eiffel_tower_res12], "France");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the cell is not present in the `HexTreeMap`.
    fn index(&self, cell: Cell) -> &V {
        self.get(cell).expect("no entry found for cell").1
    }
}

impl<V, C> std::ops::Index<&Cell> for HexTreeMap<V, C> {
    type Output = V;

    /// Returns a reference to the value corresponding to the supplied
    /// key.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> hextree::Result<()> {;
    /// use hextree::{Cell, HexTreeMap};
    ///
    /// let mut map = HexTreeMap::new();
    /// let eiffel_tower_res12 = Cell::from_raw(0x8c1fb46741ae9ff)?;
    ///
    /// map.insert(eiffel_tower_res12, "France");
    /// assert_eq!(map[&eiffel_tower_res12], "France");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the cell is not present in the `HexTreeMap`.
    fn index(&self, cell: &Cell) -> &V {
        self.get(*cell).expect("no entry found for cell").1
    }
}

impl<V, C> std::ops::IndexMut<Cell> for HexTreeMap<V, C> {
    /// Returns a reference to the value corresponding to the supplied
    /// key.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> hextree::Result<()> {;
    /// use hextree::{Cell, HexTreeMap};
    ///
    /// let mut map = HexTreeMap::new();
    /// let eiffel_tower_res12 = Cell::from_raw(0x8c1fb46741ae9ff)?;
    ///
    /// map.insert(eiffel_tower_res12, "France");
    /// assert_eq!(map[eiffel_tower_res12], "France");
    ///
    /// map[eiffel_tower_res12] = "Paris";
    /// assert_eq!(map[eiffel_tower_res12], "Paris");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the cell is not present in the `HexTreeMap`.
    fn index_mut(&mut self, cell: Cell) -> &mut V {
        self.get_mut(cell).expect("no entry found for cell").1
    }
}

impl<V, C> std::ops::IndexMut<&Cell> for HexTreeMap<V, C> {
    /// Returns a reference to the value corresponding to the supplied
    /// key.
    ///
    /// # Examples
    ///
    /// ```
    /// # fn main() -> hextree::Result<()> {;
    /// use hextree::{Cell, HexTreeMap};
    ///
    /// let mut map = HexTreeMap::new();
    /// let eiffel_tower_res12 = Cell::from_raw(0x8c1fb46741ae9ff)?;
    ///
    /// map.insert(eiffel_tower_res12, "France");
    /// assert_eq!(map[&eiffel_tower_res12], "France");
    ///
    /// map[&eiffel_tower_res12] = "Paris";
    /// assert_eq!(map[&eiffel_tower_res12], "Paris");
    /// # Ok(())
    /// # }
    /// ```
    ///
    /// # Panics
    ///
    /// Panics if the cell is not present in the `HexTreeMap`.
    fn index_mut(&mut self, cell: &Cell) -> &mut V {
        self.get_mut(*cell).expect("no entry found for cell").1
    }
}

impl<V: std::fmt::Debug, C> std::fmt::Debug for HexTreeMap<V, C> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("{")?;
        let mut iter = self.iter();
        if let Some((cell, val)) = iter.next() {
            write!(f, "{cell:?}: {val:?}")?
        }
        for (cell, val) in iter {
            write!(f, ", {cell:?}: {val:?}")?
        }
        f.write_str("}")
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn map_is_send() {
        fn assert_send<T: Send>() {}
        assert_send::<HexTreeMap<i32>>();
    }

    #[test]
    fn map_is_sync() {
        fn assert_sync<T: Sync>() {}
        assert_sync::<HexTreeMap<i32>>();
    }
}