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
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.

//! The [`MemoryRange`] type, which represents a 4KB-page-aligned byte range of
//! memory, plus algorithms operating on the type.

#![warn(missing_docs)]
#![forbid(unsafe_code)]
#![no_std]

#[cfg(feature = "std")]
extern crate std;

use core::iter::Iterator;
use core::iter::Peekable;
use core::ops::Range;

const PAGE_SIZE: u64 = 4096;
const TWO_MB: u64 = 0x20_0000;
const ONE_GB: u64 = 0x4000_0000;

/// Represents a page-aligned byte range of memory.
///
/// This type has a stable `Protobuf` representation, and can be directly used
/// in saved state.
// TODO: enforce invariants during de/serialization
#[derive(Copy, Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
#[cfg_attr(
    feature = "mesh",
    derive(mesh_protobuf::Protobuf),
    mesh(package = "topology")
)]
#[cfg_attr(feature = "inspect", derive(inspect::Inspect), inspect(display))]
pub struct MemoryRange {
    #[cfg_attr(feature = "mesh", mesh(1))]
    start: u64,
    #[cfg_attr(feature = "mesh", mesh(2))]
    end: u64,
}

impl core::fmt::Display for MemoryRange {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{:#x}-{:#x}", self.start(), self.end())
    }
}

impl TryFrom<Range<u64>> for MemoryRange {
    type Error = InvalidMemoryRange;

    fn try_from(range: Range<u64>) -> Result<Self, Self::Error> {
        Self::try_new(range)
    }
}

impl TryFrom<Range<usize>> for MemoryRange {
    type Error = InvalidMemoryRange;

    fn try_from(range: Range<usize>) -> Result<Self, Self::Error> {
        Self::try_new(range.start as u64..range.end as u64)
    }
}

/// Error returned by [`MemoryRange::try_new`].
#[derive(Debug)]
#[cfg_attr(
    feature = "std",
    derive(thiserror::Error),
    error("unaligned or invalid memory range: {start:#x}-{end:#x}")
)]
#[cfg_attr(not(feature = "std"), allow(dead_code))]
pub struct InvalidMemoryRange {
    start: u64,
    end: u64,
}

impl MemoryRange {
    /// The maximum address that can be represented by a `MemoryRange`.
    pub const MAX_ADDRESS: u64 = u64::MAX & !(PAGE_SIZE - 1);

    /// Returns a new range for the given guest address range.
    ///
    /// Panics if the start or end are not 4KB aligned or if the start is after
    /// the end.
    #[track_caller]
    pub const fn new(range: Range<u64>) -> Self {
        assert!(range.start & (PAGE_SIZE - 1) == 0);
        assert!(range.end & (PAGE_SIZE - 1) == 0);
        assert!(range.start <= range.end);
        Self {
            start: range.start,
            end: range.end,
        }
    }

    /// Returns a new range for the given guest address range.
    ///
    /// Returns `None` if the start or end are not 4KB aligned or if the start
    /// is after the end.
    pub const fn try_new(range: Range<u64>) -> Result<Self, InvalidMemoryRange> {
        if range.start & (PAGE_SIZE - 1) != 0
            || range.end & (PAGE_SIZE - 1) != 0
            || range.start > range.end
        {
            return Err(InvalidMemoryRange {
                start: range.start,
                end: range.end,
            });
        }
        Ok(Self {
            start: range.start,
            end: range.end,
        })
    }

    /// Returns the smallest 4K-aligned range that contains the given address
    /// range.
    ///
    /// Panics if the start is after the end or if the end address is in the
    /// last page of the 64-bit space.
    pub fn bounding(range: Range<u64>) -> Self {
        assert!(range.start <= range.end);
        assert!(range.end < u64::MAX - PAGE_SIZE);
        let start = range.start & !(PAGE_SIZE - 1);
        let end = (range.end + (PAGE_SIZE - 1)) & !(PAGE_SIZE - 1);
        Self::new(start..end)
    }

