dtoolkit 0.1.1

A library for parsing and manipulating Flattened Device Tree (FDT) blobs.
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
// Copyright 2025 Google LLC
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.

//! A read-only API for parsing and traversing a [Flattened Device Tree (FDT)].
//!
//! This module provides the [`Fdt`] struct, which is the entry point for
//! parsing and traversing an FDT blob. The API is designed to be safe and
//! efficient, performing no memory allocation and providing a zero-copy view
//! of the FDT data.
//!
//! [Flattened Device Tree (FDT)]: https://devicetree-specification.readthedocs.io/en/latest/chapter5-flattened-format.html

mod node;
mod property;

use core::ffi::CStr;
use core::fmt::{self, Debug, Display, Formatter};
use core::mem::offset_of;
use core::ptr;

use zerocopy::byteorder::big_endian;
use zerocopy::{FromBytes, Immutable, IntoBytes, KnownLayout, Unaligned};

pub use self::node::FdtNode;
pub use self::property::FdtProperty;
use crate::Node;
use crate::error::{FdtErrorKind, FdtParseError};
use crate::memreserve::MemoryReservation;

/// Version of the FDT specification supported by this library.
const FDT_VERSION: u32 = 17;
pub(crate) const FDT_TAGSIZE: usize = size_of::<u32>();
pub(crate) const FDT_MAGIC: u32 = 0xd00d_feed;
pub(crate) const FDT_BEGIN_NODE: u32 = 0x1;
pub(crate) const FDT_END_NODE: u32 = 0x2;
pub(crate) const FDT_END: u32 = 0x9;
pub(crate) const FDT_PROP: u32 = 0x3;
pub(crate) const FDT_NOP: u32 = 0x4;

#[repr(C, packed)]
#[derive(Debug, Copy, Clone, FromBytes, IntoBytes, Unaligned, Immutable, KnownLayout)]
pub(crate) struct FdtHeader {
    /// Magic number of the device tree.
    pub(crate) magic: big_endian::U32,
    /// Total size of the device tree.
    pub(crate) totalsize: big_endian::U32,
    /// Offset of the device tree structure.
    pub(crate) off_dt_struct: big_endian::U32,
    /// Offset of the device tree strings.
    pub(crate) off_dt_strings: big_endian::U32,
    /// Offset of the memory reservation map.
    pub(crate) off_mem_rsvmap: big_endian::U32,
    /// Version of the device tree.
    pub(crate) version: big_endian::U32,
    /// Last compatible version of the device tree.
    pub(crate) last_comp_version: big_endian::U32,
    /// Physical ID of the boot CPU.
    pub(crate) boot_cpuid_phys: big_endian::U32,
    /// Size of the device tree strings.
    pub(crate) size_dt_strings: big_endian::U32,
    /// Size of the device tree structure.
    pub(crate) size_dt_struct: big_endian::U32,
}

impl FdtHeader {
    pub(crate) fn magic(&self) -> u32 {
        self.magic.get()
    }

    pub(crate) fn totalsize(&self) -> u32 {
        self.totalsize.get()
    }

    pub(crate) fn off_dt_struct(&self) -> u32 {
        self.off_dt_struct.get()
    }

    pub(crate) fn off_dt_strings(&self) -> u32 {
        self.off_dt_strings.get()
    }

    pub(crate) fn off_mem_rsvmap(&self) -> u32 {
        self.off_mem_rsvmap.get()
    }

    pub(crate) fn version(&self) -> u32 {
        self.version.get()
    }

    pub(crate) fn last_comp_version(&self) -> u32 {
        self.last_comp_version.get()
    }

    pub(crate) fn boot_cpuid_phys(&self) -> u32 {
        self.boot_cpuid_phys.get()
    }

    pub(crate) fn size_dt_strings(&self) -> u32 {
        self.size_dt_strings.get()
    }

    pub(crate) fn size_dt_struct(&self) -> u32 {
        self.size_dt_struct.get()
    }
}

/// A flattened device tree.
#[derive(Clone, Copy)]
pub struct Fdt<'a> {
    pub(crate) data: &'a [u8],
}

impl Debug for Fdt<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        write!(
            f,
            "Fdt {{ data: {} bytes at {:?} }}",
            self.data.len(),
            self.data.as_ptr()
        )
    }
}

/// A token in the device tree structure.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FdtToken {
    BeginNode,
    EndNode,
    Prop,
    Nop,
    End,
}

