kitsune2_dht 0.4.1

The DHT model for kitsune2
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
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
use crate::SECTOR_SIZE;
use kitsune2_api::{DhtArc, K2Error, K2Result};
use std::collections::HashSet;

/// Represents a set of [DhtArc]s.
///
/// A set of [DhtArc]s is combined as a set union into an [ArcSet].
///
/// To restrict [`crate::dht::Dht`] operations to a specific set of sectors, the [`ArcSet`]s of two
/// DHTs can be intersected to find the common sectors, using [ArcSet::intersection].
#[derive(Clone, PartialEq)]
pub struct ArcSet {
    inner: HashSet<u32>,
}

impl std::fmt::Debug for ArcSet {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut dbg = f.debug_struct("ArcSet");
        match self.inner.len() {
            0 => dbg.field("sectors", &"Empty").finish(),
            len if len == (u32::MAX / SECTOR_SIZE + 1) as usize => {
                dbg.field("sectors", &"Full").finish()
            }
            _ => dbg.field("sectors", &self.inner.len()).finish(),
        }
    }
}

impl ArcSet {
    /// Create a new arc set from a list of arcs.
    ///
    /// The resulting arc set represents the union of the input arcs.
    pub fn new(arcs: Vec<DhtArc>) -> K2Result<Self> {
        let factor = u32::MAX / SECTOR_SIZE + 1;

        // The factor that was used to define the size should have been a power of 2
        if factor == 0 || factor & (factor - 1) != 0 {
            return Err(K2Error::other("Invalid size"));
        }

        let mut inner = HashSet::new();
        for arc in arcs {
            // If we have reached full arc then there's no need to keep going
            if inner.len() == factor as usize {
                break;
            }

            match arc {
                DhtArc::Empty => {
                    continue;
                }
                DhtArc::Arc(start, end) => {
                    let num_sectors_covered = if start > end {
                        let length = u32::MAX - start + end + 1;
                        length / SECTOR_SIZE + 1
                    } else {
                        (end - start) / SECTOR_SIZE + 1
                    };

                    let mut start = start;
                    for _ in 0..num_sectors_covered {
                        inner.insert(start / SECTOR_SIZE);
                        start = start.overflowing_add(SECTOR_SIZE).0;
                    }

                    if start != end.overflowing_add(1).0
                        && !(end == u32::MAX && start == 0)
                    {
                        return Err(K2Error::other(format!(
                            "Invalid arc, expected end at {start} but arc specifies {end}"
                        )));
                    }
                }
            }
        }

        Ok(ArcSet { inner })
    }

    /// Get the intersection of two arc sets as a new [ArcSet].
    ///
    /// # Example
    ///
    /// ```rust
    /// use kitsune2_api::DhtArc;
    /// use kitsune2_dht::{ArcSet, SECTOR_SIZE};
    ///
    /// # fn main() -> kitsune2_api::K2Result<()> {
    /// let arc_1 = DhtArc::Arc(0, 2 * SECTOR_SIZE - 1);
    /// let arc_set_1 = ArcSet::new(vec![arc_1])?;
    ///
    /// let arc_2 = DhtArc::Arc(SECTOR_SIZE, 4 * SECTOR_SIZE - 1);
    /// let arc_set_2 = ArcSet::new(vec![arc_2])?;
    ///
    /// assert_eq!(1, arc_set_1.intersection(&arc_set_2).covered_sector_count());
    /// # Ok(())
    /// # }
    /// ```
    pub fn intersection(&self, other: &Self) -> Self {
        ArcSet {
            inner: self.inner.intersection(&other.inner).copied().collect(),
        }
    }

    /// The number of sectors covered by this arc set.
    ///
    /// # Example
    ///
    /// ```rust
    /// use kitsune2_api::DhtArc;
    /// use kitsune2_dht::{ArcSet, SECTOR_SIZE};
    ///
    /// # fn main() -> kitsune2_api::K2Result<()> {
    /// let arc_1 = DhtArc::Arc(0, 2 * SECTOR_SIZE - 1);
    /// let arc_2 = DhtArc::Arc(2 * SECTOR_SIZE, 4 * SECTOR_SIZE - 1);
    /// let arc_set = ArcSet::new(vec![arc_1, arc_2])?;
    ///
    /// assert_eq!(4, arc_set.covered_sector_count());
    /// # Ok(())
    /// # }
    /// ```
    pub fn covered_sector_count(&self) -> usize {
        self.inner.len()
    }

