Skip to main content

graphity_core/
sorted_int_view.rs

1use std::borrow::Cow;
2use std::fmt;
3use std::ops::Deref;
4
5use crate::GraphError;
6use crate::array_limits::MAX_ARRAY_LENGTH;
7use crate::error::{index_out_of_bounds, invalid_argument};
8
9/// A list of `u32` values in ascending order and without duplicates, as a view of a range of an
10/// array.
11///
12/// Adjacency lookups such as [`Graph::out_nodes`] return it, as do other functions of this library
13/// that return nodes or edge indices in ascending order, such as [`graphs::reachable_from`]. It
14/// dereferences to `[u32]`, so it reads, iterates and compares like any slice, and it cannot be
15/// modified - Java's `SortedIntView` is an unmodifiable fastutil `IntList`. Since its values are
16/// sorted and distinct, [`index_of`](Self::index_of) and [`contains`](Self::contains) search in
17/// O(log len), and [`first`](Self::first) and [`last`](Self::last) are the smallest and the largest
18/// value.
19///
20/// ```
21/// use graphity_core::{GraphBuilder, SortedIntView};
22///
23/// let mut b = GraphBuilder::new();
24/// b.add_nodes(4);
25/// b.add_out_edges(0, &[3, 1, 2]);
26/// let graph = b.build();
27///
28/// let out = graph.out_nodes(0);
29/// assert_eq!(out, [1, 2, 3]);
30/// assert!(out.contains(2));
31/// assert_eq!(out.index_of(3), Some(2));
32/// assert_eq!(out.first(), Some(1));
33/// let view = SortedIntView::view_of(&[0, 4, 7, 9], 1, 3).unwrap();
34/// assert_eq!(out.union(&view), [1, 2, 3, 4, 7]);
35/// ```
36///
37/// A view borrows the array of the object it comes from instead of copying it, for the lifetime
38/// `'a`; a function that returns a copy, such as [`union`](Self::union) or
39/// [`BiAdjacentGraph::neighbors`], says so, and its result owns its array, as a
40/// `SortedIntView<'static>`. Instances are immutable and safe to share between threads (`Send` and
41/// `Sync`): a borrowed array cannot change while the view exists. Two views are equal if they hold
42/// the same values, as Java's `List` contract defines it.
43///
44/// [`Graph::out_nodes`]: crate::Graph::out_nodes
45/// [`BiAdjacentGraph::neighbors`]: crate::BiAdjacentGraph::neighbors
46/// [`graphs::reachable_from`]: crate::graphs::reachable_from
47///
48/// **Memory:** constant for a borrowed view, whose values stay in the shared array; 4 bytes per
49/// value for one that owns its array.
50#[derive(Clone, PartialEq, Eq, Hash)]
51pub struct SortedIntView<'a> {
52    values: Cow<'a, [u32]>,
53}
54
55impl SortedIntView<'static> {
56    /// An empty view.
57    pub const EMPTY: SortedIntView<'static> = SortedIntView {
58        values: Cow::Borrowed(&[]),
59    };
60
61    /// Returns a view that owns `values`, which must be strictly ascending: the owned counterpart of
62    /// [`view_of`](SortedIntView::view_of), for an analysis that collects its result into a new array, as
63    /// `IteratedDominanceFrontier::frontier_of` in `graphity-controlflow` does. Java needs none: there,
64    /// the garbage collector owns every array.
65    ///
66    /// **Time:** O(len).
67    ///
68    /// # Errors
69    /// An [`InvalidArgument`](crate::ErrorKind::InvalidArgument) error if the values are not strictly
70    /// ascending.
71    pub fn from_vec(values: Vec<u32>) -> Result<SortedIntView<'static>, GraphError> {
72        check_ascending(&values, 0, "values")?;
73        Ok(Self::owned(values))
74    }
75
76    /// A view over values the caller guarantees to be strictly ascending.
77    pub(crate) fn owned(values: Vec<u32>) -> SortedIntView<'static> {
78        debug_assert!(values.windows(2).all(|w| w[0] < w[1]));
79        SortedIntView {
80            values: Cow::Owned(values),
81        }
82    }
83}
84
85impl<'a> SortedIntView<'a> {
86    /// A view over values the caller guarantees to be strictly ascending.
87    #[inline]
88    pub(crate) fn new(values: &'a [u32]) -> Self {
89        Self {
90            values: Cow::Borrowed(values),
91        }
92    }
93
94    /// Returns a view of `array[from_index..to_index]`, which must be strictly ascending.
95    ///
96    /// The range is checked, not copied: the view borrows `array`, which cannot change while the view
97    /// exists.
98    ///
99    /// **Time:** O(to_index - from_index).
100    ///
101    /// # Errors
102    /// An [`IndexOutOfBounds`](crate::ErrorKind::IndexOutOfBounds) error if `to_index` is greater than
103    /// `array.len()` or `from_index > to_index`; an [`InvalidArgument`](crate::ErrorKind::InvalidArgument)
104    /// error if the range is not strictly ascending.
105    pub fn view_of(
106        array: &'a [u32],
107        from_index: usize,
108        to_index: usize,
109    ) -> Result<Self, GraphError> {
110        if from_index > to_index || to_index > array.len() {
111            return Err(GraphError::index_out_of_bounds(format!(
112                "Range [{from_index}, {to_index}) out of bounds for length {}",
113                array.len()
114            )));
115        }
116        if from_index == to_index {
117            return Ok(Self::new(&[]));
118        }
119        let range = &array[from_index..to_index];
120        check_ascending(
121            range,
122            from_index,
123            format_args!("array[{from_index}..{to_index})"),
124        )?;
125        Ok(Self::new(range))
126    }
127
128    /// Returns the values as a slice; the same as dereferencing.
129    ///
130    /// **Time:** O(1).
131    #[inline]
132    pub fn as_slice(&self) -> &[u32] {
133        &self.values
134    }
135
136    /// Returns the first value, which is the smallest, or `None` if the view is empty - where Java throws
137    /// `NoSuchElementException`.
138    ///
139    /// **Time:** O(1).
140    #[inline]
141    pub fn first(&self) -> Option<u32> {
142        self.values.first().copied()
143    }
144
145    /// Returns the last value, which is the largest, or `None` if the view is empty - where Java throws
146    /// `NoSuchElementException`.
147    ///
148    /// **Time:** O(1).
149    #[inline]
150    pub fn last(&self) -> Option<u32> {
151        self.values.last().copied()
152    }
153
154    /// Returns the position of `value`, or `None` if the view does not contain it - Java's `-1`.
155    ///
156    /// **Time:** O(log len).
157    #[inline]
158    pub fn index_of(&self, value: u32) -> Option<usize> {
159        self.values.binary_search(&value).ok()
160    }
161
162    /// Returns the position of `value`, or `None` if the view does not contain it. Equivalent to
163    /// [`index_of`](Self::index_of), since no value occurs twice.
164    ///
165    /// **Time:** O(log len).
166    #[inline]
167    pub fn last_index_of(&self, value: u32) -> Option<usize> {
168        self.index_of(value)
169    }
170
171    /// Returns whether the view contains `value`, by binary search - unlike the linear `contains` of a
172    /// slice.
173    ///
174    /// **Time:** O(log len).
175    #[inline]
176    pub fn contains(&self, value: u32) -> bool {
177        self.values.binary_search(&value).is_ok()
178    }
179
180    /// Returns the values at the positions `from_index..to_index` as a view of the same array, not a
181    /// copy.
182    ///
183    /// **Time:** O(1).
184    ///
185    /// # Panics
186    /// With an `index out of bounds` message if `to_index` is greater than `len()` or
187    /// `from_index > to_index`.
188    #[track_caller]
189    pub fn sub_list(&self, from_index: usize, to_index: usize) -> SortedIntView<'_> {
190        if from_index > to_index || to_index > self.values.len() {
191            index_out_of_bounds!(
192                "Range [{from_index}, {to_index}) out of bounds for length {}",
193                self.values.len()
194            );
195        }
196        SortedIntView::new(&self.values[from_index..to_index])
197    }
198
199    /// Returns the values of this view and `other` together, in ascending order and without duplicates.
200    ///
201    /// The result owns a copy, merged on every call, unless one of the two views is empty: then it
202    /// borrows the other one, as Java returns it. [`into_owned`](Self::into_owned) detaches a result
203    /// from both views.
204    ///
205    /// **Time:** O(len() + other.len()).
206    /// **Memory:** up to 4 x (len() + other.len()) bytes for the result; while it runs, up to as much
207    /// again if the two views share values.
208    ///
209    /// # Panics
210    /// With an `invalid argument` message if the union has more than `2^31 - 9` values, the most an
211    /// array can hold.
212    #[track_caller]
213    pub fn union<'s>(&'s self, other: &'s SortedIntView<'_>) -> SortedIntView<'s> {
214        if other.is_empty() {
215            return SortedIntView::new(&self.values);
216        }
217        if self.is_empty() {
218            return SortedIntView::new(&other.values);
219        }
220        SortedIntView {
221            values: Cow::Owned(union_of(&self.values, &other.values)),
222        }
223    }
224
225    /// Returns the view with its own copy of the values, independent of the array it borrowed; a view
226    /// that already owns its array keeps it.
227    ///
228    /// **Time:** O(len()) for a borrowed view, O(1) for an owned one.
229    pub fn into_owned(self) -> SortedIntView<'static> {
230        SortedIntView {
231            values: Cow::Owned(self.values.into_owned()),
232        }
233    }
234}
235
236impl Default for SortedIntView<'_> {
237    fn default() -> Self {
238        Self::new(&[])
239    }
240}
241
242impl Deref for SortedIntView<'_> {
243    type Target = [u32];
244
245    #[inline]
246    fn deref(&self) -> &[u32] {
247        &self.values
248    }
249}
250
251impl AsRef<[u32]> for SortedIntView<'_> {
252    fn as_ref(&self) -> &[u32] {
253        &self.values
254    }
255}
256
257impl<'s> IntoIterator for &'s SortedIntView<'_> {
258    type Item = &'s u32;
259    type IntoIter = std::slice::Iter<'s, u32>;
260
261    fn into_iter(self) -> Self::IntoIter {
262        self.values.iter()
263    }
264}
265
266impl fmt::Debug for SortedIntView<'_> {
267    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
268        f.debug_list().entries(self.values.iter()).finish()
269    }
270}
271
272impl PartialEq<[u32]> for SortedIntView<'_> {
273    fn eq(&self, other: &[u32]) -> bool {
274        *self.values == *other
275    }
276}
277
278impl PartialEq<&[u32]> for SortedIntView<'_> {
279    fn eq(&self, other: &&[u32]) -> bool {
280        *self.values == **other
281    }
282}
283
284impl PartialEq<Vec<u32>> for SortedIntView<'_> {
285    fn eq(&self, other: &Vec<u32>) -> bool {
286        *self.values == **other
287    }
288}
289
290impl<const N: usize> PartialEq<[u32; N]> for SortedIntView<'_> {
291    fn eq(&self, other: &[u32; N]) -> bool {
292        *self.values == *other
293    }
294}
295
296impl<const N: usize> PartialEq<&[u32; N]> for SortedIntView<'_> {
297    fn eq(&self, other: &&[u32; N]) -> bool {
298        *self.values == **other
299    }
300}
301
302impl PartialEq<SortedIntView<'_>> for [u32] {
303    fn eq(&self, other: &SortedIntView<'_>) -> bool {
304        *self == *other.values
305    }
306}
307
308impl PartialEq<SortedIntView<'_>> for Vec<u32> {
309    fn eq(&self, other: &SortedIntView<'_>) -> bool {
310        **self == *other.values
311    }
312}
313
314/// Rejects values that are not strictly ascending, with Java's message: `name` is what the values
315/// are, and `offset` the index of the first in it.
316fn check_ascending(
317    values: &[u32],
318    offset: usize,
319    name: impl std::fmt::Display,
320) -> Result<(), GraphError> {
321    if let Some(i) = values.windows(2).position(|w| w[1] <= w[0]) {
322        return Err(GraphError::invalid_argument(format!(
323            "{name} must be strictly ascending, but {} follows {} at index {}",
324            values[i + 1],
325            values[i],
326            offset + i + 1
327        )));
328    }
329    Ok(())
330}
331
332/// The index of `value` in `array[from..to]` as an absolute position, or `None`.
333#[inline]
334pub(crate) fn index_of_in_range(array: &[u32], from: usize, to: usize, value: u32) -> Option<u32> {
335    array[from..to]
336        .binary_search(&value)
337        .ok()
338        .map(|i| (from + i) as u32)
339}
340
341/// Whether `array[from..to]` contains `value`.
342#[inline]
343pub(crate) fn contains_in_range(array: &[u32], from: usize, to: usize, value: u32) -> bool {
344    array[from..to].binary_search(&value).is_ok()
345}
346
347/// The sorted union of two sorted, duplicate-free slices; each distinct value once.
348///
349/// # Panics
350/// With an `invalid argument` message if the union has more values than the largest array holds.
351#[track_caller]
352pub(crate) fn union_of(a: &[u32], b: &[u32]) -> Vec<u32> {
353    let mut out = Vec::with_capacity(union_capacity(a, b, MAX_ARRAY_LENGTH as usize));
354    let (mut i, mut j) = (0, 0);
355    while i < a.len() && j < b.len() {
356        let (x, y) = (a[i], b[j]);
357        if x < y {
358            out.push(x);
359            i += 1;
360        } else if y < x {
361            out.push(y);
362            j += 1;
363        } else {
364            out.push(x);
365            i += 1;
366            j += 1;
367        }
368    }
369    out.extend_from_slice(&a[i..]);
370    out.extend_from_slice(&b[j..]);
371    // Shared values leave room at the end; Java copies the result to its size.
372    out.shrink_to_fit();
373    out
374}
375
376/// The length to allocate for the union of two sorted, duplicate-free slices: the sum of their
377/// lengths, or, if that exceeds `max_length`, the size of the union itself, counted by a merge that
378/// writes nothing. `max_length` is the largest array length; tests pass a small one.
379///
380/// # Panics
381/// With an `invalid argument` message if the union has more than `max_length` values.
382#[track_caller]
383fn union_capacity(a: &[u32], b: &[u32], max_length: usize) -> usize {
384    let size_sum = a.len() + b.len();
385    if size_sum <= max_length {
386        return size_sum;
387    }
388    let (mut i, mut j) = (0, 0);
389    let mut union_size = 0usize;
390    while i < a.len() && j < b.len() {
391        let (x, y) = (a[i], b[j]);
392        if x <= y {
393            i += 1;
394        }
395        if y <= x {
396            j += 1;
397        }
398        union_size += 1;
399    }
400    union_size += (a.len() - i) + (b.len() - j);
401    if union_size > max_length {
402        invalid_argument!(
403            "the union has {union_size} values, more than the largest array length of {max_length}"
404        );
405    }
406    union_size
407}
408
409#[cfg(test)]
410mod tests {
411    use graphity_testutils::panic_message;
412
413    use super::*;
414
415    #[test]
416    fn index_of_in_range_returns_absolute_index() {
417        let array = [1, 3, 5, 7, 9];
418        assert_eq!(index_of_in_range(&array, 2, 5, 5), Some(2));
419        assert_eq!(index_of_in_range(&array, 2, 5, 7), Some(3));
420        assert_eq!(index_of_in_range(&array, 2, 5, 3), None);
421    }
422
423    #[test]
424    fn contains_in_range_detects_membership() {
425        let array = [1, 3, 5, 7, 9];
426        assert!(contains_in_range(&array, 2, 5, 7));
427        assert!(!contains_in_range(&array, 2, 5, 3));
428    }
429
430    #[test]
431    fn union_in_range_with_offset_ranges_deduplicates() {
432        let a = [0, 1, 3, 5, 9];
433        let b = [0, 3, 4, 5, 9];
434        assert_eq!(union_of(&a[1..4], &b[1..4]), [1, 3, 4, 5]);
435    }
436
437    #[test]
438    fn union_is_trimmed_to_its_values() {
439        // Java copies the result to its size when the views share values.
440        let union = union_of(&[1, 2, 3, 4], &[1, 2, 3, 4]);
441        assert_eq!((union.len(), union.capacity()), (4, 4));
442        let union = union_of(&[1, 3], &[2, 4]);
443        assert_eq!((union.len(), union.capacity()), (4, 4));
444    }
445
446    // The size of a union against the largest array, on small limits: two views that reach the
447    // real one take gigabytes.
448
449    #[test]
450    fn union_capacity_is_the_sum_of_the_sizes_within_the_limit() {
451        let a = [1, 2, 3];
452        let b = [2, 3, 4];
453        assert_eq!(union_capacity(&a, &b, 6), 6);
454    }
455
456    #[test]
457    fn union_capacity_counts_the_union_when_the_sum_exceeds_the_limit() {
458        // The sizes add up to 6; the union {1, 2, 3, 4} has 4 values.
459        let a = [1, 2, 3];
460        let b = [2, 3, 4];
461        assert_eq!(union_capacity(&a, &b, 5), 4);
462        assert_eq!(union_capacity(&a, &b, 4), 4);
463        let message = panic_message(|| {
464            union_capacity(&a, &b, 3);
465        });
466        assert!(message.starts_with("invalid argument") && message.contains("4 values"));
467    }
468
469    #[test]
470    fn union_capacity_counts_the_union_of_random_ranges() {
471        // With the limit at the size of the union, the count runs whenever the ranges share a
472        // value.
473        let mut random = graphity_testutils::JavaRandom::new(42);
474        for _ in 0..500 {
475            let a = random_set(&mut random);
476            let b = random_set(&mut random);
477            let a_from = random.next_u32(a.len() as u32 + 1) as usize;
478            let a_to = a_from + random.next_u32((a.len() - a_from) as u32 + 1) as usize;
479            let b_from = random.next_u32(b.len() as u32 + 1) as usize;
480            let b_to = b_from + random.next_u32((b.len() - b_from) as u32 + 1) as usize;
481            let (a, b) = (&a[a_from..a_to], &b[b_from..b_to]);
482            let size = union_of(a, b).len();
483            assert_eq!(union_capacity(a, b, size), size);
484            if size > 0 {
485                assert!(
486                    panic_message(|| {
487                        union_capacity(a, b, size - 1);
488                    })
489                    .starts_with("invalid argument")
490                );
491            }
492        }
493    }
494
495    /// Up to 20 distinct values in 0..60, sorted ascending.
496    fn random_set(random: &mut graphity_testutils::JavaRandom) -> Vec<u32> {
497        let mut values: Vec<u32> = (0..random.next_u32(21))
498            .map(|_| random.next_u32(60))
499            .collect();
500        values.sort_unstable();
501        values.dedup();
502        values
503    }
504}