impl TryFrom<u32> for FdtToken {
    type Error = u32;

    fn try_from(value: u32) -> Result<Self, Self::Error> {
        match value {
            FDT_BEGIN_NODE => Ok(FdtToken::BeginNode),
            FDT_END_NODE => Ok(FdtToken::EndNode),
            FDT_PROP => Ok(FdtToken::Prop),
            FDT_NOP => Ok(FdtToken::Nop),
            FDT_END => Ok(FdtToken::End),
            _ => Err(value),
        }
    }
}

impl<'a> Fdt<'a> {
    /// Creates a new `Fdt` from the given byte slice.
    ///
    /// # Errors
    ///
    /// Returns an [`FdtErrorKind::InvalidLength`] if `data` is too short to
    /// contain a valid FDT header or if the `totalsize` field in the header
    /// does not match the length of `data`.
    ///
    /// Returns an [`FdtErrorKind::InvalidMagic`] if the `magic` field in the
    /// header is not `0xd00dfeed`.
    ///
    /// Returns an [`FdtErrorKind::UnsupportedVersion`] if the `version` field
    /// in the header is not supported by this library.
    ///
    /// Returns an [`FdtErrorKind::InvalidHeader`] if the header fails to pass
    /// the header integrity checks.
    ///
    /// # Examples
    ///
    /// ```
    /// # use dtoolkit::fdt::Fdt;
    /// # let dtb = include_bytes!("../../tests/dtb/test.dtb");
    /// let fdt = Fdt::new(dtb).unwrap();
    /// ```
    pub fn new(data: &'a [u8]) -> Result<Self, FdtParseError> {
        let fdt = Self::new_unchecked(data);
        fdt.validate()?;
        Ok(fdt)
    }

    /// Creates a new `Fdt` from the given byte slice without validation.
    ///
    /// # Safety
    ///
    /// The caller must ensure that `data` contains a valid Flattened Device
    /// Tree (FDT) blob. If the blob is invalid, methods on `Fdt` and
    /// related types may panic.
    #[must_use]
    pub fn new_unchecked(data: &'a [u8]) -> Self {
        Self { data }
    }