    /// Encode this arc set into a compressed format for transmission.
    ///
    /// The encoding is a simple bitset where each bit represents a sector.
    pub fn encode(&self) -> Vec<u32> {
        let mut out = vec![0; 512 / 32];

        for sector in &self.inner {
            let index = sector / 32;
            let bit = sector % 32;
            out[index as usize] |= 1 << bit;
        }

        out
    }

    /// Decode an arc set from a compressed format.
    ///
    /// See the [ArcSet::encode] method for details on the encoding format.
    pub fn decode(input: &[u32]) -> K2Result<Self> {
        if input.len() != 512 / 32 {
            return Err(K2Error::other("Invalid size for encoded arc set"));
        }

        let mut inner = HashSet::new();
        for (index, value) in input.iter().enumerate() {
            for bit in 0..32 {
                if value & (1 << bit) != 0 {
                    inner.insert(index as u32 * 32 + bit);
                }
            }
        }

        Ok(ArcSet { inner })
    }

    /// Check whether a given sector index is included in this arc set.
    pub fn includes_sector_index(&self, value: u32) -> bool {
        self.inner.contains(&value)
    }

    /// Remove the given sector indices from this arc set.
    ///
    /// Note that this is a mutable operation, which is normally not needed for arc sets. This
    /// function therefore consumes the provided arc set to make it harder to accidentally modify
    /// an arc set that wasn't intended to be updated.
    pub fn without_sector_indices(
        mut self,
        remove: impl IntoIterator<Item = u32>,
    ) -> Self {
        for sector in remove {
            self.inner.remove(&sector);
        }

        self
    }

