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
57
58
59
60
61
62
//! Errors that occur during writing

use std::sync::Arc;

use crate::{graph::Graph, validate::ValidationReport};

/// A packing could not be found that satisfied all offsets
#[derive(Clone, Debug)]
pub struct PackingError {
    pub(crate) graph: Arc<Graph>,
}

/// An error occured while writing this table
#[derive(Debug)]
pub enum Error {
    ValidationFailed(ValidationReport),
    PackingFailed(PackingError),
}

impl PackingError {
    /// Write a graphviz file representing the failed packing to the provided path.
    ///
    /// Has the same semantics as [`std::fs::write`].
    #[cfg(feature = "dot2")]
    pub fn write_graph_viz(&self, path: impl AsRef<std::path::Path>) -> std::io::Result<()> {
        self.graph.write_graph_viz(path)
    }
}

impl std::fmt::Display for Error {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Error::ValidationFailed(report) => report.fmt(f),
            Error::PackingFailed(error) => error.fmt(f),
        }
    }
}

impl std::fmt::Display for PackingError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "Table packing failed with {} overflows",
            self.graph.find_overflows().len()
        )
    }
}

impl std::error::Error for PackingError {}
impl std::error::Error for Error {}

#[cfg(test)]
mod tests {
    use super::*;

    /// Some users, notably fontmake-rs, like Send errors.
    #[test]
    fn assert_compiler_error_is_send() {
        fn send_me_baby<T: Send>() {}
        send_me_baby::<Error>();
    }
}