h3ron 0.18.0

High-level rust API for H3
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
use std::borrow::Borrow;
use std::ops::RangeInclusive;

#[cfg(feature = "use-serde")]
use serde::{Deserialize, Serialize};

use crate::collections::indexvec::IndexVec;
use crate::collections::H3CellSet;
use crate::collections::HashSet;
use crate::{compact_cells, Index, H3_MAX_RESOLUTION, H3_MIN_RESOLUTION};
use crate::{Error, H3Cell};

const H3_RESOLUTION_RANGE_USIZE: RangeInclusive<usize> =
    (H3_MIN_RESOLUTION as usize)..=(H3_MAX_RESOLUTION as usize);

/// structure to keep compacted h3ron cells to allow more or less efficient
/// adding of further cells
#[derive(PartialEq, Eq, Debug)]
#[cfg_attr(feature = "use-serde", derive(Serialize, Deserialize))]
pub struct CompactedCellVec {
    /// cells by their resolution. The index of the array is the resolution for the referenced vec
    cells_by_resolution: [Vec<H3Cell>; H3_MAX_RESOLUTION as usize + 1],
}

impl CompactedCellVec {
    pub fn new() -> Self {
        Self {
            cells_by_resolution: Default::default(),
        }
    }

    /// append the contents of another Stack to this one
    ///
    /// Indexes get moved, see [`Vec::append`]
    ///
    /// will trigger a re-compacting when compact is true
    pub fn append(&mut self, other: &mut Self, compact: bool) -> Result<(), Error> {
        let mut resolutions_touched = Vec::new();
        for resolution in H3_RESOLUTION_RANGE_USIZE {
            if !other.cells_by_resolution[resolution].is_empty() {
                resolutions_touched.push(resolution);
                let mut cells = std::mem::take(&mut other.cells_by_resolution[resolution]);
                self.cells_by_resolution[resolution].append(&mut cells);
            }
        }
        if compact {
            if let Some(max_res) = resolutions_touched.iter().max() {
                self.compact_from_resolution_up(*max_res, resolutions_touched)?;
            }
        }
        Ok(())
    }

    pub fn compact(&mut self) -> Result<(), Error> {
        self.compact_from_resolution_up(H3_MAX_RESOLUTION as usize, H3_RESOLUTION_RANGE_USIZE)
    }

    /// append the contents of a vector. The caller is responsible to ensure that
    /// the append cells all are at resolution `resolution`.
    ///
    /// Cells get moved, this is the same API as [`Vec::append`].
    pub fn append_to_resolution(
        &mut self,
        resolution: u8,
        cells: &mut Vec<H3Cell>,
        compact: bool,
    ) -> Result<(), Error> {
        self.cells_by_resolution[resolution as usize].append(cells);
        if compact {
            self.compact_from_resolution_up(resolution as usize, [])?;
        }
        Ok(())
    }

    /// shrink the underlying vec to fit using [`Vec::shrink_to_fit`].
    pub fn shrink_to_fit(&mut self) {
        self.cells_by_resolution
            .iter_mut()
            .for_each(Vec::shrink_to_fit);
    }

    pub fn len(&self) -> usize {
        self.cells_by_resolution
            .iter()
            .fold(0, |acc, cells| acc + cells.len())
    }

    /// length of the vectors for all resolutions. The index of the vec is the resolution
    pub fn len_resolutions(&self) -> Vec<usize> {
        self.cells_by_resolution.iter().map(Vec::len).collect()
    }

    pub fn is_empty(&self) -> bool {
        !self
            .cells_by_resolution
            .iter()
            .any(|cells| !cells.is_empty())
    }

    /// check if the stack contains the cell or any of its parents
    ///
    /// This function is pretty inefficient.
    pub fn contains(&self, mut cell: H3Cell) -> bool {
        if self.is_empty() {
            return false;
        }
        for r in cell.resolution()..=H3_MIN_RESOLUTION {
            cell = match cell.get_parent(r) {
                Ok(i) => i,
                Err(_) => continue,
            };
            if self.cells_by_resolution[r as usize].contains(&cell) {
                return true;
            }
        }
        false
    }

    /// add a single h3 cell
    ///
    /// will trigger a re-compacting when `compact` is set
    #[inline]
    pub fn add_cell(&mut self, cell: H3Cell, compact: bool) -> Result<(), Error> {
        let res = cell.resolution() as usize;
        self.cells_by_resolution[res].push(cell);
        if compact {
            self.compact_from_resolution_up(res, [])?;
        }
        Ok(())
    }

