fdt 0.2.0-alpha2

A pure-Rust `#![no_std]` crate for parsing Flattened Devicetrees
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
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
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
/// Types and helpers for the devicetree PCI bindings.
pub mod pci;

use super::{cells::AddressCells, PHandle, Property};
use crate::{
    cell_collector::{BuildCellCollector, CellCollector, CollectCellsError},
    helpers::{FallibleNode, FallibleRoot},
    nodes::{root::Root, Node},
    parsing::{aligned::AlignedParser, BigEndianU32, NoPanic, Panic, ParserWithMode},
    FdtError,
};

/// Enum representing the two possibilities for interrupt descriptions on a
/// devicetree node. See the documentation for each type for more information.
/// [`ExtendedInterrupts`] will take precedence if both properties exist.
pub enum Interrupts<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)> {
    /// The `interrupts` property.
    Legacy(LegacyInterrupts<'a, P>),
    /// The `interrupts-extended` property.
    Extended(ExtendedInterrupts<'a, P>),
}

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for Interrupts<'a, P> {
    fn parse(node: FallibleNode<'a, P>, root: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match ExtendedInterrupts::parse(node, root)? {
            Some(extended) => Ok(Some(Self::Extended(extended))),
            None => match LegacyInterrupts::parse(node, root)? {
                Some(legacy) => Ok(Some(Self::Legacy(legacy))),
                None => Ok(None),
            },
        }
    }
}

/// [Devicetree 2.4.1.1.
/// `interrupts`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupts)
///
/// The `interrupts` property of a device node defines the interrupt or
/// interrupts that are generated by the device. The value of the `interrupts`
/// property consists of an arbitrary number of interrupt specifiers. The format
/// of an interrupt specifier is defined by the binding of the interrupt domain
/// root.
///
/// `interrupts` is overridden by the `interrupts-extended` property and
/// normally only one or the other should be used.
pub struct LegacyInterrupts<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)> {
    interrupt_parent: InterruptParent<'a, P>,
    interrupt_cells: InterruptCells,
    encoded_array: &'a [u8],
}

impl<'a, P: ParserWithMode<'a>> LegacyInterrupts<'a, P> {
    #[allow(missing_docs)]
    pub fn interrupt_parent(self) -> InterruptParent<'a, P> {
        self.interrupt_parent
    }

    #[allow(missing_docs)]
    pub fn iter<I: CellCollector>(self) -> LegacyInterruptsIter<'a, I> {
        LegacyInterruptsIter {
            interrupt_cells: self.interrupt_cells,
            encoded_array: self.encoded_array,
            _collector: core::marker::PhantomData,
        }
    }
}

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for LegacyInterrupts<'a, P> {
    fn parse(node: FallibleNode<'a, P>, root: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match node.properties()?.find("interrupts")? {
            Some(interrupts) => {
                let interrupt_parent = match InterruptParent::<(P::Parser, NoPanic)>::parse(node, root)? {
                    Some(p) => p,
                    None => return Err(FdtError::MissingRequiredProperty("interrupt-parent")),
                };

                let Some(interrupt_cells) = interrupt_parent.property::<InterruptCells>()? else {
                    return Err(FdtError::MissingRequiredProperty("interrupt-cells"));
                };

                if interrupts.value.len() % (interrupt_cells.as_byte_count()) != 0 {
                    return Err(FdtError::InvalidPropertyValue);
                }

                Ok(Some(Self {
                    interrupt_parent: InterruptParent(interrupt_parent.0.alt()),
                    interrupt_cells,
                    encoded_array: interrupts.value,
                }))
            }
            None => Ok(None),
        }
    }
}

impl<'a, P: ParserWithMode<'a>> Copy for LegacyInterrupts<'a, P> {}
impl<'a, P: ParserWithMode<'a>> Clone for LegacyInterrupts<'a, P> {
    fn clone(&self) -> Self {
        *self
    }
}

#[allow(missing_docs)]
pub struct LegacyInterruptsIter<'a, I: CellCollector> {
    interrupt_cells: InterruptCells,
    encoded_array: &'a [u8],
    _collector: core::marker::PhantomData<*mut I>,
}