    /// Returns a new range for the given guest 4KB page range.
    ///
    /// Panics if the start is after the end or if the start address or end
    /// address overflow.
    pub fn from_4k_gpn_range(range: Range<u64>) -> Self {
        const MAX: u64 = u64::MAX / PAGE_SIZE;
        assert!(range.start <= MAX);
        assert!(range.end <= MAX);
        Self::new(range.start * PAGE_SIZE..range.end * PAGE_SIZE)
    }

    /// The empty range, with start and end addresses of zero.
    pub const EMPTY: Self = Self::new(0..0);

    /// The start address.
    pub fn start(&self) -> u64 {
        self.start
    }

    /// The start address as a 4KB page number.
    pub fn start_4k_gpn(&self) -> u64 {
        self.start / PAGE_SIZE
    }

    /// The end address as a 4KB page number.
    pub fn end_4k_gpn(&self) -> u64 {
        self.end / PAGE_SIZE
    }

    /// The number of 4KB pages in the range.
    pub fn page_count_4k(&self) -> u64 {
        (self.end - self.start) / PAGE_SIZE
    }

    /// The number of 2MB pages in the range.
    pub fn page_count_2m(&self) -> u64 {
        (self.end - self.start).div_ceil(TWO_MB)
    }

    /// The end address.
    pub fn end(&self) -> u64 {
        self.end
    }

    /// The length of the range in bytes.
    pub fn len(&self) -> u64 {
        self.end() - self.start()
    }

    /// Check if the range is empty.
    pub fn is_empty(&self) -> bool {
        self.start == self.end
    }

    /// Gets the biggest page size possible for the range.
    pub fn alignment(&self, base: u64) -> u64 {
        let order = ((base + self.start()) | (base + self.end())).trailing_zeros();
        1 << order
    }

    /// Returns the largest range contained in this range whose start and end
    /// are aligned to `alignment` bytes. This may be the empty range.
    ///
    /// Panics if `alignment` is not a power of two.
    pub fn aligned_subrange(&self, alignment: u64) -> Self {
        assert!(alignment.is_power_of_two());
        let start = (self.start + alignment - 1) & !(alignment - 1);
        let end = self.end & !(alignment - 1);
        if start <= end {
            Self::new(start..end)
        } else {
            Self::EMPTY
        }
    }

    /// Returns whether `self` and `other` overlap.
    pub fn overlaps(&self, other: &Self) -> bool {
        self.end > other.start && self.start < other.end
    }

    /// Returns whether `self` contains `other`.
    pub fn contains(&self, other: &Self) -> bool {
        self.start <= other.start && self.end >= other.end
    }

    /// Returns whether `self` contains the byte at `addr`.
    pub fn contains_addr(&self, addr: u64) -> bool {
        (self.start..self.end).contains(&addr)
    }

    /// Returns the byte offset of `addr` within the range, if it is contained.
    pub fn offset_of(&self, addr: u64) -> Option<u64> {
        if self.contains_addr(addr) {
            Some(addr - self.start)
        } else {
            None
        }
    }

    /// Returns the intersection of `self` and `other`.
    pub fn intersection(&self, other: &Self) -> Self {
        let start = self.start.max(other.start);
        let end = self.end.min(other.end);
        if start <= end {
            Self::new(start..end)
        } else {
            Self::EMPTY
        }
    }

    /// Split the range at the given byte offset within the range.
    ///
    /// Panics if `offset` is not within the range or is not page-aligned.
    #[track_caller]
    pub fn split_at_offset(&self, offset: u64) -> (Self, Self) {
        assert!(offset <= self.len());
        assert!(offset % PAGE_SIZE == 0);
        (
            Self {
                start: self.start,
                end: self.start + offset,
            },
            Self {
                start: self.start + offset,
                end: self.end,
            },
        )
    }
}

impl From<MemoryRange> for Range<u64> {
    fn from(range: MemoryRange) -> Self {
        Range {
            start: range.start(),
            end: range.end(),
        }
    }
}