    ///
    ///
    pub fn add_cells<I>(&mut self, cells: I, compact: bool) -> Result<(), Error>
    where
        I: IntoIterator,
        I::Item: Borrow<H3Cell> + Index,
    {
        let mut resolutions_touched = HashSet::default();
        for cell in cells {
            let res = cell.resolution() as usize;
            resolutions_touched.insert(res);
            self.cells_by_resolution[res].push(*(cell.borrow()));
        }

        if compact {
            let recompact_res = resolutions_touched.iter().max();
            if let Some(rr) = recompact_res {
                self.compact_from_resolution_up(*rr, resolutions_touched.into_iter())?;
            }
        }
        Ok(())
    }

    /// iterate over the compacted (or not, depending on if `compact` was called) contents
    pub const fn iter_compacted_cells(&self) -> CompactedCellVecCompactedIterator {
        CompactedCellVecCompactedIterator {
            compacted_vec: self,
            current_resolution: H3_MIN_RESOLUTION as usize,
            current_pos: 0,
        }
    }

    /// get the compacted cells of the given resolution
    ///
    /// parent cells at lower resolutions will not be uncompacted
    pub fn get_compacted_cells_at_resolution(&self, resolution: u8) -> &[H3Cell] {
        &self.cells_by_resolution[resolution as usize]
    }

    /// iterate over the uncompacted cells.
    ///
    /// cells at lower resolutions will be decompacted, cells at higher resolutions will be
    /// ignored.
    pub fn iter_uncompacted_cells(
        &self,
        resolution: u8,
    ) -> CompactedCellVecUncompactedIterator<'_> {
        CompactedCellVecUncompactedIterator {
            compacted_vec: self,
            current_resolution: H3_MIN_RESOLUTION as usize,
            current_pos: 0,
            current_uncompacted: Default::default(),
            iteration_resolution: resolution as usize,
        }
    }

    /// deduplicate the internal cell vectors
    pub fn dedup(&mut self) -> Result<(), Error> {
        self.cells_by_resolution.iter_mut().for_each(|cells| {
            cells.sort_unstable();
            cells.dedup();
        });
        self.purge_children()
    }

    /// the finest resolution contained
    pub fn finest_resolution_contained(&self) -> Option<u8> {
        for resolution in H3_RESOLUTION_RANGE_USIZE.rev() {
            if !self.cells_by_resolution[resolution].is_empty() {
                return Some(resolution as u8);
            }
        }
        None
    }

    /// compact all resolution from the given to 0
    ///
    /// resolutions are skipped when the compacting of the
    /// former finer resolution added no new cells to
    /// the parent resolution unless include_resolutions
    /// forces the recompacting of a given resolution
    fn compact_from_resolution_up<InclResIter>(
        &mut self,
        resolution: usize,
        include_resolutions: InclResIter,
    ) -> Result<(), Error>
    where
        InclResIter: IntoIterator<Item = usize>,
    {
        let mut resolutions_touched = include_resolutions.into_iter().collect::<HashSet<_>>();
        resolutions_touched.insert(resolution);

        for res in ((H3_MIN_RESOLUTION as usize)..=resolution).rev() {
            if !resolutions_touched.contains(&res) {
                // no new cells have been added to this resolution
                continue;
            }

            let mut cells_to_compact = std::mem::take(&mut self.cells_by_resolution[res]);
            cells_to_compact.sort_unstable();
            cells_to_compact.dedup();
            let compacted = compact_cells(&cells_to_compact)?;
            for cell in compacted.iter() {
                let res = cell.resolution() as usize;
                resolutions_touched.insert(res);
                self.cells_by_resolution[res].push(cell);
            }
        }
        self.purge_children()
    }

    /// purge children of cells already contained in lower resolutions
    fn purge_children(&mut self) -> Result<(), Error> {
        let mut lowest_resolution = None;
        for (r, cells) in self.cells_by_resolution.iter().enumerate() {
            if lowest_resolution.is_none() && !cells.is_empty() {
                lowest_resolution = Some(r);
                break;
            }
        }

        if let Some(lowest_res) = lowest_resolution {
            let mut known_cells = self.cells_by_resolution[lowest_res]
                .iter()
                .copied()
                .collect::<H3CellSet>();

            for r in (lowest_res + 1)..=(H3_MAX_RESOLUTION as usize) {
                for cell in std::mem::take(&mut self.cells_by_resolution[r]) {
                    let mut is_parent_known = false;
                    for parent_res in lowest_res..r {
                        if known_cells.contains(&cell.get_parent(parent_res as u8)?) {
                            is_parent_known = true;
                            break;
                        }
                    }
                    if !is_parent_known {
                        known_cells.insert(cell);
                        self.cells_by_resolution[r].push(cell);
                    }
                }
            }
        }
        Ok(())
    }
}

