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
//! Errors produced by crate logic.

use std::{error, fmt, str::Utf8Error};

/// Kind of a [`ReadError`].
#[derive(Debug)]
#[non_exhaustive]
pub enum ReadErrorKind {
    /// Unexpected end of the input.
    UnexpectedEof,
    /// Error parsing
    Utf8(Utf8Error),
}

impl fmt::Display for ReadErrorKind {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::UnexpectedEof => formatter.write_str("reached end of input"),
            Self::Utf8(err) => write!(formatter, "{err}"),
        }
    }
}

impl ReadErrorKind {
    pub(crate) fn with_context(self, context: impl Into<String>) -> ReadError {
        ReadError {
            kind: self,
            context: context.into(),
        }
    }
}

/// Errors that can occur when reading declarations of functions manipulating [`Resource`]s
/// from a WASM module.
///
/// [`Resource`]: crate::Resource
#[derive(Debug)]
pub struct ReadError {
    kind: ReadErrorKind,
    context: String,
}

impl fmt::Display for ReadError {
    fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(formatter, "failed reading {}: {}", self.context, self.kind)
    }
}

impl error::Error for ReadError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        match &self.kind {
            ReadErrorKind::Utf8(err) => Some(err),
            ReadErrorKind::UnexpectedEof => None,
        }
    }
}