use crate::types::Version;
pub type Result<T, E = Error> = std::result::Result<T, E>;
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum Error {
#[error("I/O failed")]
Io(#[from] std::io::Error),
#[error("not an mbook file")]
NotMbook,
#[error("format version {0} is newer than this library supports")]
UnsupportedVersion(Version),
#[error("the container or a frame is damaged")]
Container(#[source] Box<dyn std::error::Error + Send + Sync>),
#[error("resource {resource} is malformed: {reason}")]
Malformed {
resource: u32,
reason: &'static str,
},
#[error("limit exceeded: {0}")]
Limit(&'static str),
#[error("resource {0} is not a chapter or picture of this book")]
NoSuchResource(u32),
#[error("nothing in the book has the path {0:?}")]
NoSuchPath(String),
#[error("index {index} is out of range for {len} chapters")]
IndexOutOfRange {
index: usize,
len: usize,
},
#[error("invalid path {path:?}")]
InvalidPath {
path: String,
#[source]
reason: PathError,
},
#[error("the path {0:?} is already used")]
DuplicatePath(String),
#[error("invalid chapter text")]
InvalidText(#[from] TextError),
#[error("invalid picture: {0}")]
InvalidPicture(&'static str),
#[error("invalid metadata")]
InvalidMeta(#[from] MetaError),
#[error("the destination leads nowhere")]
Unresolved(#[from] ResolveError),
#[error("invalid landmarks")]
InvalidLandmark(#[from] LandmarkError),
#[error("the book cannot be written")]
Invalid(#[from] Problems),
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum PathError {
#[error("the path is empty")]
Empty,
#[error("a segment is empty")]
EmptySegment,
#[error("a segment is `.` or `..`")]
DotSegment,
#[error("the path contains a backslash")]
Backslash,
#[error("the path contains a control character")]
ControlCharacter,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[error("control character U+{:04X} at byte {offset}", u32::from(*.character))]
#[non_exhaustive]
pub struct TextError {
pub offset: usize,
pub character: char,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum MetaError {
#[error("{0:?} is not a valid key")]
InvalidKey(String),
#[error("the key {0:?} is required")]
Required(String),
#[error("the key {0:?} holds one value")]
SingleValued(String),
#[error("the title is empty")]
EmptyTitle,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum LandmarkError {
#[error("{0:?} is not a valid kind of landmark")]
InvalidKind(String),
#[error("a book has one start")]
RepeatedStart,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ResolveError {
#[error("the scheme is not allowed")]
ForbiddenScheme,
#[error("the destination is malformed")]
Malformed,
#[error("the destination leaves the book")]
OutsideRoot,
#[error("nothing in the book has that path")]
NotFound,
#[error("the chapter has no such anchor")]
UnknownAnchor,
#[error("a picture cannot have a fragment")]
FragmentOnPicture,
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("the book has {} problem(s)", .0.len())]
pub struct Problems(Vec<Problem>);
impl Problems {
#[cfg(feature = "write")]
pub(crate) fn none_or(problems: Vec<Problem>) -> Result<(), Self> {
if problems.is_empty() {
Ok(())
} else {
Err(Self(problems))
}
}
pub fn iter(&self) -> std::slice::Iter<'_, Problem> {
self.0.iter()
}
#[must_use]
pub fn len(&self) -> usize {
self.0.len()
}
#[must_use]
pub fn is_empty(&self) -> bool {
self.0.is_empty()
}
}
impl<'a> IntoIterator for &'a Problems {
type Item = &'a Problem;
type IntoIter = std::slice::Iter<'a, Problem>;
fn into_iter(self) -> Self::IntoIter {
self.iter()
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[error("{}{kind}", location(.path.as_deref(), *.offset))]
pub struct Problem {
pub path: Option<String>,
pub offset: Option<u32>,
pub kind: ProblemKind,
}
fn location(path: Option<&str>, offset: Option<u32>) -> String {
match (path, offset) {
(Some(path), Some(offset)) => format!("{path}, byte {offset}: "),
(Some(path), None) => format!("{path}: "),
(None, _) => String::new(),
}
}
#[derive(Clone, Debug, PartialEq, Eq, thiserror::Error)]
#[non_exhaustive]
pub enum ProblemKind {
#[error("the link to {0:?} leads nowhere")]
UnresolvedLink(String),
#[error("the picture {0:?} is not in the book")]
UnresolvedPicture(String),
#[error("the destination {0:?} uses a scheme that is not allowed")]
ForbiddenScheme(String),
#[error("raw HTML is not allowed")]
RawHtml,
#[error("the cover is not a picture of the book")]
MissingCover,
#[error("the character U+{:04X} is not allowed", u32::from(*.0))]
ForbiddenCharacter(char),
#[error("the contents item {0:?} leads nowhere")]
DanglingTocItem(String),
#[error("the landmark {0:?} leads nowhere")]
DanglingLandmark(String),
#[error("a contents item has no title")]
EmptyTocTitle,
#[error("the level of the contents item {0:?} does not continue the tree")]
TocLevel(String),
#[error("the contents item {0:?} is out of reading order")]
TocOrder(String),
}
#[cfg(test)]
mod tests {
use super::{
Error, LandmarkError, MetaError, PathError, Problem, ProblemKind, Problems, ResolveError,
TextError,
};
use crate::types::Version;
use std::error::Error as _;
fn problem(path: Option<&str>, offset: Option<u32>) -> Problem {
Problem {
path: path.map(str::to_owned),
offset,
kind: ProblemKind::RawHtml,
}
}
#[test]
fn io_error_keeps_its_source() {
let error = Error::from(std::io::Error::other("disk on fire"));
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some("disk on fire"));
}
#[test]
fn unsupported_version_names_the_version() {
let error = Error::UnsupportedVersion(Version { major: 2, minor: 1 });
assert_eq!(
error.to_string(),
"format version 2.1 is newer than this library supports"
);
}
#[test]
fn container_error_keeps_its_source() {
let error = Error::Container("bad checksum".into());
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some("bad checksum"));
}
#[test]
fn malformed_names_the_resource_and_the_rule() {
let error = Error::Malformed {
resource: 3,
reason: "levels skip",
};
assert_eq!(error.to_string(), "resource 3 is malformed: levels skip");
}
#[test]
fn invalid_path_quotes_the_path() {
let error = Error::InvalidPath {
path: "a//b".into(),
reason: PathError::EmptySegment,
};
assert_eq!(error.to_string(), r#"invalid path "a//b""#);
}
#[test]
fn invalid_path_keeps_the_reason_as_its_source() {
let error = Error::InvalidPath {
path: "a//b".into(),
reason: PathError::EmptySegment,
};
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some("a segment is empty"));
}
#[test]
fn index_out_of_range_names_both_numbers() {
let error = Error::IndexOutOfRange { index: 4, len: 3 };
assert_eq!(error.to_string(), "index 4 is out of range for 3 chapters");
}
#[test]
fn text_error_converts_into_invalid_text() {
let text = TextError {
offset: 7,
character: '\u{1b}',
};
assert!(matches!(Error::from(text), Error::InvalidText(inner) if inner == text));
}
#[test]
fn text_error_names_the_character_and_the_offset() {
let text = TextError {
offset: 7,
character: '\u{1b}',
};
assert_eq!(text.to_string(), "control character U+001B at byte 7");
}
#[test]
fn meta_error_is_the_source_of_invalid_meta() {
let error = Error::from(MetaError::Required("id".into()));
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some(r#"the key "id" is required"#));
}
#[test]
fn resolve_error_is_the_source_of_unresolved() {
let error = Error::from(ResolveError::UnknownAnchor);
let source = error.source().map(ToString::to_string);
assert_eq!(
(error.to_string().as_str(), source.as_deref()),
(
"the destination leads nowhere",
Some("the chapter has no such anchor")
)
);
}
#[test]
fn landmark_error_is_the_source_of_invalid_landmark() {
let error = Error::from(LandmarkError::InvalidKind("The Index".into()));
let source = error.source().map(ToString::to_string);
assert_eq!(
(error.to_string().as_str(), source.as_deref()),
(
"invalid landmarks",
Some(r#""The Index" is not a valid kind of landmark"#)
)
);
assert_eq!(
LandmarkError::RepeatedStart.to_string(),
"a book has one start"
);
}
#[test]
fn a_dangling_landmark_names_its_kind() {
let kind = ProblemKind::DanglingLandmark("index".into());
assert_eq!(kind.to_string(), r#"the landmark "index" leads nowhere"#);
}
#[test]
fn resolve_error_has_a_message() {
assert_eq!(
ResolveError::UnknownAnchor.to_string(),
"the chapter has no such anchor"
);
}
#[test]
fn problem_with_a_place_names_the_chapter_and_the_byte() {
let text = problem(Some("ch01.md"), Some(130)).to_string();
assert_eq!(text, "ch01.md, byte 130: raw HTML is not allowed");
}
#[test]
fn problem_in_a_chapter_names_the_chapter() {
let text = problem(Some("ch01.md"), None).to_string();
assert_eq!(text, "ch01.md: raw HTML is not allowed");
}
#[test]
fn problem_of_the_whole_book_has_no_prefix() {
let whole = Problem {
path: None,
offset: None,
kind: ProblemKind::MissingCover,
};
assert_eq!(whole.to_string(), "the cover is not a picture of the book");
}
#[test]
fn problem_kind_quotes_the_destination() {
let kind = ProblemKind::UnresolvedLink("ch09.md".into());
assert_eq!(kind.to_string(), r#"the link to "ch09.md" leads nowhere"#);
}
#[test]
fn problems_count_what_they_hold() {
let problems = Problems(vec![problem(None, None), problem(None, None)]);
assert_eq!((problems.len(), problems.is_empty()), (2, false));
}
#[test]
fn problems_iterate_in_order() {
let problems = Problems(vec![
problem(Some("a.md"), None),
problem(Some("b.md"), None),
]);
let paths: Vec<_> = (&problems)
.into_iter()
.filter_map(|p| p.path.as_deref())
.collect();
assert_eq!(paths, ["a.md", "b.md"]);
}
#[test]
fn problems_become_an_invalid_book_error() {
let error = Error::from(Problems(vec![problem(None, None)]));
let source = error.source().map(ToString::to_string);
assert_eq!(source.as_deref(), Some("the book has 1 problem(s)"));
}
}