impl<'a, I: CellCollector> Iterator for LegacyInterruptsIter<'a, I> {
    type Item = Result<I::Output, CollectCellsError>;
    fn next(&mut self) -> Option<Self::Item> {
        let encoded_specifier = self.encoded_array.get(..self.interrupt_cells.as_byte_count())?;
        let mut specifier_collector = <I as CellCollector>::Builder::default();

        for encoded_specifier in encoded_specifier.chunks_exact(4) {
            // TODO: replace this stuff with `array_chunks` when its stabilized
            //
            // These unwraps can't panic because `chunks_exact` guarantees that
            // we'll always get slices of 4 bytes
            if let Err(e) = specifier_collector.push(u32::from_be_bytes(encoded_specifier.try_into().unwrap())) {
                return Some(Err(e));
            }
        }

        self.encoded_array = self.encoded_array.get(self.interrupt_cells.as_byte_count()..)?;
        Some(Ok(I::map(specifier_collector.finish())))
    }
}

/// [Devicetree 2.4.1.3.
/// `interrupts-extended`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupts-extended)
///
/// The `interrupts-extended` property lists the interrupt(s) generated by a
/// device. `interrupts-extended` should be used instead of interrupts when a
/// device is connected to multiple interrupt controllers as it encodes a parent
/// `phandle` with each interrupt specifier.
///
/// Example:
///
/// This example shows how a device with two interrupt outputs connected to two
/// separate interrupt controllers would describe the connection using an
/// `interrupts-extended` property. `pic` is an interrupt controller with an
/// `#interrupt-cells` specifier of 2, while `gic` is an interrupt controller
/// with an `#interrupts-cells` specifier of 1.
///
/// `interrupts-extended = <&pic 0xA 8>, <&gic 0xda>;`
pub struct ExtendedInterrupts<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)> {
    root: Root<'a, P>,
    encoded_array: &'a [u8],
}

impl<'a, P: ParserWithMode<'a>> ExtendedInterrupts<'a, P> {
    #[allow(missing_docs)]
    pub fn iter(self) -> ExtendedInterruptsIter<'a, P> {
        ExtendedInterruptsIter { root: self.root, encoded_array: self.encoded_array }
    }
}

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for ExtendedInterrupts<'a, P> {
    fn parse(node: FallibleNode<'a, P>, root: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match node.properties()?.find("interrupts-extended")? {
            Some(interrupts) => {
                Ok(Some(Self { encoded_array: interrupts.value, root: Root { node: root.node.alt() } }))
            }

            None => Ok(None),
        }
    }
}

#[allow(missing_docs)]
pub struct ExtendedInterruptsIter<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)> {
    root: Root<'a, P>,
    encoded_array: &'a [u8],
}

impl<'a, P: ParserWithMode<'a>> Iterator for ExtendedInterruptsIter<'a, P> {
    type Item = P::Output<ExtendedInterrupt<'a, P>>;

    #[track_caller]
    fn next(&mut self) -> Option<Self::Item> {
        let phandle = self
            .encoded_array
            .get(..4)
            .map(|bytes| PHandle(BigEndianU32::from_be(u32::from_ne_bytes(bytes.try_into().unwrap()))))?;
        self.encoded_array = self.encoded_array.get(4..)?;

        let res = crate::tryblock!({
            let root: FallibleRoot<'a, P> = Root { node: self.root.node.fallible() };
            let Some(interrupt_parent) = root.resolve_phandle(phandle)? else {
                return Err(FdtError::MissingPHandleNode(phandle.0.to_ne()));
            };

            let Some(interrupt_cells) = interrupt_parent.property::<InterruptCells>()? else {
                return Err(FdtError::MissingRequiredProperty("#interrupt-cells"));
            };

            let cells_length = interrupt_cells.as_byte_count();
            let encoded_array = match self.encoded_array.get(..cells_length) {
                Some(bytes) => bytes,
                None => return Ok(None),
            };

            self.encoded_array = match self.encoded_array.get(cells_length..) {
                Some(bytes) => bytes,
                None => return Ok(None),
            };

            Ok(Some(ExtendedInterrupt {
                interrupt_parent: InterruptParent(interrupt_parent.alt()),
                interrupt_cells,
                encoded_array,
            }))
        });

        // This is a manual impl of `map` because we need the panic location to
        // be the caller if `P::to_output` panics
        #[allow(clippy::manual_map)]
        match res.transpose() {
            Some(output) => Some(P::to_output(output)),
            None => None,
        }
    }
}

/// A single entry in an `interrupts-extended` property.
pub struct ExtendedInterrupt<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)> {
    interrupt_parent: InterruptParent<'a, P>,
    interrupt_cells: InterruptCells,
    encoded_array: &'a [u8],
}

