cloudflare_zlib/
lib.rs

1use std::fmt;
2
3pub use cloudflare_zlib_sys::{Z_NO_COMPRESSION, Z_BEST_SPEED,
4    Z_BEST_COMPRESSION, Z_DEFAULT_COMPRESSION, Z_FILTERED,
5    Z_HUFFMAN_ONLY, Z_RLE, Z_FIXED, Z_DEFAULT_STRATEGY};
6
7mod def;
8pub use def::*;
9mod inf;
10pub use inf::*;
11use std::os::raw::c_int;
12
13/// If `false`, this crate won't work
14#[inline]
15#[must_use]
16pub fn is_supported() -> bool {
17    #[cfg(target_arch = "x86_64")]
18    {
19        if is_x86_feature_detected!("sse4.2") && is_x86_feature_detected!("pclmulqdq") {
20            return true;
21        }
22    }
23
24    #[cfg(target_arch = "aarch64")]
25    {
26        // As of Rust 1.60 is_aarch64_feature_detected is poorly implemented on non-Linux,
27        // and Apple only ships modern ARM CPUs:
28        if cfg!(feature = "arm-always") || cfg!(target_vendor = "apple") {
29            return true;
30        }
31        use std::arch::is_aarch64_feature_detected;
32        if is_aarch64_feature_detected!("neon") && is_aarch64_feature_detected!("crc") {
33            return true;
34        }
35    }
36    false
37}
38
39#[derive(Debug)]
40/// See zlib's documentation for exact meaning of these errors.
41pub enum ZError {
42    /// `Z_STREAM_END`
43    StreamEnd,
44    /// `Z_NEED_DICT`
45    NeedDict,
46    /// `Z_ERRNO`
47    Errno,
48    /// `Z_STREAM_ERROR`
49    StreamError,
50    /// `Z_DATA_ERROR`
51    DataError,
52    /// `Z_MEM_ERROR`
53    MemError,
54    /// `Z_BUF_ERROR`
55    BufError,
56    /// `Z_VERSION_ERROR`
57    VersionError,
58    /// When `compress_with_limit` was used, and limit was exceeded. Contains size compressed so far.
59    DeflatedDataTooLarge(usize),
60    /// Unknown error. Shouldn't happen.
61    OtherError(c_int),
62    /// It won't work on this computer
63    ///
64    /// Only recent 64-bit Intel and ARM CPUs are supported.
65    IncompatibleCPU,
66}
67
68impl ZError {
69    #[inline]
70    fn new(code: c_int) -> Self {
71        match code {
72            1 => ZError::StreamEnd,
73            2 => ZError::NeedDict,
74            -1 => ZError::Errno,
75            -2 => ZError::StreamError,
76            -3 => ZError::DataError,
77            -4 => ZError::MemError,
78            -5 => ZError::BufError,
79            -6 => ZError::VersionError,
80            other => ZError::OtherError(other),
81        }
82    }
83}
84
85impl fmt::Display for ZError {
86    #[cold]
87    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
88        <Self as fmt::Debug>::fmt(self, f)
89    }
90}
91
92impl std::error::Error for ZError {
93}