/// Iterator over aligned subranges of a memory range.
///
/// Each subrange will be made up of aligned pages of size 4KB, 2MB, or 1GB.
/// Subrange boundaries are chosen to output the maximum number of the largest
/// pages.
#[derive(Debug, Clone)]
pub struct AlignedSubranges {
    range: MemoryRange,
    offset: u64,
    max_len: u64,
}

impl AlignedSubranges {
    /// Returns a new iterator of subranges in `range`.
    pub fn new(range: MemoryRange) -> Self {
        Self {
            range,
            offset: 0,
            max_len: u64::MAX,
        }
    }

    /// Returns an iterator that considers subrange alignment offset by `offset`
    /// bytes.
    pub fn with_offset(self, offset: u64) -> Self {
        Self { offset, ..self }
    }

    /// Returns an iterator that outputs subranges only up to `max_len` bytes.
    pub fn with_max_range_len(self, max_len: u64) -> Self {
        Self { max_len, ..self }
    }
}

impl Iterator for AlignedSubranges {
    type Item = MemoryRange;

    fn next(&mut self) -> Option<Self::Item> {
        if self.range.is_empty() {
            return None;
        }

        let start = self.range.start() + self.offset;
        let mut end = self.range.end() + self.offset;
        if end - start > self.max_len {
            end = start + self.max_len;
        }

        let mut align = |page_size| {
            let page_mask: u64 = page_size - 1;
            if (start + page_mask) & !page_mask >= end & !page_mask {
                // No sense in aligning this, since we won't get any aligned
                // pages.
                return;
            }
            if start & page_mask != 0 {
                // Align the next range's start.
                end = end.min((start + page_mask) & !page_mask);
            } else {
                // Align this range's end.
                end &= !page_mask;
            }
        };

        align(TWO_MB);
        align(ONE_GB);
        let start = start - self.offset;
        let end = end - self.offset;
        self.range = MemoryRange::new(end..self.range.end());
        Some(MemoryRange::new(start..end))
    }
}

/// Returns an iterator over memory ranges that are in both `left` and `right`.
///
/// For example, if `left` is `[0..4MB, 8MB..12MB]` and `right` is `[2MB..6MB, 10MB..11MB]`,
/// the resulting iterator will yield `[2MB..4MB, 10MB..11MB]`.
///
/// Panics if `left` or `right` are not sorted or are overlapping.
pub fn overlapping_ranges(
    left: impl IntoIterator<Item = MemoryRange>,
    right: impl IntoIterator<Item = MemoryRange>,
) -> impl Iterator<Item = MemoryRange> {
    walk_ranges(
        left.into_iter().map(|r| (r, ())),
        right.into_iter().map(|r| (r, ())),
    )
    .filter_map(|(r, c)| match c {
        RangeWalkResult::Both((), ()) => Some(r),
        _ => None,
    })
}

/// Returns an iterator over the ranges in `left` that are not in `right`.
///
/// For example, if `left` is `[0..4MB, 8MB..12MB]` and `right` is `[2MB..6MB,
/// 10MB..11MB]`, the resulting iterator will yield `[0..2MB, 8MB..10MB,
/// 11MB..12MB]`.
///
/// Panics if `left` or `right` are not sorted or are overlapping.
pub fn subtract_ranges(
    left: impl IntoIterator<Item = MemoryRange>,
    right: impl IntoIterator<Item = MemoryRange>,
) -> impl Iterator<Item = MemoryRange> {
    walk_ranges(
        left.into_iter().map(|r| (r, ())),
        right.into_iter().map(|r| (r, ())),
    )
    .filter_map(|(r, c)| match c {
        RangeWalkResult::Left(()) => Some(r),
        RangeWalkResult::Neither | RangeWalkResult::Right(()) | RangeWalkResult::Both((), ()) => {
            None
        }
    })
}

