Skip to content

The native runtime for three.js: three.js, down to the metal. 45× smaller than Electron, on a Sony PS3, and path-traced at 60 fps on ray-tracing GPUs.

6.7 KB
Raw Blame
//! Content-Encoding decoding (gzip, deflate, br): macOS uses the system Compression framework
//! (`libcompression`), other platforms use pure-Rust `flate2` and `brotli`.

#[cfg(target_os = "macos")]
mod imp {
    use std::ffi::c_void;

    const ALG_ZLIB: i32 = 0x205; // raw DEFLATE (RFC 1951)
    const ALG_BROTLI: i32 = 0xB02; // macOS 12+
    const OP_DECODE: i32 = 1;
    const STATUS_OK: i32 = 0;
    const STATUS_END: i32 = 1;
    const FLAG_FINALIZE: i32 = 1;

    #[repr(C)]
    struct CompressionStream {
        dst_ptr: *mut u8,
        dst_size: usize,
        src_ptr: *const u8,
        src_size: usize,
        state: *mut c_void,
    }

    #[link(name = "compression")]
    unsafe extern "C" {
        fn compression_stream_init(s: *mut CompressionStream, op: i32, alg: i32) -> i32;
        fn compression_stream_process(s: *mut CompressionStream, flags: i32) -> i32;
        fn compression_stream_destroy(s: *mut CompressionStream) -> i32;
    }

    fn inflate(alg: i32, input: &[u8]) -> Result<(Vec<u8>, usize), String> {
        let mut s = CompressionStream { dst_ptr: std::ptr::null_mut(), dst_size: 0, src_ptr: std::ptr::null(), src_size: 0, state: std::ptr::null_mut() };
        if unsafe { compression_stream_init(&mut s, OP_DECODE, alg) } != STATUS_OK {
            return Err("decoder unavailable".into());
        }
        let mut out: Vec<u8> = Vec::with_capacity((input.len() * 4).clamp(4096, 64 << 20));
        s.src_ptr = input.as_ptr();
        s.src_size = input.len();
        let result = loop {
            if out.capacity() - out.len() < 4096 {
                out.reserve(out.capacity().max(4096));
            }
            let spare = out.capacity() - out.len();
            s.dst_ptr = unsafe { out.as_mut_ptr().add(out.len()) };
            s.dst_size = spare;
            let st = unsafe { compression_stream_process(&mut s, FLAG_FINALIZE) };
            let produced = spare - s.dst_size;
            unsafe { out.set_len(out.len() + produced) };
            match st {
                STATUS_END => break Ok(input.len() - s.src_size),
                STATUS_OK if produced == 0 && s.src_size == 0 => break Err("truncated stream".to_string()),
                STATUS_OK => {}
                _ => break Err("corrupt stream".to_string()),
            }
        };
        unsafe { compression_stream_destroy(&mut s) };
        result.map(|used| (out, used))
    }

    pub fn gunzip(mut data: &[u8]) -> Result<Vec<u8>, String> {
        let mut out = Vec::new();
        loop {
            if data.len() < 18 || data[0] != 0x1f || data[1] != 0x8b || data[2] != 8 {
                return if out.is_empty() { Err("not gzip".into()) } else { Ok(out) };
            }
            let flags = data[3];
            let mut i = 10;
            if flags & 4 != 0 {
                let n = *data.get(i).ok_or("short header")? as usize | (*data.get(i + 1).ok_or("short header")? as usize) << 8;
                i += 2 + n;
            }
            for bit in [8u8, 16] {
                if flags & bit != 0 {
                    while *data.get(i).ok_or("short header")? != 0 {
                        i += 1;
                    }
                    i += 1;
                }
            }
            if flags & 2 != 0 {
                i += 2;
            }
            let body = data.get(i..).ok_or("short header")?;
            let (mut part, used) = inflate(ALG_ZLIB, body)?;
            out.append(&mut part);
            data = body.get(used + 8..).unwrap_or(&[]);
            if data.is_empty() {
                return Ok(out);
            }
        }
    }

