dcm4rs 0.1.0

DICOM 数据模型与数据字典
Documentation
use std::fmt;
use std::str::Utf8Error;

use crate::tag::Tag;
use crate::vr::Vr;

/// Errors the core data model can produce.
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Error {
    /// The tag text could not be parsed.
    InvalidTag(String),
    /// Not a known VR.
    UnknownVr(String),
    /// The VR does not match the requested decoding.
    WrongVr {
        /// The element's actual VR.
        actual: Vr,
        /// The VR (or VR family) the decoding requires.
        expected: &'static str,
    },
    /// The value's byte length is not a multiple of its VR's unit.
    WrongLength {
        /// The element's VR.
        vr: Vr,
        /// Actual byte length.
        len: usize,
        /// Expected unit length (2, 4 or 8).
        unit: usize,
    },
    /// The value's bytes are not valid UTF-8.
    InvalidUtf8(Utf8Error),
    /// A numeric string could not be parsed.
    InvalidNumber(String),
    /// The data set does not contain this tag.
    MissingTag(Tag),
    /// The tag is present but has no value.
    NoValue(Tag),
    /// The value is not a sequence, or the VR is not `SQ`.
    NotASequence(Vr),
}

/// Convenience result alias.
pub type Result<T> = std::result::Result<T, Error>;

impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::InvalidTag(text) => write!(f, "invalid tag text: {text:?}"),
            Self::UnknownVr(text) => write!(f, "unknown VR: {text:?}"),
            Self::WrongVr { actual, expected } => {
                write!(f, "VR mismatch: expected {expected}, got {actual}")
            }
            Self::WrongLength { vr, len, unit } => {
                write!(
                    f,
                    "value byte length {len} is not a multiple of {unit} (VR={vr})"
                )
            }
            Self::InvalidUtf8(err) => write!(f, "value bytes are not valid UTF-8: {err}"),
            Self::InvalidNumber(text) => write!(f, "could not parse number: {text:?}"),
            Self::MissingTag(tag) => write!(f, "tag {tag} is missing from the data set"),
            Self::NoValue(tag) => write!(f, "tag {tag} has no value"),
            Self::NotASequence(vr) => write!(f, "VR {vr} is not a sequence"),
        }
    }
}

impl std::error::Error for Error {
    fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
        match self {
            Self::InvalidUtf8(err) => Some(err),
            _ => None,
        }
    }
}