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#[derive(Clone, PartialEq, Eq, Hash)]
51pub struct SortedIntView<'a> {
52 values: Cow<'a, [u32]>,
53}
54
55impl SortedIntView<'static> {
56 pub const EMPTY: SortedIntView<'static> = SortedIntView {
58 values: Cow::Borrowed(&[]),
59 };
60
61 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 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 #[inline]
88 pub(crate) fn new(values: &'a [u32]) -> Self {
89 Self {
90 values: Cow::Borrowed(values),
91 }
92 }
93
94 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 #[inline]
132 pub fn as_slice(&self) -> &[u32] {
133 &self.values
134 }
135
136 #[inline]
141 pub fn first(&self) -> Option<u32> {
142 self.values.first().copied()
143 }
144
145 #[inline]
150 pub fn last(&self) -> Option<u32> {
151 self.values.last().copied()
152 }
153
154 #[inline]
158 pub fn index_of(&self, value: u32) -> Option<usize> {
159 self.values.binary_search(&value).ok()
160 }
161
162 #[inline]
167 pub fn last_index_of(&self, value: u32) -> Option<usize> {
168 self.index_of(value)
169 }
170
171 #[inline]
176 pub fn contains(&self, value: u32) -> bool {
177 self.values.binary_search(&value).is_ok()
178 }
179
180 #[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 #[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 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
314fn 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#[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#[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#[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 out.shrink_to_fit();
373 out
374}
375
376#[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 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 #[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 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 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 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}