    pub fn inflate_http_deflate(data: &[u8]) -> Result<Vec<u8>, String> {
        let zlib = data.len() >= 2 && data[0] & 0x0f == 8 && (u16::from(data[0]) << 8 | u16::from(data[1])) % 31 == 0;
        if zlib {
            if data[1] & 0x20 != 0 {
                return Err("preset dictionary".into());
            }
            if let Ok((out, _)) = inflate(ALG_ZLIB, &data[2..]) {
                return Ok(out);
            }
        }
        inflate(ALG_ZLIB, data).map(|r| r.0)
    }

    pub fn inflate_brotli(data: &[u8]) -> Result<Vec<u8>, String> {
        inflate(ALG_BROTLI, data).map(|r| r.0)
    }
}

#[cfg(not(target_os = "macos"))]
mod imp {
    use std::io::Read;

    pub fn gunzip(data: &[u8]) -> Result<Vec<u8>, String> {
        let mut dec = flate2::read::MultiGzDecoder::new(data);
        let mut out = Vec::new();
        dec.read_to_end(&mut out).map_err(|e| format!("gzip: {e}"))?;
        Ok(out)
    }

    pub fn inflate_http_deflate(data: &[u8]) -> Result<Vec<u8>, String> {
        let mut z = flate2::read::ZlibDecoder::new(data);
        let mut out = Vec::new();
        if z.read_to_end(&mut out).is_ok() {
            return Ok(out);
        }
        out.clear();
        let mut raw = flate2::read::DeflateDecoder::new(data);
        raw.read_to_end(&mut out).map_err(|e| format!("deflate: {e}"))?;
        Ok(out)
    }

    pub fn inflate_brotli(data: &[u8]) -> Result<Vec<u8>, String> {
        let mut dec = brotli::Decompressor::new(data, 4096);
        let mut out = Vec::new();
        dec.read_to_end(&mut out).map_err(|e| format!("brotli: {e}"))?;
        Ok(out)
    }
}

/// Undo a `Content-Encoding` header value (codings apply in order, so they are undone in reverse).
/// Unknown codings leave the body as it is, like Chromium.
pub fn decode(encoding: &str, mut body: Vec<u8>) -> Result<Vec<u8>, String> {
    for coding in encoding.split(',').rev().map(|c| c.trim().to_ascii_lowercase()) {
        if body.is_empty() {
            break;
        }
        body = match coding.as_str() {
            "gzip" | "x-gzip" => imp::gunzip(&body)?,
            "deflate" => imp::inflate_http_deflate(&body)?,
            "br" => imp::inflate_brotli(&body)?,
            _ => body,
        };
    }
    Ok(body)
}

#[cfg(test)]
mod tests {
    use super::*;
    #[test]
    fn gzip_and_deflate() {
        // zlib.gzipSync('hello hello hello')
        let gz = [0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x13, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x90, 0x00, 0x80, 0x88, 0xf9, 0xe5, 0x11, 0x00, 0x00, 0x00];
        assert_eq!(decode("gzip", gz.to_vec()).unwrap(), b"hello hello hello");
        // zlib.deflateSync('hello hello hello')
        let z = [0x78, 0x9c, 0xcb, 0x48, 0xcd, 0xc9, 0xc9, 0x57, 0xc8, 0x40, 0x90, 0x00, 0x3a, 0x2e, 0x06, 0x7d];
        assert_eq!(decode("deflate", z.to_vec()).unwrap(), b"hello hello hello");
        // zlib.brotliCompressSync('hello hello hello')
        let br = [0x1b, 0x10, 0x00, 0xf8, 0x8d, 0x94, 0x6e, 0xde, 0x44, 0x55, 0x86, 0x96, 0x6c, 0x20, 0x6f, 0x01, 0x4f, 0x1c, 0x60, 0x1c];
        assert_eq!(decode("br", br.to_vec()).unwrap(), b"hello hello hello");
        assert!(decode("gzip", b"garbage!garbage!garbage!".to_vec()).is_err());
    }
}