/// Returns an iterator that computes the overlapping state of the ranges in
/// `left` and `right`.
///
/// The iterator yields a tuple of a [`MemoryRange`] and a [`RangeWalkResult`]
/// enum that indicates whether each subrange is only in `left`, only in
/// `right`, in both, or in neither.
///
/// Panics if `left` or `right` are not sorted.
///
/// # Examples
///
/// ```
/// # use memory_range::{MemoryRange, RangeResult, walk_ranges};
/// let left = [(MemoryRange::new(0x100000..0x400000), "first"), (MemoryRange::new(0x800000..0xc00000), "second")];
/// let right = [(MemoryRange::new(0x200000..0x900000), 1000), (MemoryRange::new(0x900000..0xa00000), 2000)];
/// let v: Vec<_> = walk_ranges(left, right).collect();
/// let expected = [
///     (MemoryRange::new(0..0x100000), RangeResult::Neither),
///     (MemoryRange::new(0x100000..0x200000), RangeResult::Left("first")),
///     (MemoryRange::new(0x200000..0x400000), RangeResult::Both("first", 1000)),
///     (MemoryRange::new(0x400000..0x800000), RangeResult::Right(1000)),
///     (MemoryRange::new(0x800000..0x900000), RangeResult::Both("second", 1000)),
///     (MemoryRange::new(0x900000..0xa00000), RangeResult::Both("second", 2000)),
///     (MemoryRange::new(0xa00000..0xc00000), RangeResult::Left("second")),
///     (MemoryRange::new(0xc00000..MemoryRange::MAX_ADDRESS), RangeResult::Neither),
/// ];
/// assert_eq!(v.as_slice(), expected.as_slice());
/// ```
pub fn walk_ranges<T: Clone, U: Clone>(
    left: impl IntoIterator<Item = (MemoryRange, T)>,
    right: impl IntoIterator<Item = (MemoryRange, U)>,
) -> impl Iterator<Item = (MemoryRange, RangeWalkResult<T, U>)> {
    RangeWalkIter {
        pos: 0,
        left: PeekableSorted::new(left),
        right: PeekableSorted::new(right),
    }
}

/// The result of an iteration of [`walk_ranges`].
#[derive(Copy, Clone, Debug, PartialEq, Eq)]
pub enum RangeWalkResult<T, U> {
    /// Neither iterator contains this range.
    Neither,
    /// Only the left iterator contains this range, in the element with the
    /// given value.
    Left(T),
    /// Only the right iterator contains this range, in the element with the
    /// given value.
    Right(U),
    /// Both iterators contain this range, in the elements with the given
    /// values.
    Both(T, U),
}

struct RangeWalkIter<I: Iterator, J: Iterator> {
    pos: u64,
    left: PeekableSorted<I>,
    right: PeekableSorted<J>,
}

struct PeekableSorted<I: Iterator> {
    iter: I,
    #[allow(clippy::option_option)] // `Some(None)` is used to remember that `iter` is empty.
    item: Option<Option<I::Item>>,
}

impl<I: Iterator<Item = (MemoryRange, T)>, T> PeekableSorted<I> {
    fn new(iter: impl IntoIterator<IntoIter = I>) -> Self {
        Self {
            iter: iter.into_iter(),
            item: None,
        }
    }

    fn peek_in_range_ensure_sorted(&mut self, pos: u64, msg: &str) -> Option<&(MemoryRange, T)> {
        loop {
            let r = self
                .item
                .get_or_insert_with(|| {
                    let r = self.iter.next()?;
                    assert!(r.0.start() >= pos, "{msg} not sorted");
                    Some(r)
                })
                .as_ref()?;
            if !r.0.is_empty() && r.0.end() > pos {
                return Some(self.item.as_ref().unwrap().as_ref().unwrap());
            }
            self.item = None;
        }
    }
}

