use core::fmt;
use crate::WorkLimit;
pub type Result<T> = core::result::Result<T, Error>;
#[derive(Debug, Clone)]
#[non_exhaustive]
pub enum Error {
Codestream(ErrorDetail),
Incomplete(ErrorDetail),
Marker(ErrorDetail),
FileFormat(ErrorDetail),
Unsupported(ErrorDetail),
Limit(LimitDetail),
InvalidOptions(ErrorDetail),
Inconsistent(ErrorDetail),
}
impl fmt::Display for Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Error::Codestream(d) => write!(f, "codestream: {d}"),
Error::Incomplete(d) => write!(f, "incomplete: {d}"),
Error::Marker(d) => write!(f, "marker: {d}"),
Error::FileFormat(d) => write!(f, "file format: {d}"),
Error::Unsupported(d) => write!(f, "unsupported: {d}"),
Error::Limit(d) => write!(f, "limit: {d}"),
Error::InvalidOptions(d) => write!(f, "invalid options: {d}"),
Error::Inconsistent(d) => write!(f, "decoder bug (please report it): {d}"),
}
}
}
impl Error {
pub fn message(&self) -> &str {
match self {
Error::Codestream(d)
| Error::Incomplete(d)
| Error::Marker(d)
| Error::FileFormat(d)
| Error::Unsupported(d)
| Error::InvalidOptions(d)
| Error::Inconsistent(d) => d.message(),
Error::Limit(d) => d.message(),
}
}
}
impl std::error::Error for Error {}
impl Error {
pub(crate) fn codestream(message: impl Into<String>) -> Error {
Error::Codestream(ErrorDetail::new(message))
}
pub(crate) fn incomplete(message: impl Into<String>) -> Error {
Error::Incomplete(ErrorDetail::new(message))
}
pub(crate) fn marker(message: impl Into<String>) -> Error {
Error::Marker(ErrorDetail::new(message))
}
pub(crate) fn file_format(message: impl Into<String>) -> Error {
Error::FileFormat(ErrorDetail::new(message))
}
pub(crate) fn unsupported(message: impl Into<String>) -> Error {
Error::Unsupported(ErrorDetail::new(message))
}
pub(crate) fn invalid_options(message: impl Into<String>) -> Error {
Error::InvalidOptions(ErrorDetail::new(message))
}
pub(crate) fn inconsistent(message: impl Into<String>) -> Error {
Error::Inconsistent(ErrorDetail::new(message))
}
pub(crate) fn limit_fixed(kind: LimitKind, message: impl Into<String>) -> Error {
debug_assert!(!kind.is_adjustable(), "{kind:?} has an option");
Error::limit(kind, None, message.into())
}
pub(crate) fn limit_retry(
kind: LimitKind,
retry_with: WorkLimit,
message: impl Into<String>,
) -> Error {
debug_assert!(kind.is_adjustable(), "{kind:?} has no option");
Error::limit(kind, Some(retry_with), message.into())
}
pub(crate) fn limit_unhinted(kind: LimitKind, message: impl Into<String>) -> Error {
debug_assert!(kind.is_adjustable(), "{kind:?} has no option");
Error::limit(kind, None, message.into())
}
fn limit(kind: LimitKind, retry_with: Option<WorkLimit>, message: String) -> Error {
debug_assert!(
names_its_data(kind, retry_with.as_ref(), &message),
"{kind:?}, {retry_with:?}: {message}"
);
Error::Limit(LimitDetail {
kind,
retry_with,
message,
})
}
}
fn names_its_data(kind: LimitKind, retry_with: Option<&WorkLimit>, message: &str) -> bool {
let option = match kind {
LimitKind::Samples => Some("`DecodeOptions::sample_limit`"),
LimitKind::PacketWork => Some("`DecodeOptions::packet_work_limit`"),
LimitKind::CodeBlockWork => Some("`DecodeOptions::code_block_work_limit`"),
_ => None,
};
let retry = match retry_with {
Some(WorkLimit::Raised(n)) => message.contains(&format!("`WorkLimit::Raised({n})`")),
Some(WorkLimit::Unlimited) => message.contains("only `WorkLimit::Unlimited`"),
Some(_) => false,
None => !message.contains("`WorkLimit::Raised("),
};
retry
&& match option {
Some(option) => retry_with.is_none() || message.contains(option),
None => retry_with.is_none() && !message.contains("DecodeOptions::"),
}
}
#[derive(Clone)]
#[non_exhaustive]
pub struct ErrorDetail {
message: String,
}
impl ErrorDetail {
fn new(message: impl Into<String>) -> Self {
ErrorDetail {
message: message.into(),
}
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Debug for ErrorDetail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(&self.message, f)
}
}
impl fmt::Display for ErrorDetail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct LimitDetail {
kind: LimitKind,
retry_with: Option<WorkLimit>,
message: String,
}
impl LimitDetail {
pub fn kind(&self) -> LimitKind {
self.kind
}
pub fn retry_with(&self) -> Option<WorkLimit> {
self.retry_with.clone()
}
pub fn message(&self) -> &str {
&self.message
}
}
impl fmt::Display for LimitDetail {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum LimitKind {
Samples,
PacketWork,
CodeBlockWork,
AddressSpace,
TileCodeBlocks,
TilePrecincts,
PocVolumes,
BitPlanes,
}
impl LimitKind {
pub fn is_adjustable(self) -> bool {
matches!(
self,
LimitKind::Samples | LimitKind::PacketWork | LimitKind::CodeBlockWork
)
}
}
#[cfg(test)]
pub(crate) fn keyed<T>(result: Result<T>) -> core::result::Result<T, String> {
result.map_err(|error| format!("{error:?}"))
}
#[cfg(test)]
pub(crate) fn is_fixed_limit(error: &Error, kind: LimitKind) -> bool {
matches!(error, Error::Limit(limit) if limit.kind() == kind && limit.retry_with().is_none())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn debug_shows_the_variant_the_data_and_the_message() {
assert_eq!(
format!("{:?}", crate::decode(b"hello").unwrap_err()),
"Codestream(\"does not start with the `SOC` marker\")"
);
let limit = Error::limit_fixed(LimitKind::BitPlanes, "31 bit-planes");
assert_eq!(
format!("{limit:?}"),
"Limit(LimitDetail { kind: BitPlanes, retry_with: None, message: \"31 bit-planes\" })"
);
}
#[test]
fn message_drops_the_prefix() {
let error = Error::marker("reserved");
assert_eq!(error.to_string(), "marker: reserved");
assert_eq!(error.message(), "reserved");
let limit = Error::limit_fixed(LimitKind::PocVolumes, "33 volumes");
assert_eq!(limit.message(), "33 volumes");
}
#[test]
fn the_three_options_are_the_adjustable_kinds() {
use LimitKind::*;
for kind in [Samples, PacketWork, CodeBlockWork] {
assert!(kind.is_adjustable(), "{kind:?}");
}
for kind in [
AddressSpace,
TileCodeBlocks,
TilePrecincts,
PocVolumes,
BitPlanes,
] {
assert!(!kind.is_adjustable(), "{kind:?}");
}
}
}