    /// Creates a new `Fdt` from the given pointer without validation.
    ///
    /// # Safety
    ///
    /// The `data` pointer must be a valid pointer to a Flattened Device Tree
    /// (FDT) blob. The memory region starting at `data` and spanning
    /// `totalsize` bytes (as specified in the FDT header) must be valid and
    /// accessible for reading.
    #[expect(
        unsafe_code,
        reason = "Having a methods that reads a Device Tree from a raw pointer is useful for \
        embedded applications, where the binary only gets a pointer to DT from the firmware or \
        a bootloader. The user must ensure it trusts the data."
    )]
    #[must_use]
    pub unsafe fn from_raw_unchecked(data: *const u8) -> Self {
        // SAFETY: The caller guarantees that `data` is a valid pointer to a Flattened
        // Device Tree (FDT) blob. We are reading an `FdtHeader` from this
        // pointer, which is a `#[repr(C, packed)]` struct. The `totalsize`
        // field of this header is then used to determine the total size of the FDT
        // blob. The caller must ensure that the memory at `data` is valid for
        // at least `size_of::<FdtHeader>()` bytes.
        let header = unsafe { ptr::read_unaligned(data.cast::<FdtHeader>()) };
        let size = header.totalsize();
        // SAFETY: The caller must ensure that `data` is a valid pointer to a Flattened
        // Device Tree (FDT) blob. The caller must ensure the `data` spans
        // `totalsize` bytes (as specified in the FDT header).
        let slice = unsafe { core::slice::from_raw_parts(data, size as usize) };
        Self::new_unchecked(slice)
    }

    /// Creates a new `Fdt` from the given pointer.
    ///
    /// # Safety
    ///
    /// The `data` pointer must be a valid pointer to a Flattened Device Tree
    /// (FDT) blob. The memory region starting at `data` and spanning
    /// `totalsize` bytes (as specified in the FDT header) must be valid and
    /// accessible for reading. The FDT blob must be well-formed and adhere
    /// to the Device Tree Specification.
    ///
    /// # Errors
    ///
    /// This function can return the same errors as [`Fdt::new`].
    ///
    /// # Examples
    ///
    /// ```
    /// # use dtoolkit::fdt::Fdt;
    /// # let dtb = include_bytes!("../../tests/dtb/test.dtb");
    /// let ptr = dtb.as_ptr();
    /// let fdt = unsafe { Fdt::from_raw(ptr).unwrap() };
    /// ```
    #[expect(
        unsafe_code,
        reason = "Having a methods that reads a Device Tree from a raw pointer is useful for \
        embedded applications, where the binary only gets a pointer to DT from the firmware or \
        a bootloader. The user must ensure it trusts the data."
    )]
    pub unsafe fn from_raw(data: *const u8) -> Result<Self, FdtParseError> {
        // SAFETY: The caller guarantees that `data` is a valid pointer to a Flattened
        // Device Tree (FDT) blob.
        let fdt = unsafe { Self::from_raw_unchecked(data) };
        fdt.validate()?;
        Ok(fdt)
    }

    fn validate(self) -> Result<(), FdtParseError> {
        if self.data.len() < size_of::<FdtHeader>() {
            return Err(FdtParseError::new(FdtErrorKind::InvalidLength, 0));
        }

        let header = self.header();

        if header.magic() != FDT_MAGIC {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidMagic,
                offset_of!(FdtHeader, magic),
            ));
        }
        if !(header.last_comp_version()..=header.version()).contains(&FDT_VERSION) {
            return Err(FdtParseError::new(
                FdtErrorKind::UnsupportedVersion(header.version()),
                offset_of!(FdtHeader, version),
            ));
        }

        if header.totalsize() as usize != self.data.len() {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidLength,
                offset_of!(FdtHeader, totalsize),
            ));
        }

        self.validate_header()?;
        self.validate_mem_reservations()?;

        // Validate structure block
        let offset = header.off_dt_struct() as usize;
        // Check root node
        if self.read_token(offset)? != FdtToken::BeginNode {
            return Err(FdtParseError::new(
                FdtErrorKind::BadToken(FDT_BEGIN_NODE),
                offset,
            ));
        }

        let end_offset = self.traverse_node(offset, true)?;

        // Check FDT_END
        if self.read_token(end_offset)? != FdtToken::End {
            return Err(FdtParseError::new(
                FdtErrorKind::BadToken(FDT_END),
                end_offset,
            ));
        }

        Ok(())
    }

    fn validate_mem_reservations(self) -> Result<(), FdtParseError> {
        let header = self.header();
        let mut offset = header.off_mem_rsvmap() as usize;
        loop {
            if offset >= header.off_dt_struct() as usize {
                return Err(FdtParseError::new(
                    FdtErrorKind::MemReserveNotTerminated,
                    offset,
                ));
            }

            let (reservation, _) = MemoryReservation::ref_from_prefix(&self.data[offset..])
                .map_err(|_| FdtParseError::new(FdtErrorKind::MemReserveInvalid, offset))?;
            offset += size_of::<MemoryReservation>();

            if *reservation == MemoryReservation::TERMINATOR {
                break;
            }
        }
        Ok(())
    }

    fn traverse_node(self, offset: usize, check_strings: bool) -> Result<usize, FdtParseError> {
        let mut offset = offset;
        let mut depth = 0;
        loop {
            let token = self.read_token(offset)?;
            match token {
                FdtToken::BeginNode => {
                    depth += 1;
                    offset += FDT_TAGSIZE;
                    // Validate name
                    offset = self.find_string_end(offset)?;
                    offset = Self::align_tag_offset(offset);
                }
                FdtToken::EndNode => {
                    if depth == 0 {
                        return Err(FdtParseError::new(
                            FdtErrorKind::BadToken(FDT_END_NODE),
                            offset,
                        ));
                    }
                    depth -= 1;
                    offset += FDT_TAGSIZE;
                    if depth == 0 {
                        // End of root node
                        return Ok(offset);
                    }
                }
                FdtToken::Prop => {
                    offset += FDT_TAGSIZE;
                    offset = self.next_property_offset(offset, check_strings)?;
                }
                FdtToken::Nop => offset += FDT_TAGSIZE,
                FdtToken::End => {
                    return Err(FdtParseError::new(FdtErrorKind::BadToken(FDT_END), offset));
                }
            }
        }
    }

    fn validate_header(self) -> Result<(), FdtParseError> {
        let header = self.header();
        let data = &self.data;

        let off_mem_rsvmap = header.off_mem_rsvmap() as usize;
        let off_dt_struct = header.off_dt_struct() as usize;
        let off_dt_strings = header.off_dt_strings() as usize;
        if off_mem_rsvmap > off_dt_struct {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("dt_struct not after memrsvmap"),
                offset_of!(FdtHeader, off_mem_rsvmap),
            ));
        }
        if off_dt_struct > data.len() {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("struct offset out of bounds"),
                offset_of!(FdtHeader, off_dt_struct),
            ));
        }
        if off_dt_strings > data.len() {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("strings offset out of bounds"),
                offset_of!(FdtHeader, off_dt_strings),
            ));
        }

        let size_dt_struct = header.size_dt_struct() as usize;
        let size_dt_strings = header.size_dt_strings() as usize;
        if off_dt_struct.saturating_add(size_dt_struct) > data.len() {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("struct block overflows"),
                offset_of!(FdtHeader, size_dt_struct),
            ));
        }
        if off_dt_strings.saturating_add(size_dt_strings) > data.len() {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("strings block overflows"),
                offset_of!(FdtHeader, size_dt_strings),
            ));
        }
        if off_dt_struct.saturating_add(size_dt_struct) > off_dt_strings {
            return Err(FdtParseError::new(
                FdtErrorKind::InvalidHeader("strings block not after struct block"),
                offset_of!(FdtHeader, off_dt_strings),
            ));
        }

        Ok(())
    }

    /// Returns the header of the device tree.
    pub(crate) fn header(self) -> &'a FdtHeader {
        let (header, _remaining_bytes) = FdtHeader::ref_from_prefix(self.data)
            .expect("new() checks if the slice is at least as big as the header");
        header
    }

    /// Returns the underlying data slice of the FDT.
    #[must_use]
    pub fn data(self) -> &'a [u8] {
        self.data
    }

    /// Returns the version of the FDT.
    #[must_use]
    pub fn version(self) -> u32 {
        self.header().version()
    }

    /// Returns the last compatible version of the FDT.
    #[must_use]
    pub fn last_comp_version(self) -> u32 {
        self.header().last_comp_version()
    }

    /// Returns the physical ID of the boot CPU.
    #[must_use]
    pub fn boot_cpuid_phys(self) -> u32 {
        self.header().boot_cpuid_phys()
    }

    /// Returns an iterator over the memory reservation block.
    ///
    /// # Panics
    ///
    /// Panics if the [`Fdt`] structure was constructed using
    /// [`Fdt::new_unchecked`] or [`Fdt::from_raw_unchecked`] and the FDT is not
    /// valid.
    pub fn memory_reservations(self) -> impl Iterator<Item = MemoryReservation> + 'a {
        let mut offset = self.header().off_mem_rsvmap() as usize;
        core::iter::from_fn(move || {
            let (reservation, _) = MemoryReservation::ref_from_prefix(&self.data[offset..])
                .expect("Fdt should be valid");
            offset += size_of::<MemoryReservation>();

            if *reservation == MemoryReservation::TERMINATOR {
                return None;
            }
            Some(*reservation)
        })
    }

    /// Returns the root node of the device tree.
    ///
    /// # Panics
    ///
    /// Panics if the [`Fdt`] structure was constructed using
    /// [`Fdt::new_unchecked`] or [`Fdt::from_raw_unchecked`] and the FDT is not
    /// valid.
    ///
    /// # Examples
    ///
    /// ```
    /// use dtoolkit::Node;
    /// use dtoolkit::fdt::Fdt;
    ///
    /// # let dtb = include_bytes!("../../tests/dtb/test.dtb");
    /// let fdt = Fdt::new(dtb).unwrap();
    /// let root = fdt.root();
    /// assert_eq!(root.name(), "");
    /// ```
    #[must_use]
    pub fn root(self) -> FdtNode<'a> {
        let offset = self.header().off_dt_struct() as usize;
        FdtNode::new(self, offset)
    }

    /// Finds a node by its path.
    ///
    /// If a name in the given path contains a _unit-address_ (the part after
    /// the `@` sign) then both the _node-name_ and _unit-address_ must
    /// match. If it doesn't have a _unit-address_, then nodes with any
    /// _unit-address_ or none will be allowed.
    ///
    /// For example, searching for `/cpus/cpu` would match either `/cpus/cpu`,
    /// `/cpus/cpu@0` or `/cpus/cpu@1`, while `/cpus/cpu@1` would match only the
    /// latter.
    ///
    /// # Performance
    ///
    /// This method traverses the device tree and its performance is linear in
    /// the number of nodes in the path. If you need to call this often,
    /// consider using
    /// [`DeviceTree::from_fdt`](crate::model::DeviceTree::from_fdt)
    /// first. [`DeviceTree`](crate::model::DeviceTree) stores the nodes in a
    /// hash map for constant-time lookup.
    ///
    /// # Panics
    ///
    /// Panics if the [`Fdt`] structure was constructed using
    /// [`Fdt::new_unchecked`] or [`Fdt::from_raw_unchecked`] and the FDT is not
    /// valid.
    ///
    /// # Examples
    ///
    /// ```
    /// use dtoolkit::Node;
    /// use dtoolkit::fdt::Fdt;
    ///
    /// # let dtb = include_bytes!("../../tests/dtb/test_traversal.dtb");
    /// let fdt = Fdt::new(dtb).unwrap();
    /// let node = fdt.find_node("/a/b/c").unwrap();
    /// assert_eq!(node.name(), "c");
    /// ```
    ///
    /// ```
    /// use dtoolkit::Node;
    /// use dtoolkit::fdt::Fdt;
    ///
    /// # let dtb = include_bytes!("../../tests/dtb/test_children.dtb");
    /// let fdt = Fdt::new(dtb).unwrap();
    /// let node = fdt.find_node("/child2").unwrap();
    /// assert_eq!(node.name(), "child2@42");
    /// let node = fdt.find_node("/child2@42").unwrap();
    /// assert_eq!(node.name(), "child2@42");
    /// ```
    #[must_use]
    pub fn find_node(self, path: &str) -> Option<FdtNode<'a>> {
        if !path.starts_with('/') {
            return None;
        }
        let mut current_node = self.root();
        if path == "/" {
            return Some(current_node);
        }
        for component in path.split('/').filter(|s| !s.is_empty()) {
            match current_node.child(component) {
                Some(node) => current_node = node,
                None => return None,
            }
        }
        Some(current_node)
    }

    pub(crate) fn read_token(self, offset: usize) -> Result<FdtToken, FdtParseError> {
        let val = big_endian::U32::ref_from_prefix(&self.data[offset..])
            .map(|(val, _)| val.get())
            .map_err(|_e| FdtParseError::new(FdtErrorKind::InvalidLength, offset))?;
        FdtToken::try_from(val).map_err(|t| FdtParseError::new(FdtErrorKind::BadToken(t), offset))
    }

    /// Returns a string from the string block.
    pub(crate) fn string(self, string_block_offset: usize) -> Result<&'a str, FdtParseError> {
        let header = self.header();
        let str_block_start = header.off_dt_strings() as usize;
        let str_block_size = header.size_dt_strings() as usize;
        let str_block_end = str_block_start + str_block_size;
        let str_start = str_block_start + string_block_offset;

        if str_start >= str_block_end {
            return Err(FdtParseError::new(FdtErrorKind::InvalidLength, str_start));
        }

        self.string_at_offset(str_start, Some(str_block_end))
    }

    /// Returns a NUL-terminated string from a given offset.
    pub(crate) fn string_at_offset(
        self,
        offset: usize,
        end: Option<usize>,
    ) -> Result<&'a str, FdtParseError> {
        let slice = match end {
            Some(end) => self.data.get(offset..end),
            None => self.data.get(offset..),
        };
        let slice = slice.ok_or(FdtParseError::new(FdtErrorKind::InvalidOffset, offset))?;

        match CStr::from_bytes_until_nul(slice).map(|val| val.to_str()) {
            Ok(Ok(val)) => Ok(val),
            _ => Err(FdtParseError::new(FdtErrorKind::InvalidString, offset)),
        }
    }

    pub(crate) fn find_string_end(self, start: usize) -> Result<usize, FdtParseError> {
        let mut offset = start;
        loop {
            match self.data.get(offset) {
                Some(0) => return Ok(offset + 1),
                Some(_) => {}
                None => return Err(FdtParseError::new(FdtErrorKind::InvalidString, start)),
            }
            offset += 1;
        }
    }

    pub(crate) fn next_sibling_offset(self, offset: usize) -> Result<usize, FdtParseError> {
        self.traverse_node(offset, false)
    }

    pub(crate) fn next_property_offset(
        self,
        offset: usize,
        check_name: bool,
    ) -> Result<usize, FdtParseError> {
        let len = big_endian::U32::ref_from_prefix(&self.data[offset..])
            .map(|(val, _)| val.get())
            .map_err(|_e| FdtParseError::new(FdtErrorKind::InvalidLength, offset))?
            as usize;
        let nameoff = big_endian::U32::ref_from_prefix(&self.data[offset + FDT_TAGSIZE..])
            .map(|(val, _)| val.get())
            .map_err(|_e| FdtParseError::new(FdtErrorKind::InvalidLength, offset))?
            as usize;

        if check_name {
            self.string(nameoff)?;
        }

        let prop_offset = offset + 2 * FDT_TAGSIZE;
        let end_offset = prop_offset + len;
        if end_offset > self.data.len() {
            return Err(FdtParseError::new(FdtErrorKind::InvalidLength, prop_offset));
        }

        Ok(Self::align_tag_offset(end_offset))
    }

    pub(crate) fn align_tag_offset(offset: usize) -> usize {
        offset.next_multiple_of(FDT_TAGSIZE)
    }
}