impl<
        I: Iterator<Item = (MemoryRange, T)>,
        J: Iterator<Item = (MemoryRange, U)>,
        T: Clone,
        U: Clone,
    > Iterator for RangeWalkIter<I, J>
{
    type Item = (MemoryRange, RangeWalkResult<T, U>);

    fn next(&mut self) -> Option<Self::Item> {
        if self.pos == MemoryRange::MAX_ADDRESS {
            return None;
        }
        let left = self.left.peek_in_range_ensure_sorted(self.pos, "left");
        let right = self.right.peek_in_range_ensure_sorted(self.pos, "right");
        let (end, c) = match (left, right) {
            (Some(&(left, ref t)), Some(&(right, ref u))) => {
                if self.pos < left.start() {
                    if self.pos < right.start() {
                        (left.start().min(right.start()), RangeWalkResult::Neither)
                    } else {
                        (
                            left.start().min(right.end()),
                            RangeWalkResult::Right(u.clone()),
                        )
                    }
                } else if self.pos < right.start() {
                    (
                        right.start().min(left.end()),
                        RangeWalkResult::Left(t.clone()),
                    )
                } else {
                    (
                        left.end().min(right.end()),
                        RangeWalkResult::Both(t.clone(), u.clone()),
                    )
                }
            }
            (Some(&(left, ref t)), None) => {
                if self.pos < left.start() {
                    (left.start, RangeWalkResult::Neither)
                } else {
                    (left.end(), RangeWalkResult::Left(t.clone()))
                }
            }
            (None, Some(&(right, ref u))) => {
                if self.pos < right.start() {
                    (right.start, RangeWalkResult::Neither)
                } else {
                    (right.end(), RangeWalkResult::Right(u.clone()))
                }
            }
            (None, None) => (MemoryRange::MAX_ADDRESS, RangeWalkResult::Neither),
        };
        let r = MemoryRange::new(self.pos..end);
        self.pos = end;
        Some((r, c))
    }
}

/// Takes a sequence of memory ranges, sorted by their start address, and
/// returns an iterator over the flattened ranges, where adjacent ranges are
/// merged and deduplicated.
///
/// Panics if the input ranges are not sorted by their start address, or if
/// ranges overlap.
///
/// # Example
/// ```rust
/// # use memory_range::{flatten_ranges, MemoryRange};
/// let ranges = [
///     MemoryRange::new(0x1000..0x2000),
///     MemoryRange::new(0x2000..0x5000),
///     MemoryRange::new(0x5000..0x6000),
///     MemoryRange::new(0x8000..0x9000),
/// ];
/// let flattened = [
///     MemoryRange::new(0x1000..0x6000),
///     MemoryRange::new(0x8000..0x9000),
/// ];
/// assert!(flatten_ranges(ranges).eq(flattened));
/// ```
pub fn flatten_ranges(
    ranges: impl IntoIterator<Item = MemoryRange>,
) -> impl Iterator<Item = MemoryRange> {
    FlattenIter {
        iter: ranges.into_iter().map(|r| (r, ())).peekable(),
    }
    .map(|(r, _)| r)
}

/// Similar to [`flatten_ranges`], but also requires that ranges are equivalent
/// via the passed in closure. This can be useful when merging memory ranges
/// with associated tags.
///
/// Panics if the input ranges are not sorted by their start address, or if
/// ranges overlap.
///
/// # Example
/// ```rust
/// # use memory_range::{flatten_equivalent_ranges, MemoryRange};
///
/// #[derive(Clone, Copy, Debug, PartialEq, Eq)]
/// enum Color {
///    Red,
///    Blue,
/// }
///
/// let ranges = [
///     (MemoryRange::new(0x1000..0x2000), Color::Red),
///     (MemoryRange::new(0x2000..0x5000), Color::Red),
///     (MemoryRange::new(0x5000..0x6000), Color::Blue),
///     (MemoryRange::new(0x8000..0x9000), Color::Red),
/// ];
/// let flattened = [
///     (MemoryRange::new(0x1000..0x5000), Color::Red),
///     (MemoryRange::new(0x5000..0x6000), Color::Blue),
///     (MemoryRange::new(0x8000..0x9000), Color::Red),
/// ];
/// assert!(flatten_equivalent_ranges(ranges).eq(flattened));
/// ```
pub fn flatten_equivalent_ranges<T: PartialEq>(
    ranges: impl IntoIterator<Item = (MemoryRange, T)>,
) -> impl Iterator<Item = (MemoryRange, T)> {
    FlattenIter {
        iter: ranges.into_iter().peekable(),
    }
}