#[allow(missing_docs)]
impl<'a, P: ParserWithMode<'a>> ExtendedInterrupt<'a, P> {
    pub fn interrupt_parent(self) -> InterruptParent<'a, P> {
        self.interrupt_parent
    }

    pub fn interrupt_cells(self) -> InterruptCells {
        self.interrupt_cells
    }

    pub fn interrupt_specifier(self) -> InterruptSpecifier<'a> {
        InterruptSpecifier { interrupt_cells: self.interrupt_cells, encoded_array: self.encoded_array }
    }
}

/// An individual interrupt specifier from an [`ExtendedInterrupt`] value.
pub struct InterruptSpecifier<'a> {
    interrupt_cells: InterruptCells,
    encoded_array: &'a [u8],
}

impl<'a> InterruptSpecifier<'a> {
    /// Attempt to collect the specifier bytes into a specific type.
    pub fn collect_to<C: CellCollector>(self) -> Result<<C as CellCollector>::Output, CollectCellsError> {
        let mut collector = <C as CellCollector>::Builder::default();
        for chunk in self.encoded_array.chunks_exact(4) {
            // UNWRAP: this unwrap cannot panic because `chunk` is guaranteed to
            // be 4 bytes.
            collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
        }

        Ok(C::map(collector.finish()))
    }

    /// Iterator over the raw [`u32`] components that comprise this interrupt specifier.
    pub fn iter(self) -> InterruptSpecifierIter<'a> {
        InterruptSpecifierIter { encoded_array: self.encoded_array }
    }

    /// Iterator over `(u32, u32)` interrupt specifier pairs, if
    /// `#interrupt-cells` value is `2`.
    pub fn iter_pairs(self) -> Option<InterruptSpecifierIterPairs<'a>> {
        if self.interrupt_cells.0 != 2 {
            return None;
        }

        Some(InterruptSpecifierIterPairs { encoded_array: self.encoded_array })
    }

    /// Extract the single component that comprises the interrupt specifier, if
    /// the `#interrupt-cells` value is `1`.
    pub fn single(self) -> Option<u32> {
        if self.interrupt_cells.0 != 1 {
            return None;
        }

        self.iter().next()
    }

    /// Extract the two components that comprise the interrupt specifier, if the
    /// `#interrupt-cells` value is `2`.
    pub fn pair(self) -> Option<(u32, u32)> {
        if self.interrupt_cells.0 != 2 {
            return None;
        }

        let mut iter = self.into_iter();
        Some((iter.next()?, iter.next()?))
    }
}

impl<'a> IntoIterator for InterruptSpecifier<'a> {
    type IntoIter = InterruptSpecifierIter<'a>;
    type Item = u32;

    fn into_iter(self) -> Self::IntoIter {
        self.iter()
    }
}

/// Iterator over individual components in an interrupt specifier
pub struct InterruptSpecifierIter<'a> {
    encoded_array: &'a [u8],
}

impl<'a> Iterator for InterruptSpecifierIter<'a> {
    type Item = u32;

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

        let next = self.encoded_array.get(..4)?;
        self.encoded_array = self.encoded_array.get(4..)?;

        // This panic can never fail since the slice length is guaranteed to be
        // 4 bytes long
        Some(u32::from_be_bytes(next.try_into().unwrap()))
    }
}

/// Iterator over pairs of `u32`s representing an interrupt specifier
pub struct InterruptSpecifierIterPairs<'a> {
    encoded_array: &'a [u8],
}

impl<'a> Iterator for InterruptSpecifierIterPairs<'a> {
    type Item = (u32, u32);

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

        let (next, rest) = self.encoded_array.split_at_checked(8)?;
        self.encoded_array = rest;

        let (first, second) = next.split_at(4);

        // This panic can never fail since the slice length is guaranteed to be
        // 4 bytes long
        Some((u32::from_be_bytes(first.try_into().unwrap()), u32::from_be_bytes(second.try_into().unwrap())))
    }
}

/// [Devicetree 2.4.1.2.
/// `interrupt-parent`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-parent)
///
/// Because the hierarchy of the nodes in the interrupt tree might not match the
/// devicetree, the `interrupt-parent` property is available to make the
/// definition of an interrupt parent explicit. The value is the `phandle` to
/// the interrupt parent. If this property is missing from a device, its
/// interrupt parent is assumed to be its devicetree parent.
pub struct InterruptParent<'a, P: ParserWithMode<'a> = (AlignedParser<'a>, Panic)>(Node<'a, P>);