impl Display for Fdt<'_> {
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        writeln!(f, "/dts-v1/;")?;
        for reservation in self.memory_reservations() {
            writeln!(
                f,
                "/memreserve/ {:#x} {:#x};",
                reservation.address(),
                reservation.size()
            )?;
        }
        writeln!(f)?;
        let root = self.root();
        root.fmt_recursive(f, 0)
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::error::FdtErrorKind;

    const FDT_HEADER_OK: &[u8] = &[
        0xd0, 0x0d, 0xfe, 0xed, // magic
        0x00, 0x00, 0x00, 0x48, // totalsize = 72
        0x00, 0x00, 0x00, 0x38, // off_dt_struct = 56
        0x00, 0x00, 0x00, 0x48, // off_dt_strings = 72
        0x00, 0x00, 0x00, 0x28, // off_mem_rsvmap = 40
        0x00, 0x00, 0x00, 0x11, // version = 17
        0x00, 0x00, 0x00, 0x10, // last_comp_version = 16
        0x00, 0x00, 0x00, 0x00, // boot_cpuid_phys = 0
        0x00, 0x00, 0x00, 0x00, // size_dt_strings = 0
        0x00, 0x00, 0x00, 0x10, // size_dt_struct = 16
        0x00, 0x00, 0x00, 0x00, // memory reservation
        0x00, 0x00, 0x00, 0x00, // ...
        0x00, 0x00, 0x00, 0x00, // ...
        0x00, 0x00, 0x00, 0x00, // ...
        0x00, 0x00, 0x00, 0x01, // FDT_BEGIN_NODE
        0x00, 0x00, 0x00, 0x00, // ""
        0x00, 0x00, 0x00, 0x02, // FDT_END_NODE
        0x00, 0x00, 0x00, 0x09, // FDT_END
    ];

    #[test]
    fn header_is_parsed_correctly() {
        let fdt = Fdt::new(FDT_HEADER_OK).unwrap();
        let header = fdt.header();

        assert_eq!(header.totalsize(), 72);
        assert_eq!(header.off_dt_struct(), 56);
        assert_eq!(header.off_dt_strings(), 72);
        assert_eq!(header.off_mem_rsvmap(), 40);
        assert_eq!(header.version(), 17);
        assert_eq!(header.last_comp_version(), 16);
        assert_eq!(header.boot_cpuid_phys(), 0);
        assert_eq!(header.size_dt_strings(), 0);
        assert_eq!(header.size_dt_struct(), 16);
    }

    #[test]
    fn invalid_magic() {
        let mut header = FDT_HEADER_OK.to_vec();
        header[0] = 0x00;
        let result = Fdt::new(&header);
        assert!(matches!(result, Err(e) if matches!(e.kind, FdtErrorKind::InvalidMagic)));
    }

    #[test]
    fn invalid_length() {
        let header = &FDT_HEADER_OK[..10];
        let result = Fdt::new(header);
        assert!(matches!(result, Err(e) if matches!(e.kind, FdtErrorKind::InvalidLength)));
    }

    #[test]
    fn unsupported_version() {
        let mut header = FDT_HEADER_OK.to_vec();
        header[23] = 0x10;
        let result = Fdt::new(&header);
        assert!(matches!(result, Err(e) if matches!(e.kind, FdtErrorKind::UnsupportedVersion(16))));
    }
}