utopia_compression/error.rs
1//! The error type shared by every algorithm.
2
3/// Why compressing, decompressing or configuring an algorithm failed.
4///
5/// PHP: one variant per way `utopia-php/compression` fails (see
6/// [`Error::php_class`]).
7#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
8pub enum Error {
9 /// An argument out of range, such as a compression level.
10 ///
11 /// PHP: `\InvalidArgumentException`, thrown by `setLevel()`.
12 #[error("{0}")]
13 InvalidArgument(String),
14 /// The codec refused the input: data that is not a valid stream of the
15 /// algorithm, or a level the codec does not accept. The message is the
16 /// warning PHP's extension emits, such as `gzinflate(): data error`.
17 ///
18 /// PHP: no exception. The extension emits an `E_WARNING` with this
19 /// message and returns `false`, which the method's `string` return type
20 /// coerces to an empty string.
21 #[error("{0}")]
22 Codec(String),
23 /// The algorithm was built without the cargo feature that provides it.
24 /// The message names the missing function, such as
25 /// `Call to undefined function Utopia\Compression\Algorithms\xzencode()`.
26 ///
27 /// PHP: `\Error`, thrown when the extension is not loaded.
28 #[error("{0}")]
29 Unsupported(String),
30}
31
32impl Error {
33 /// The name of the PHP class this error matches, such as
34 /// `InvalidArgumentException`.
35 ///
36 /// PHP: the class of the exception `utopia-php/compression` throws in the
37 /// same case. [`Error::Codec`] is a warning in PHP, not an exception; it
38 /// reports `ErrorException`, the class an error handler that turns
39 /// warnings into exceptions throws.
40 pub fn php_class(&self) -> &'static str {
41 match self {
42 Error::InvalidArgument(_) => "InvalidArgumentException",
43 Error::Codec(_) => "ErrorException",
44 Error::Unsupported(_) => "Error",
45 }
46 }
47
48 /// The error of an algorithm whose feature is off: PHP's message for a
49 /// call to the missing extension function `function`.
50 #[allow(dead_code)]
51 pub(crate) fn undefined(function: &str) -> Self {
52 Error::Unsupported(format!("Call to undefined function Utopia\\Compression\\Algorithms\\{function}()"))
53 }
54}