impl<'a, P: ParserWithMode<'a>> Copy for InterruptParent<'a, P> {}
impl<'a, P: ParserWithMode<'a>> Clone for InterruptParent<'a, P> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<'a, P: ParserWithMode<'a>> core::ops::Deref for InterruptParent<'a, P> {
    type Target = Node<'a, P>;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl<'a, P: ParserWithMode<'a>> core::ops::DerefMut for InterruptParent<'a, P> {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.0
    }
}

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for InterruptParent<'a, P> {
    fn parse(node: FallibleNode<'a, P>, root: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match node.properties()?.find("interrupt-parent")? {
            Some(phandle) => match root.resolve_phandle(PHandle(phandle.as_value()?))? {
                Some(parent) => Ok(Some(Self(parent.alt()))),
                None => Err(FdtError::MissingPHandleNode(phandle.as_value()?)),
            },
            None => Ok(node.parent().map(|n| Self(n.alt()))),
        }
    }
}

/// [Devicetree 2.4.2.1.
/// `#interrupt-cells`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-cells)
///
/// The `#interrupt-cells` property defines the number of cells required to
/// encode an interrupt specifier for an interrupt domain.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InterruptCells(pub usize);

impl InterruptCells {
    /// The number of interrupt cells times `size_of::<u32>()`.
    pub fn as_byte_count(self) -> usize {
        self.0 * core::mem::size_of::<u32>()
    }
}

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for InterruptCells {
    fn parse(node: FallibleNode<'a, P>, _: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match node.properties()?.find("#interrupt-cells")? {
            Some(ic) => Ok(Some(Self(ic.as_value()?))),
            None => Ok(None),
        }
    }
}

/// [Devicetree 2.4.3.2.
/// `interrupt-map-mask`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-map-mask)
///
/// An `interrupt-map-mask` property is specified for a nexus node in the
/// interrupt tree. This property specifies a mask that is `AND`ed with the
/// incoming unit interrupt specifier being looked up in the table specified in
/// the `interrupt-map` property.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InterruptMapMask<AddrMask: CellCollector, IntMask: CellCollector> {
    address_mask: AddrMask::Output,
    interrupt_specifier_mask: IntMask::Output,
}

impl<AddrMask: CellCollector, IntMask: CellCollector> InterruptMapMask<AddrMask, IntMask> {
    /// Mask the provided unit address and interrupt specifier with the value of
    /// the mask.
    pub fn mask(
        &self,
        address: <AddrMask as CellCollector>::Output,
        interrupt_specifier: <IntMask as CellCollector>::Output,
    ) -> (<AddrMask as CellCollector>::Output, <IntMask as CellCollector>::Output)
    where
        <AddrMask as CellCollector>::Output: Clone
            + core::ops::BitAnd<<AddrMask as CellCollector>::Output, Output = <AddrMask as CellCollector>::Output>,
        <IntMask as CellCollector>::Output:
            Clone + core::ops::BitAnd<<IntMask as CellCollector>::Output, Output = <IntMask as CellCollector>::Output>,
    {
        (self.address_mask.clone() & address, self.interrupt_specifier_mask.clone() & interrupt_specifier)
    }
}

impl<'a, AddrMask: CellCollector, IntMask: CellCollector, P: ParserWithMode<'a>> Property<'a, P>
    for InterruptMapMask<AddrMask, IntMask>
{
    fn parse(node: FallibleNode<'a, P>, _: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        let address_cells =
            node.property::<AddressCells>()?.ok_or(FdtError::MissingRequiredProperty("#address-cells"))?;
        let interrupt_cells =
            node.property::<InterruptCells>()?.ok_or(FdtError::MissingRequiredProperty("#interrupt-cells"))?;
        match node.properties()?.find("interrupt-map-mask")? {
            Some(prop) => {
                if prop.value.len() % 4 != 0 {
                    return Err(FdtError::InvalidPropertyValue);
                }

                let mut address_collector = AddrMask::Builder::default();
                let mut specifier_collector = IntMask::Builder::default();
                let mut cells = prop.value.chunks_exact(4);

                // TODO: replace this stuff with `array_chunks` when its stabilized
                //
                // These unwraps can't panic because `chunks_exact` guarantees that
                // we'll always get slices of 4 bytes
                for chunk in cells.by_ref().take(address_cells.0) {
                    address_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
                }

                for chunk in cells.take(interrupt_cells.0) {
                    specifier_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
                }

                Ok(Some(Self {
                    address_mask: AddrMask::map(address_collector.finish()),
                    interrupt_specifier_mask: IntMask::map(specifier_collector.finish()),
                }))
            }
            None => Ok(None),
        }
    }
}