struct FlattenIter<I: Iterator> {
    iter: Peekable<I>,
}

impl<I: Iterator<Item = (MemoryRange, T)>, T: PartialEq> Iterator for FlattenIter<I> {
    type Item = (MemoryRange, T);

    fn next(&mut self) -> Option<Self::Item> {
        let (first, typ) = self.iter.next()?;
        let mut start = first.start();
        let mut end = first.end();
        while let Some((r, _t)) = self.iter.next_if(|(r, t)| {
            assert!(r.start() >= start, "ranges are not sorted");
            assert!(r.start() >= end, "ranges overlap");
            r.start() == end && &typ == t
        }) {
            start = r.start();
            end = end.max(r.end());
        }
        Some((MemoryRange::new(first.start()..end), typ))
    }
}

#[cfg(test)]
mod tests {
    extern crate alloc;
    use super::MemoryRange;
    use super::TWO_MB;
    use crate::flatten_equivalent_ranges;
    use crate::flatten_ranges;
    use crate::overlapping_ranges;
    use crate::subtract_ranges;
    use crate::AlignedSubranges;
    use alloc::vec;
    use alloc::vec::Vec;

    const KB: u64 = 1024;
    const MB: u64 = 1024 * KB;
    const GB: u64 = 1024 * MB;

    #[test]
    fn test_align() {
        #[derive(Clone, Debug, PartialEq, Copy)]
        struct AlignedRangeResult {
            range: MemoryRange,
            page_size: u64,
        }

        let compare_with_base = |r1: Vec<MemoryRange>, base: u64, er: Vec<AlignedRangeResult>| {
            let result: Vec<_> = r1
                .iter()
                .flat_map(|range| AlignedSubranges::new(*range).with_offset(base))
                .collect();
            assert_eq!(result.len(), er.len());
            for (pos, range) in result.iter().enumerate() {
                assert_eq!(*range, er[pos].range);
                assert_eq!(range.alignment(base), er[pos].page_size);
            }
        };

        let compare = |r1: Vec<MemoryRange>, er: Vec<AlignedRangeResult>| {
            compare_with_base(r1, 0, er);
        };

        /// Builds a memory range with short hand.
        fn b_mr(start: u64, end: u64) -> MemoryRange {
            MemoryRange::new(start..end)
        }

        /// Builds a aligned range result with short hand.
        fn b_arr(range: MemoryRange, page_size: u64) -> AlignedRangeResult {
            AlignedRangeResult { range, page_size }
        }

        // [0, 4KB]
        let ram: Vec<_> = vec![b_mr(0x0, 4 * KB)];
        let expected_res: Vec<_> = vec![b_arr(ram[0], 1 << 12)];

        compare(ram, expected_res);

        // [0, 2MB]
        let ram: Vec<_> = vec![b_mr(0x0, 2 * MB)];
        let expected_res: Vec<_> = vec![b_arr(ram[0], 1 << 21)];
        compare(ram, expected_res);

        // [0, 1MB]
        let ram: Vec<_> = vec![b_mr(0x0, GB)];
        let expected_res: Vec<_> = vec![b_arr(ram[0], 1 << 30)];
        compare(ram, expected_res);

        // [6MB, 12.004MB]
        let ram: Vec<_> = vec![b_mr(6 * MB, 12 * MB + 4 * KB)];
        let expected_res: Vec<_> = vec![
            b_arr(b_mr(6 * MB, 12 * MB), TWO_MB),
            b_arr(b_mr(12 * MB, 12 * MB + 4 * KB), 1 << 12),
        ];
        compare(ram, expected_res);

        // [5.4MB, 12.2MB]
        let ram: Vec<_> = vec![b_mr(5 * MB + 400 * KB, 12 * MB + 400 * KB)];
        let expected_res: Vec<_> = vec![
            b_arr(b_mr(5 * MB + 400 * KB, 6 * MB), 1 << 14),
            b_arr(b_mr(6 * MB, 12 * MB), TWO_MB),
            b_arr(b_mr(12 * MB, 12 * MB + 400 * KB), 1 << 14),
        ];
        compare(ram, expected_res);

        // [1.501GB, 3.503GB]
        let ram: Vec<_> = vec![b_mr(GB + 501 * MB, 3 * GB + 503 * MB)];
        let expected_res: Vec<_> = vec![
            b_arr(b_mr(GB + 501 * MB, GB + 502 * MB), 1 << 20),
            b_arr(b_mr(GB + 502 * MB, 2 * GB), 1 << 21),
            b_arr(b_mr(2 * GB, 3 * GB), 1 << 30),
            b_arr(b_mr(3 * GB, 3 * GB + 502 * MB), 1 << 21),
            b_arr(b_mr(3 * GB + 502 * MB, 3 * GB + 503 * MB), 1 << 20),
        ];
        compare(ram, expected_res);

        // [4.008MB, 6.008MB] with necessary base to align up to 2MB
        let ram: Vec<_> = vec![b_mr(4 * MB + 8 * KB, 6 * MB + 8 * KB)];
        let base = 2 * MB - 8 * KB;
        let expected_res: Vec<_> = vec![b_arr(ram[0], TWO_MB)];
        compare_with_base(ram, base, expected_res);

        // [4.008MB, 6.008MB] without any base
        let ram: Vec<_> = vec![b_mr(4 * MB + 8 * KB, 6 * MB + 8 * KB)];
        let expected_res: Vec<_> = vec![b_arr(ram[0], 1 << 13)];
        compare_with_base(ram, 0, expected_res);
    }

