Skip to main content

tf2_sku/
error.rs

1//! Errors.
2
3use std::fmt;
4use std::num::{IntErrorKind, ParseIntError};
5
6/// An error when parsing from a string.
7#[derive(Debug, Clone, PartialEq, Eq)]
8pub enum ParseError {
9    /// An integer failed to parse.
10    ParseInt {
11        /// The key of the attribute.
12        key: &'static str,
13        /// The error from parsing the integer.
14        error: ParseIntError,
15    },
16    /// The SKU format is not valid. Must begin with a defindex and a quality e.g. "5021;6".
17    InvalidFormat,
18    /// An attribute value is not valid.
19    InvalidValue {
20        /// The key of the attribute.
21        key: &'static str,
22        /// The value attempted to be converted.
23        number: u32,
24    },
25}
26
27impl fmt::Display for ParseError {
28    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29        match self {
30            ParseError::ParseInt {
31                key,
32                error ,
33            } => match *error.kind() {
34                IntErrorKind::Empty => write!(f, "Value for {key} in SKU is empty."),
35                IntErrorKind::InvalidDigit => write!(f, "Value for {key} in SKU contains invalid digit."),
36                IntErrorKind::PosOverflow => write!(f, "Value for {key} in SKU overflows integer bounds."),
37                IntErrorKind::NegOverflow => write!(f, "Value for {key} in SKU underflows integer bounds."),
38                // shouldn't occur
39                IntErrorKind::Zero => write!(f, "Value for {key} in SKU zero for non-zero type."),
40                _ => write!(f, "Value for {key} in SKU could not be parsed: {error}"),
41            },
42            ParseError::InvalidFormat => write!(f, "Invalid SKU format. Must begin with a defindex followed by a quality e.g. \"5021;6\""),
43            ParseError::InvalidValue {
44                key,
45                number,
46            } => write!(f, "Unknown {key}: {number}"),
47        }
48    }
49}
50
51impl std::error::Error for ParseError {}