/// [Devicetree 2.4.2.2.
/// `interrupt-controller`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-controller)
///
/// The presence of an `interrupt-controller` property defines a node as an
/// interrupt controller node.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct InterruptController;

impl<'a, P: ParserWithMode<'a>> Property<'a, P> for InterruptController {
    fn parse(node: FallibleNode<'a, P>, _: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        match node.properties()?.find("interrupt-controller")? {
            Some(_) => Ok(Some(Self)),
            None => Ok(None),
        }
    }
}

/// [Devicetree 2.4.3.1.
/// `interrupt-map`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-map)
///
/// The `interrupt-map` property allows for mapping interrupt specifiers between
/// one interrupt domain to a parent domain. The description of each generic
/// parameter is as follows:
///
/// `ChildUnitAddres`:
/// > The unit address of the child node being mapped. The number of 32-bit
/// > cells required to specify this is described by the `#address-cells`
/// > property of the bus node on which the child is located.
///
/// `ChildInterruptSpecifier`:
/// > The interrupt specifier of the child node being mapped. The number of
/// > 32-bit cells required to specify this component is described by the
/// > `#interrupt-cells` property of this node—the nexus node containing the
/// > `interrupt-map` property.
///
/// `ParentUnitAddress`:
/// > The unit address in the domain of the interrupt parent. The number of
/// > 32-bit cells required to specify this address is described by the
/// > `#address-cells` property of the node pointed to by the
/// > `interrupt-parent` field.
///
/// `ParentInterruptSpecifier`:
/// > The interrupt specifier in the parent domain. The number of 32-bit
/// > cells required to specify this component is described by the
/// > `#interrupt-cells` property of the node pointed to by the
/// > `interrupt-parent` field.
pub struct InterruptMap<
    'a,
    ChildUnitAddress: CellCollector,
    ChildInterruptSpecifier: CellCollector = u32,
    ParentUnitAddress: CellCollector = u64,
    ParentInterruptSpecifier: CellCollector = u32,
    P: ParserWithMode<'a> = (AlignedParser<'a>, Panic),
> {
    address_cells: AddressCells,
    interrupt_cells: InterruptCells,
    node: FallibleNode<'a, P>,
    encoded_map: &'a [u8],
    _collectors: core::marker::PhantomData<*mut (
        ChildUnitAddress,
        ChildInterruptSpecifier,
        ParentUnitAddress,
        ParentInterruptSpecifier,
    )>,
}

