← Files ISA-L ZipARCHIVED FILE

native/isal/isal.go

1.63 KB · Nov 30, 2026 · 00:22 UTC

↓ Download file

package isal

/*
#include "bridge.h"
#include <stdlib.h>
*/
import "C"

import (
	"errors"
	"fmt"
	"io"
)

const maxInput = int(^uint32(0))

// DeflateRaw compresses one raw DEFLATE stream with Intel ISA-L level 1.
func DeflateRaw(input []byte) ([]byte, error) {
	if len(input) > maxInput {
		return nil, fmt.Errorf("single-file compression is limited to %d bytes", maxInput)
	}
	// ISA-L's stateless interface emits raw DEFLATE, whose worst-case expansion
	// is bounded by the input plus a small block/header allowance.
	capOut := len(input) + len(input)/16383*8 + 64
	if capOut > maxInput {
		return nil, errors.New("compressed output exceeds ISA-L 32-bit buffer limit")
	}
	if capOut < 64 {
		capOut = 64
	}
	out := make([]byte, capOut)
	var src *C.uint8_t
	if len(input) != 0 {
		src = (*C.uint8_t)(&input[0])
	}
	var dst *C.uint8_t
	if len(out) != 0 {
		dst = (*C.uint8_t)(&out[0])
	}
	var written C.uint32_t
	rc := C.isa_zip_deflate_raw(src, C.uint32_t(len(input)), dst, C.uint32_t(len(out)), &written)
	if rc != 0 {
		return nil, fmt.Errorf("ISA-L stateless DEFLATE failed: code %d", int(rc))
	}
	return out[:int(written)], nil
}

type compressor struct {
	dst    io.Writer
	data   []byte
	closed bool
}

func NewCompressor(dst io.Writer) io.WriteCloser { return &compressor{dst: dst} }
func (c *compressor) Write(p []byte) (int, error) {
	if c.closed {
		return 0, errors.New("write after compressor close")
	}
	c.data = append(c.data, p...)
	return len(p), nil
}
func (c *compressor) Close() error {
	if c.closed {
		return nil
	}
	c.closed = true
	packed, err := DeflateRaw(c.data)
	if err != nil {
		return err
	}
	_, err = c.dst.Write(packed)
	return err
}

SHA-256: fddd3bed95be7ef1a2fe2a0798a71926937dee18eef366c02bf4643f2f8d69d1