|
| 1 | +// Copyright 2025 Google LLC |
| 2 | +// |
| 3 | +// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or |
| 4 | +// https://www.apache.org/licenses/LICENSE-2.0> or the MIT license |
| 5 | +// <LICENSE-MIT or https://opensource.org/licenses/MIT>, at your |
| 6 | +// option. This file may not be copied, modified, or distributed |
| 7 | +// except according to those terms. |
| 8 | + |
| 9 | +//! Error types for the `dtoolkit` crate. |
| 10 | +
|
| 11 | +use core::fmt; |
| 12 | + |
| 13 | +/// An error that can occur when parsing a device tree. |
| 14 | +#[derive(Debug)] |
| 15 | +#[non_exhaustive] |
| 16 | +pub struct FdtError { |
| 17 | + offset: usize, |
| 18 | + /// The type of the error that has occurred. |
| 19 | + pub kind: FdtErrorKind, |
| 20 | +} |
| 21 | + |
| 22 | +impl FdtError { |
| 23 | + pub(crate) fn new(kind: FdtErrorKind, offset: usize) -> Self { |
| 24 | + Self { offset, kind } |
| 25 | + } |
| 26 | +} |
| 27 | + |
| 28 | +/// The kind of an error that can occur when parsing a device tree. |
| 29 | +#[derive(Debug)] |
| 30 | +#[non_exhaustive] |
| 31 | +pub enum FdtErrorKind { |
| 32 | + /// The magic number of the device tree is invalid. |
| 33 | + InvalidMagic, |
| 34 | + /// The Device Tree version is not supported by this library. |
| 35 | + UnsupportedVersion(u32), |
| 36 | + /// The length of the device tree is invalid. |
| 37 | + InvalidLength, |
| 38 | + /// The header failed validation. |
| 39 | + InvalidHeader(&'static str), |
| 40 | + /// An invalid token was encountered. |
| 41 | + BadToken(u32), |
| 42 | + /// A read from data at invalid offset was attempted. |
| 43 | + InvalidOffset, |
| 44 | + /// An invalid string was encountered. |
| 45 | + InvalidString, |
| 46 | +} |
| 47 | + |
| 48 | +impl fmt::Display for FdtError { |
| 49 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 50 | + write!(f, "{} at offset {}", self.kind, self.offset) |
| 51 | + } |
| 52 | +} |
| 53 | + |
| 54 | +impl fmt::Display for FdtErrorKind { |
| 55 | + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { |
| 56 | + match self { |
| 57 | + FdtErrorKind::InvalidMagic => write!(f, "invalid FDT magic number"), |
| 58 | + FdtErrorKind::UnsupportedVersion(version) => { |
| 59 | + write!(f, "the FDT version {version} is not supported") |
| 60 | + } |
| 61 | + FdtErrorKind::InvalidLength => write!(f, "invalid FDT length"), |
| 62 | + FdtErrorKind::InvalidHeader(msg) => { |
| 63 | + write!(f, "FDT header has failed validation: {msg}") |
| 64 | + } |
| 65 | + FdtErrorKind::BadToken(token) => write!(f, "bad FDT token: 0x{token:x}"), |
| 66 | + FdtErrorKind::InvalidOffset => write!(f, "invalid offset in FDT"), |
| 67 | + FdtErrorKind::InvalidString => write!(f, "invalid string in FDT"), |
| 68 | + } |
| 69 | + } |
| 70 | +} |
| 71 | + |
| 72 | +impl core::error::Error for FdtError {} |
0 commit comments