use std::num::TryFromIntError;
use std::string::FromUtf8Error;
pub type Result<T, E = Error> = core::result::Result<T, E>;
#[derive(Debug, thiserror::Error, PartialEq)]
pub enum Error {
#[error("Invalid annotation element tag: {0}")]
InvalidAnnotationElementTag(u8),
#[error("Invalid array type code {0}")]
InvalidArrayTypeCode(u8),
#[error("Invalid attribute length: {0}")]
InvalidAttributeLength(u32),
#[error("Invalid attribute name index: {0}")]
InvalidAttributeNameIndex(u16),
#[error("Invalid base type code {0}")]
InvalidBaseTypeCode(char),
#[error("Invalid constant pool index {0}")]
InvalidConstantPoolIndex(u16),
#[error("Invalid constant pool index type {0}")]
InvalidConstantPoolIndexType(u16),
#[error("Invalid constant tag: {0}")]
InvalidConstantTag(u8),
#[error("Invalid field type code {0}")]
InvalidFieldTypeCode(char),
#[error("Invalid field type descriptor {0}")]
InvalidFieldTypeDescriptor(String),
#[error("Invalid instruction: {0}")]
InvalidInstruction(u8),
#[error("Invalid instruction offset: {0}")]
InvalidInstructionOffset(u32),
#[error("Invalid magic number: {0}")]
InvalidMagicNumber(u32),
#[error("Invalid method descriptor: {0}")]
InvalidMethodDescriptor(String),
#[error("Invalid reference kind: {0}")]
InvalidReferenceKind(u8),
#[error("Invalid stack frame type: {0}")]
InvalidStackFrameType(u8),
#[error("Invalid target type code {0}")]
InvalidTargetTypeCode(u8),
#[error("Invalid verification type tag: {0}")]
InvalidVerificationTypeTag(u8),
#[error("Invalid version: major={major}; minor={minor}")]
InvalidVersion { major: u16, minor: u16 },
#[error("Invalid wide instruction: {0}")]
InvalidWideInstruction(u8),
#[error("IO error: {0}")]
IoError(String),
#[error("Unexpected end of input")]
UnexpectedEof,
#[error("Invalid UTF-8 sequence: {0}")]
FromUtf8Error(String),
#[error(transparent)]
TryFromIntError(#[from] TryFromIntError),
#[error(transparent)]
VerificationError(#[from] crate::verifiers::VerifyError),
}
impl From<FromUtf8Error> for Error {
fn from(error: FromUtf8Error) -> Self {
Error::FromUtf8Error(error.to_string())
}
}
impl From<std::io::Error> for Error {
fn from(error: std::io::Error) -> Self {
Error::IoError(error.to_string())
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn test_from_utf8_error() {
let invalid_utf8: Vec<u8> = vec![0, 159, 146, 150];
let utf8_error = String::from_utf8(invalid_utf8).expect_err("expected FromUtf8Error");
let error = Error::from(utf8_error);
assert_eq!(
error.to_string(),
"Invalid UTF-8 sequence: invalid utf-8 sequence of 1 bytes from index 1"
);
}
#[test]
fn test_io_error() {
let io_error = std::io::Error::new(std::io::ErrorKind::NotFound, "file not found");
let error = Error::from(io_error);
assert_eq!(error.to_string(), "IO error: file not found");
}
}