    /// Convert an arc set to a list of arcs.
    ///
    /// Note that an [ArcSet] is created from a `Vec<DhtArc>`, so if you have just created an
    /// [ArcSet] then this should return an equivalent list of arcs to what you provided, though
    /// not necessarily the same list. E.g. `ArcSet::new(vec![DhtArc::FULL, DhtArc::FULL])` will
    /// return `vec![DhtArc::FULL]`.
    ///
    /// This method is intended to be used after taking an intersection with [ArcSet::intersection].
    /// In that case, the list of arcs is not known and converting to a list of arcs is useful.
    pub fn as_arcs(&self) -> Vec<DhtArc> {
        if self.inner.is_empty() {
            return vec![];
        } else if self.inner.len() == 512 {
            return vec![DhtArc::FULL];
        }

        let mut arcs = vec![];

        let mut sectors = self.inner.iter().copied().collect::<Vec<_>>();
        sectors.sort();

        let mut start = 0;
        while start < sectors.len() {
            // Determine consecutive sectors.
            let mut end = start;
            while end + 1 < sectors.len()
                && sectors[end] + 1 == sectors[end + 1]
            {
                end += 1;
            }

            let start_sector = sectors[start];
            let end_sector = sectors[end];

            let top = (end_sector + 1).saturating_mul(SECTOR_SIZE);
            arcs.push(DhtArc::Arc(
                start_sector * SECTOR_SIZE,
                if top == u32::MAX { u32::MAX } else { top - 1 },
            ));

            start = end + 1;
        }

        arcs
    }
}

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

    #[test]
    fn new_with_no_arcs() {
        let set = ArcSet::new(vec![]).unwrap();

        assert!(set.inner.is_empty());
    }

    #[test]
    fn new_with_full_arc() {
        let set = ArcSet::new(vec![DhtArc::FULL]).unwrap();

        // Sufficient to check that all the right values are included
        assert_eq!(512, set.inner.len());
        assert_eq!(511, *set.inner.iter().max().unwrap());
    }

    #[test]
    fn new_with_two_arcs() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(0, 255 * SECTOR_SIZE - 1),
            DhtArc::Arc(255 * SECTOR_SIZE, u32::MAX),
        ])
        .unwrap();

        // Should become a full arc
        assert_eq!(512, set.inner.len());
        assert_eq!(511, *set.inner.iter().max().unwrap());
    }

    #[test]
    fn overlapping_arcs() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(0, 3 * SECTOR_SIZE - 1),
            DhtArc::Arc(2 * SECTOR_SIZE, 4 * SECTOR_SIZE - 1),
        ])
        .unwrap();

        assert_eq!(4, set.inner.len());
        assert_eq!(3, *set.inner.iter().max().unwrap());
    }

    #[test]
    fn wrapping_arc() {
        let set = ArcSet::new(vec![DhtArc::Arc(
            510 * SECTOR_SIZE,
            3 * SECTOR_SIZE - 1,
        )])
        .unwrap();

        assert_eq!(5, set.inner.len(), "Set is {:?}", set.inner);
        assert_eq!(
            set.inner.len(),
            set.inner
                .intersection(&vec![510, 511, 0, 1, 2].into_iter().collect())
                .count()
        );
    }

    #[test]
    fn overlapping_wrapping_arcs() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(510 * SECTOR_SIZE, 3 * SECTOR_SIZE - 1),
            DhtArc::Arc(2 * SECTOR_SIZE, 4 * SECTOR_SIZE - 1),
        ])
        .unwrap();

        assert_eq!(6, set.inner.len(), "Set is {:?}", set.inner);
        assert_eq!(
            set.inner.len(),
            set.inner
                .intersection(&vec![510, 511, 0, 1, 2, 3].into_iter().collect())
                .count()
        );
    }

    #[test]
    fn arc_not_on_boundaries() {
        let set = ArcSet::new(vec![DhtArc::Arc(0, 50)]);

        assert!(set.is_err());
        assert_eq!(
            "Invalid arc, expected end at 8388608 but arc specifies 50 (src: None)",
            set.unwrap_err().to_string()
        );
    }

    #[test]
    fn valid_and_invalid_arcs() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(0, SECTOR_SIZE - 1),
            DhtArc::Arc(u32::MAX, u32::MAX),
        ]);

        assert!(set.is_err());
        assert_eq!(
            "Invalid arc, expected end at 8388607 but arc specifies 4294967295 (src: None)",
            set.unwrap_err().to_string()
        );
    }

    #[test]
    fn intersect_non_overlapping_sets() {
        let set1 = ArcSet::new(vec![DhtArc::Arc(0, SECTOR_SIZE - 1)]).unwrap();
        let set2 = ArcSet::new(vec![DhtArc::Arc(
            2 * SECTOR_SIZE,
            3 * SECTOR_SIZE - 1,
        )])
        .unwrap();

        let intersection = set1.intersection(&set2);

        assert!(intersection.inner.is_empty());
    }

    #[test]
    fn intersect_overlapping_by_one() {
        let set1 =
            ArcSet::new(vec![DhtArc::Arc(0, 2 * SECTOR_SIZE - 1)]).unwrap();
        let set2 =
            ArcSet::new(vec![DhtArc::Arc(SECTOR_SIZE, 3 * SECTOR_SIZE - 1)])
                .unwrap();

        let intersection = set1.intersection(&set2);

        assert_eq!(1, intersection.inner.len());
        assert!(intersection.inner.contains(&1));
    }

    #[test]
    fn intersect_overlapping_by_multiple() {
        let set1 =
            ArcSet::new(vec![DhtArc::Arc(0, 10 * SECTOR_SIZE - 1)]).unwrap();
        let set2 =
            ArcSet::new(vec![DhtArc::Arc(SECTOR_SIZE, 3 * SECTOR_SIZE - 1)])
                .unwrap();

        let intersection = set1.intersection(&set2);

        assert_eq!(2, intersection.inner.len());
        assert!(intersection.inner.contains(&1));
        assert!(intersection.inner.contains(&2));
    }

    #[test]
    fn preserves_full_arc() {
        let full_set = ArcSet::new(vec![DhtArc::FULL]).unwrap();
        assert_eq!(
            full_set,
            full_set.intersection(&ArcSet::new(vec![DhtArc::FULL]).unwrap())
        );
    }

    #[test]
    fn preserves_empty() {
        let empty_set = ArcSet::new(vec![DhtArc::Empty]).unwrap();
        assert_eq!(
            empty_set,
            empty_set.intersection(&ArcSet::new(vec![DhtArc::FULL]).unwrap())
        );
    }

    #[test]
    fn encode_decode_empty() {
        let set = ArcSet::new(vec![DhtArc::Empty]).unwrap();
        let encoded = set.encode();
        let decoded = ArcSet::decode(&encoded).unwrap();

        assert_eq!(set, decoded);
    }

    #[test]
    fn encode_decode_full() {
        let set = ArcSet::new(vec![DhtArc::FULL]).unwrap();
        let encoded = set.encode();
        let decoded = ArcSet::decode(&encoded).unwrap();

        assert_eq!(set, decoded);
    }

    #[test]
    fn encode_decode_sparse() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(0, SECTOR_SIZE - 1),
            DhtArc::Arc(20 * SECTOR_SIZE, 21 * SECTOR_SIZE - 1),
        ])
        .unwrap();

        let encoded = set.encode();
        let decoded = ArcSet::decode(&encoded).unwrap();

        assert_eq!(set, decoded);
    }

    #[test]
    fn as_arcs_empty() {
        let set = ArcSet::new(vec![DhtArc::Empty]).unwrap();
        assert_eq!(set.as_arcs(), vec![]);
    }

    #[test]
    fn as_arcs_full() {
        let set = ArcSet::new(vec![DhtArc::FULL]).unwrap();
        assert_eq!(set.as_arcs(), vec![DhtArc::FULL]);
    }

    #[test]
    fn as_arcs_full_from_overlap() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(0, 2 * SECTOR_SIZE - 1),
            DhtArc::Arc(SECTOR_SIZE, u32::MAX),
        ])
        .unwrap();
        assert_eq!(set.as_arcs(), vec![DhtArc::FULL]);
    }

    #[test]
    fn as_arcs_multiple_disjoint() {
        let arc_1 = DhtArc::Arc(0, 2 * SECTOR_SIZE - 1);
        let arc_2 = DhtArc::Arc(10 * SECTOR_SIZE, 40 * SECTOR_SIZE - 1);
        let set = ArcSet::new(vec![arc_1, arc_2]).unwrap();

        assert_eq!(set.as_arcs(), vec![arc_1, arc_2]);
    }

    #[test]
    fn as_arcs_full_on_wrap() {
        let set = ArcSet::new(vec![
            DhtArc::Arc(SECTOR_SIZE, 2 * SECTOR_SIZE - 1),
            DhtArc::Arc(2 * SECTOR_SIZE, SECTOR_SIZE - 1),
        ])
        .unwrap();

        assert_eq!(set.as_arcs(), vec![DhtArc::FULL]);
    }

    #[test]
    fn as_arcs_split_on_wrap() {
        let set = ArcSet::new(vec![DhtArc::Arc(
            510 * SECTOR_SIZE,
            2 * SECTOR_SIZE - 1,
        )])
        .unwrap();

        assert_eq!(
            set.as_arcs(),
            vec![
                DhtArc::Arc(0, 2 * SECTOR_SIZE - 1),
                DhtArc::Arc(510 * SECTOR_SIZE, u32::MAX)
            ]
        );
    }

    #[test]
    fn debug_arc_set() {
        assert_eq!(
            "ArcSet { sectors: \"Empty\" }",
            format!("{:?}", ArcSet::new(vec![DhtArc::Empty]).unwrap())
        );

        let set =
            ArcSet::new(vec![DhtArc::Arc(0, 2 * SECTOR_SIZE - 1)]).unwrap();
        assert_eq!("ArcSet { sectors: 2 }", format!("{set:?}"));

        let set = ArcSet::new(vec![
            DhtArc::Arc(0, 2 * SECTOR_SIZE - 1),
            DhtArc::Arc(SECTOR_SIZE, 3 * SECTOR_SIZE - 1),
        ])
        .unwrap();
        assert_eq!("ArcSet { sectors: 3 }", format!("{set:?}"));

        assert_eq!(
            "ArcSet { sectors: \"Full\" }",
            format!("{:?}", ArcSet::new(vec![DhtArc::FULL]).unwrap())
        );
    }
}