impl Default for CompactedCellVec {
    fn default() -> Self {
        Self::new()
    }
}

/*
impl FromIterator<H3Cell> for CompactedCellVec {
    fn from_iter<T: IntoIterator<Item = H3Cell>>(iter: T) -> Self {
        let mut cv = Self::new();
        cv.add_cells(iter, false);
        cv.compact();
        cv
    }
}

 */

impl TryFrom<Vec<H3Cell>> for CompactedCellVec {
    type Error = Error;

    fn try_from(in_vec: Vec<H3Cell>) -> Result<Self, Self::Error> {
        let mut cv = Self::new();
        cv.add_cells(in_vec.into_iter(), false)?;
        cv.compact()?;
        Ok(cv)
    }
}

pub struct CompactedCellVecCompactedIterator<'a> {
    compacted_vec: &'a CompactedCellVec,
    current_resolution: usize,
    current_pos: usize,
}

impl<'a> Iterator for CompactedCellVecCompactedIterator<'a> {
    type Item = H3Cell;

    fn next(&mut self) -> Option<Self::Item> {
        while self.current_resolution <= (H3_MAX_RESOLUTION as usize) {
            if let Some(value) = self.compacted_vec.cells_by_resolution[self.current_resolution]
                .get(self.current_pos)
            {
                self.current_pos += 1;
                return Some(*value);
            }
            self.current_pos = 0;
            self.current_resolution += 1;
        }
        None
    }
}

pub struct CompactedCellVecUncompactedIterator<'a> {
    compacted_vec: &'a CompactedCellVec,
    current_resolution: usize,
    current_pos: usize,
    current_uncompacted: IndexVec<H3Cell>,
    iteration_resolution: usize,
}

impl<'a> Iterator for CompactedCellVecUncompactedIterator<'a> {
    type Item = Result<H3Cell, Error>;

    fn next(&mut self) -> Option<Self::Item> {
        while self.current_resolution <= self.iteration_resolution {
            if self.current_resolution == self.iteration_resolution {
                let value = self.compacted_vec.cells_by_resolution[self.current_resolution]
                    .get(self.current_pos);
                self.current_pos += 1;
                return value.copied().map(Ok);
            } else if let Some(next) = self.current_uncompacted.pop() {
                return Some(Ok(next));
            } else if let Some(next_parent) = self.compacted_vec.cells_by_resolution
                [self.current_resolution]
                .get(self.current_pos)
            {
                match next_parent.get_children(self.iteration_resolution as u8) {
                    Ok(current_uncompacted) => {
                        self.current_uncompacted = current_uncompacted;
                        self.current_pos += 1;
                        continue;
                    }
                    Err(e) => return Some(Err(e)),
                }
            }
            self.current_resolution += 1;
            self.current_pos = 0;
        }
        None
    }
}

#[cfg(test)]
mod tests {
    use std::convert::TryInto;

    #[cfg(feature = "use-serde")]
    use bincode::{deserialize, serialize};

    use crate::collections::CompactedCellVec;

    #[test]
    fn compactedvec_is_empty() {
        let mut cv = CompactedCellVec::new();
        assert!(cv.is_empty());
        assert_eq!(cv.len(), 0);
        cv.add_cell(0x89283080ddbffff_u64.try_into().unwrap(), false)
            .unwrap();
        assert!(!cv.is_empty());
        assert_eq!(cv.len(), 1);
    }

    #[cfg(feature = "use-serde")]
    #[test]
    fn compactedvec_serde_roundtrip() {
        let mut cv = CompactedCellVec::new();
        cv.add_cell(0x89283080ddbffff_u64.try_into().unwrap(), false)
            .unwrap();
        let serialized_data = serialize(&cv).unwrap();

        let cv_2: CompactedCellVec = deserialize(&serialized_data).unwrap();
        assert_eq!(cv, cv_2);
    }
}