impl<
        'a,
        P: ParserWithMode<'a>,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
    > InterruptMap<'a, CAddr, CInt, PAddr, PInt, P>
{
    /// Create an iterator over each individual [`InterruptMapEntry`].
    pub fn iter(self) -> InterruptMapIter<'a, CAddr, CInt, PAddr, PInt, P> {
        InterruptMapIter {
            address_cells: self.address_cells,
            interrupt_cells: self.interrupt_cells,
            node: self.node,
            encoded_map: self.encoded_map,
            _collectors: core::marker::PhantomData,
        }
    }

    /// Create an iterator over each individual [`InterruptMapEntry`] which uses the provided mask to modify the .
    pub fn iter_masked(
        self,
        mask: InterruptMapMask<CAddr, CInt>,
    ) -> MaskedInterruptMapIter<'a, CAddr, CInt, PAddr, PInt, P>
    where
        <CAddr as CellCollector>::Output:
            Clone + core::ops::BitAnd<<CAddr as CellCollector>::Output, Output = <CAddr as CellCollector>::Output>,
        <CInt as CellCollector>::Output:
            Clone + core::ops::BitAnd<<CInt as CellCollector>::Output, Output = <CInt as CellCollector>::Output>,
    {
        MaskedInterruptMapIter {
            address_cells: self.address_cells,
            interrupt_cells: self.interrupt_cells,
            node: self.node,
            encoded_map: self.encoded_map,
            mask,
            _collectors: core::marker::PhantomData,
        }
    }

    /// Attempt to find a specific child unit address with a specific child
    /// interrupt specifier.
    #[allow(clippy::type_complexity)]
    pub fn find(
        self,
        client_unit_address: CAddr::Output,
        child_interrupt_specifier: CInt::Output,
    ) -> P::Output<Option<InterruptMapEntry<'a, CAddr, CInt, PAddr, PInt, P>>>
    where
        CAddr::Output: PartialEq,
        CInt::Output: PartialEq,
    {
        let this: InterruptMap<_, _, _, _, (P::Parser, NoPanic)> = InterruptMap {
            address_cells: self.address_cells,
            interrupt_cells: self.interrupt_cells,
            node: self.node,
            encoded_map: self.encoded_map,
            _collectors: self._collectors,
        };

        P::to_output(
            this.iter()
                .find(|e| match e {
                    Err(_) => true,
                    Ok(entry) => {
                        entry.child_unit_address == client_unit_address
                            && entry.child_interrupt_specifier == child_interrupt_specifier
                    }
                })
                .transpose()
                .map(|e| {
                    e.map(|e| InterruptMapEntry::<_, _, _, _, P> {
                        child_unit_address: e.child_unit_address,
                        child_interrupt_specifier: e.child_interrupt_specifier,
                        interrupt_parent: e.interrupt_parent.alt(),
                        parent_unit_address: e.parent_unit_address,
                        parent_interrupt_specifier: e.parent_interrupt_specifier,
                    })
                }),
        )
    }
}

impl<
        'a,
        P: ParserWithMode<'a>,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
    > Property<'a, P> for InterruptMap<'a, CAddr, CInt, PAddr, PInt, P>
{
    fn parse(node: FallibleNode<'a, P>, _: FallibleRoot<'a, P>) -> Result<Option<Self>, FdtError> {
        let Some(encoded_map) = node.properties()?.find("interrupt-map")? else { return Ok(None) };

        let address_cells =
            node.property::<AddressCells>()?.ok_or(FdtError::MissingRequiredProperty("#address-cells"))?;
        let interrupt_cells =
            node.property::<InterruptCells>()?.ok_or(FdtError::MissingRequiredProperty("#interrupt-cells"))?;

        Ok(Some(InterruptMap {
            address_cells,
            interrupt_cells,
            node: node.alt(),
            encoded_map: encoded_map.value,
            _collectors: core::marker::PhantomData,
        }))
    }
}

#[allow(missing_docs)]
pub struct InterruptMapIter<
    'a,
    CAddr: CellCollector,
    CInt: CellCollector,
    PAddr: CellCollector,
    PInt: CellCollector,
    P: ParserWithMode<'a> = (AlignedParser<'a>, Panic),
> {
    address_cells: AddressCells,
    interrupt_cells: InterruptCells,
    node: FallibleNode<'a, P>,
    encoded_map: &'a [u8],
    _collectors: core::marker::PhantomData<*mut (CAddr, CInt, PAddr, PInt)>,
}