    #[test]
    fn test_overlapping_ranges() {
        let left = [
            MemoryRange::new(0..4 * MB),
            MemoryRange::new(8 * MB..12 * MB),
            MemoryRange::new(12 * MB..12 * MB),
            MemoryRange::new(16 * MB..20 * MB),
            MemoryRange::new(24 * MB..32 * MB),
            MemoryRange::new(40 * MB..48 * MB),
        ];
        let right = [
            MemoryRange::new(2 * MB..6 * MB),
            MemoryRange::new(10 * MB..11 * MB),
            MemoryRange::new(11 * MB..11 * MB),
            MemoryRange::new(11 * MB..13 * MB),
            MemoryRange::new(15 * MB..22 * MB),
            MemoryRange::new(26 * MB..30 * MB),
        ];

        let result: Vec<_> = overlapping_ranges(left, right).collect();
        assert_eq!(
            result.as_slice(),
            &[
                MemoryRange::new(2 * MB..4 * MB),
                MemoryRange::new(10 * MB..11 * MB),
                MemoryRange::new(11 * MB..12 * MB),
                MemoryRange::new(16 * MB..20 * MB),
                MemoryRange::new(26 * MB..30 * MB),
            ]
        );
    }

    #[test]
    fn test_subtract_ranges() {
        let left = [
            MemoryRange::new(0..4 * MB),
            MemoryRange::new(8 * MB..12 * MB),
            MemoryRange::new(12 * MB..12 * MB),
            MemoryRange::new(16 * MB..20 * MB),
            MemoryRange::new(24 * MB..32 * MB),
            MemoryRange::new(40 * MB..48 * MB),
        ];
        let right = [
            MemoryRange::new(2 * MB..6 * MB),
            MemoryRange::new(10 * MB..11 * MB),
            MemoryRange::new(11 * MB..11 * MB),
            MemoryRange::new(11 * MB..13 * MB),
            MemoryRange::new(15 * MB..22 * MB),
            MemoryRange::new(26 * MB..30 * MB),
        ];

        let result: Vec<_> = subtract_ranges(left, right).collect();
        assert_eq!(
            result.as_slice(),
            &[
                MemoryRange::new(0..2 * MB),
                MemoryRange::new(8 * MB..10 * MB),
                MemoryRange::new(24 * MB..26 * MB),
                MemoryRange::new(30 * MB..32 * MB),
                MemoryRange::new(40 * MB..48 * MB),
            ]
        );
    }