impl<
        'a,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
        P: ParserWithMode<'a>,
    > Iterator for InterruptMapIter<'a, CAddr, CInt, PAddr, PInt, P>
{
    type Item = P::Output<InterruptMapEntry<'a, CAddr, CInt, PAddr, PInt, P>>;

    #[track_caller]
    fn next(&mut self) -> Option<Self::Item> {
        let res = crate::tryblock!({
            let child_addr_size = self.address_cells.0 * 4;
            let child_intsp_size = self.interrupt_cells.as_byte_count();

            let Some((child_address_iter, rest)) = self.encoded_map.split_at_checked(child_addr_size) else {
                return Ok(None);
            };
            let Some((child_specifier_iter, rest)) = rest.split_at_checked(child_intsp_size) else {
                return Ok(None);
            };
            let Some((interrupt_parent, rest)) = rest.split_at_checked(4) else {
                return Ok(None);
            };

            let root = self.node.make_root::<(P::Parser, NoPanic)>()?;
            let phandle = u32::from_ne_bytes(interrupt_parent.try_into().unwrap());
            let interrupt_parent = root
                .resolve_phandle(PHandle(BigEndianU32::from_be(phandle)))?
                .ok_or(FdtError::MissingPHandleNode(phandle.swap_bytes()))?;

            let parent_address_cells = interrupt_parent
                .property::<AddressCells>()?
                .ok_or(FdtError::MissingRequiredProperty("#address-cells"))?;
            let parent_interrupt_cells = interrupt_parent
                .property::<InterruptCells>()?
                .ok_or(FdtError::MissingRequiredProperty("#interrupt-cells"))?;

            let parent_addr_size = parent_address_cells.0 * 4;
            let parent_intsp_size = parent_interrupt_cells.as_byte_count();

            let Some((parent_address_iter, rest)) = rest.split_at_checked(parent_addr_size) else {
                return Ok(None);
            };

            let Some((parent_specifier_iter, rest)) = rest.split_at_checked(parent_intsp_size) else {
                return Ok(None);
            };
            self.encoded_map = rest;

            let mut child_address_collector = CAddr::Builder::default();
            for chunk in child_address_iter.chunks_exact(4) {
                child_address_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut child_specifier_collector = CInt::Builder::default();
            for chunk in child_specifier_iter.chunks_exact(4) {
                child_specifier_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut parent_address_collector = PAddr::Builder::default();
            for chunk in parent_address_iter.chunks_exact(4) {
                parent_address_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut parent_specifier_collector = PInt::Builder::default();
            for chunk in parent_specifier_iter.chunks_exact(4) {
                parent_specifier_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            Ok(Some(InterruptMapEntry {
                interrupt_parent: interrupt_parent.alt(),
                child_unit_address: CAddr::map(child_address_collector.finish()),
                child_interrupt_specifier: CInt::map(child_specifier_collector.finish()),
                parent_unit_address: PAddr::map(parent_address_collector.finish()),
                parent_interrupt_specifier: PInt::map(parent_specifier_collector.finish()),
            }))
        });

        #[allow(clippy::manual_map)]
        match res.transpose() {
            Some(output) => Some(P::to_output(output)),
            None => None,
        }
    }
}

#[allow(missing_docs)]
pub struct MaskedInterruptMapIter<
    'a,
    CAddr: CellCollector,
    CInt: CellCollector,
    PAddr: CellCollector,
    PInt: CellCollector,
    P: ParserWithMode<'a> = (AlignedParser<'a>, Panic),
> where
    <CAddr as CellCollector>::Output:
        Clone + core::ops::BitAnd<<CAddr as CellCollector>::Output, Output = <CAddr as CellCollector>::Output>,
    <CInt as CellCollector>::Output:
        Clone + core::ops::BitAnd<<CInt as CellCollector>::Output, Output = <CInt as CellCollector>::Output>,
{
    address_cells: AddressCells,
    interrupt_cells: InterruptCells,
    node: FallibleNode<'a, P>,
    encoded_map: &'a [u8],
    mask: InterruptMapMask<CAddr, CInt>,
    _collectors: core::marker::PhantomData<*mut (CAddr, CInt, PAddr, PInt)>,
}

impl<
        'a,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
        P: ParserWithMode<'a>,
    > Iterator for MaskedInterruptMapIter<'a, CAddr, CInt, PAddr, PInt, P>
where
    <CAddr as CellCollector>::Output:
        Clone + core::ops::BitAnd<<CAddr as CellCollector>::Output, Output = <CAddr as CellCollector>::Output>,
    <CInt as CellCollector>::Output:
        Clone + core::ops::BitAnd<<CInt as CellCollector>::Output, Output = <CInt as CellCollector>::Output>,
{
    type Item = P::Output<InterruptMapEntry<'a, CAddr, CInt, PAddr, PInt, P>>;

    #[track_caller]
    fn next(&mut self) -> Option<Self::Item> {
        let res = crate::tryblock!({
            let child_addr_size = self.address_cells.0 * 4;
            let child_intsp_size = self.interrupt_cells.as_byte_count();

            let Some((child_address_iter, rest)) = self.encoded_map.split_at_checked(child_addr_size) else {
                return Ok(None);
            };
            let Some((child_specifier_iter, rest)) = rest.split_at_checked(child_intsp_size) else {
                return Ok(None);
            };
            let Some((interrupt_parent, rest)) = rest.split_at_checked(4) else {
                return Ok(None);
            };

            let root = self.node.make_root::<(P::Parser, NoPanic)>()?;
            let phandle = u32::from_ne_bytes(interrupt_parent.try_into().unwrap());
            let interrupt_parent = root
                .resolve_phandle(PHandle(BigEndianU32::from_be(phandle)))?
                .ok_or(FdtError::MissingPHandleNode(phandle.swap_bytes()))?;

            let parent_address_cells = interrupt_parent
                .property::<AddressCells>()?
                .ok_or(FdtError::MissingRequiredProperty("#address-cells"))?;
            let parent_interrupt_cells = interrupt_parent
                .property::<InterruptCells>()?
                .ok_or(FdtError::MissingRequiredProperty("#interrupt-cells"))?;

            let parent_addr_size = parent_address_cells.0 * 4;
            let parent_intsp_size = parent_interrupt_cells.as_byte_count();

            let Some((parent_address_iter, rest)) = rest.split_at_checked(parent_addr_size) else {
                return Ok(None);
            };

            let Some((parent_specifier_iter, rest)) = rest.split_at_checked(parent_intsp_size) else {
                return Ok(None);
            };
            self.encoded_map = rest;

            let mut child_address_collector = CAddr::Builder::default();
            for chunk in child_address_iter.chunks_exact(4) {
                child_address_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut child_specifier_collector = CInt::Builder::default();
            for chunk in child_specifier_iter.chunks_exact(4) {
                child_specifier_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut parent_address_collector = PAddr::Builder::default();
            for chunk in parent_address_iter.chunks_exact(4) {
                parent_address_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let mut parent_specifier_collector = PInt::Builder::default();
            for chunk in parent_specifier_iter.chunks_exact(4) {
                parent_specifier_collector.push(u32::from_be_bytes(chunk.try_into().unwrap()))?;
            }

            let child_unit_address = CAddr::map(child_address_collector.finish());
            let child_interrupt_specifier = CInt::map(child_specifier_collector.finish());
            let (child_unit_address, child_interrupt_specifier) =
                self.mask.mask(child_unit_address, child_interrupt_specifier);

            Ok(Some(InterruptMapEntry {
                interrupt_parent: interrupt_parent.alt(),
                child_unit_address,
                child_interrupt_specifier,
                parent_unit_address: PAddr::map(parent_address_collector.finish()),
                parent_interrupt_specifier: PInt::map(parent_specifier_collector.finish()),
            }))
        });

        #[allow(clippy::manual_map)]
        match res.transpose() {
            Some(output) => Some(P::to_output(output)),
            None => None,
        }
    }
}

/// [Devicetree 2.4.3.1.
/// `interrupt-map`](https://devicetree-specification.readthedocs.io/en/latest/chapter2-devicetree-basics.html#interrupt-map)
///
/// An individual `interrupt-map` entry, including the resolved interrupt parent
/// [`PHandle`].
pub struct InterruptMapEntry<
    'a,
    CAddr: CellCollector,
    CInt: CellCollector,
    PAddr: CellCollector,
    PInt: CellCollector,
    P: ParserWithMode<'a>,
> {
    /// Interrupt parent of this entry.
    pub interrupt_parent: Node<'a, P>,
    /// See [`InterruptMap`] for more information.
    pub child_unit_address: CAddr::Output,
    /// See [`InterruptMap`] for more information.
    pub child_interrupt_specifier: CInt::Output,
    /// See [`InterruptMap`] for more information.
    pub parent_unit_address: PAddr::Output,
    /// See [`InterruptMap`] for more information.
    pub parent_interrupt_specifier: PInt::Output,
}

impl<
        'a,
        P: ParserWithMode<'a>,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
    > Clone for InterruptMapEntry<'a, CAddr, CInt, PAddr, PInt, P>
where
    CAddr::Output: Clone,
    CInt::Output: Clone,
    PAddr::Output: Clone,
    PInt::Output: Clone,
{
    fn clone(&self) -> Self {
        Self {
            child_unit_address: self.child_unit_address.clone(),
            child_interrupt_specifier: self.child_interrupt_specifier.clone(),
            interrupt_parent: self.interrupt_parent,
            parent_unit_address: self.parent_unit_address.clone(),
            parent_interrupt_specifier: self.parent_interrupt_specifier.clone(),
        }
    }
}

impl<
        'a,
        P: ParserWithMode<'a>,
        CAddr: CellCollector,
        CInt: CellCollector,
        PAddr: CellCollector,
        PInt: CellCollector,
    > Copy for InterruptMapEntry<'a, CAddr, CInt, PAddr, PInt, P>
where
    CAddr::Output: Copy,
    CInt::Output: Copy,
    PAddr::Output: Copy,
    PInt::Output: Copy,
{
}