    #[test]
    #[should_panic(expected = "left not sorted")]
    fn test_panic_unsorted_overlapping_left() {
        overlapping_ranges(
            [MemoryRange::new(MB..2 * MB), MemoryRange::new(0..MB)],
            [MemoryRange::new(3 * MB..4 * MB)],
        )
        .for_each(|_| ());
    }

    #[test]
    #[should_panic(expected = "right not sorted")]
    fn test_panic_unsorted_overlapping_right() {
        overlapping_ranges(
            [
                MemoryRange::new(MB..2 * MB),
                MemoryRange::new(3 * MB..4 * MB),
            ],
            [MemoryRange::new(0..MB), MemoryRange::new(0..MB)],
        )
        .for_each(|_| ());
    }

    #[test]
    #[should_panic(expected = "left not sorted")]
    fn test_panic_unsorted_subtract_left() {
        subtract_ranges(
            [MemoryRange::new(MB..2 * MB), MemoryRange::new(0..MB)],
            [MemoryRange::new(MB..2 * MB)],
        )
        .for_each(|_| ());
    }

    #[test]
    #[should_panic(expected = "right not sorted")]
    fn test_panic_unsorted_subtract_right() {
        subtract_ranges(
            [
                MemoryRange::new(MB..2 * MB),
                MemoryRange::new(3 * MB..4 * MB),
            ],
            [MemoryRange::new(MB..2 * MB), MemoryRange::new(MB..2 * MB)],
        )
        .for_each(|_| ());
    }

    #[test]
    fn test_aligned_subrange() {
        let test_cases = &[
            (0..0, MB, 0..0),
            (0..MB, MB, 0..MB),
            (4 * KB..MB + 4 * KB, MB, MB..MB),
            (MB..5 * MB, 2 * MB, 2 * MB..4 * MB),
        ];
        for (range, alignment, expected_aligned_range) in test_cases.iter().cloned() {
            assert_eq!(
                MemoryRange::new(range).aligned_subrange(alignment),
                MemoryRange::new(expected_aligned_range)
            );
        }
    }

    #[test]
    fn test_flatten_ranges() {
        let ranges =
            [0..4, 5..7, 7..11, 13..20, 20..25, 35..36].map(MemoryRange::from_4k_gpn_range);
        let result = [0..4, 5..11, 13..25, 35..36].map(MemoryRange::from_4k_gpn_range);
        assert!(flatten_ranges(ranges).eq(result));
    }

    #[test]
    fn test_flatten_equiv_ranges() {
        #[derive(Clone, Copy, PartialEq, Eq)]
        enum Color {
            Red,
            Blue,
        }

        let ranges = [0..4, 5..7, 7..11, 11..12, 13..20, 20..25, 35..36]
            .map(MemoryRange::from_4k_gpn_range)
            .into_iter()
            .zip([
                Color::Red,
                Color::Red,
                Color::Red,
                Color::Blue,
                Color::Red,
                Color::Red,
                Color::Blue,
            ]);
        let result = [0..4, 5..11, 11..12, 13..25, 35..36]
            .map(MemoryRange::from_4k_gpn_range)
            .into_iter()
            .zip([Color::Red, Color::Red, Color::Blue, Color::Red, Color::Blue]);
        assert!(flatten_equivalent_ranges(ranges).eq(result));
    }

    #[test]
    #[should_panic(expected = "ranges are not sorted")]
    fn test_flatten_ranges_not_sorted() {
        flatten_ranges([0..4, 5..7, 3..8].map(MemoryRange::from_4k_gpn_range)).for_each(|_| ());
    }

    #[test]
    #[should_panic(expected = "ranges overlap")]
    fn test_flatten_ranges_overlap() {
        flatten_ranges([0..6, 5..7, 9..12].map(MemoryRange::from_4k_gpn_range)).for_each(|_| ());
    }
}