zxc

package module
v1.0.3 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 28, 2026 License: BSD-3-Clause Imports: 11 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

ZXC Go Bindings

High-performance Go bindings for the ZXC asymmetric compressor, optimised for fast decompression.
Designed for Write Once, Read Many workloads like ML datasets, game assets, and caches.

Features

  • Blazing fast decompression - ZXC is specifically optimised for read-heavy workloads.
  • Buffer API - compress/decompress []byte slices in a single call.
  • Streaming API - multi-threaded file compression/decompression.
  • Functional options - clean, composable configuration (WithLevel, WithChecksum, WithThreads).
  • Typed errors - sentinel error values for every ZXC error code.

Installation

go get github.com/hellobertrand/zxc/bindings/go

The module carries the C sources, so all it needs is cgo and a C compiler. On Windows and 32-bit ARM it compiles the baseline code only, without AVX2 or NEON paths chosen at run time.

Versioning

Releases are tagged bindings/go/vX.Y.Z: go get picks the latest, @vX.Y.Z pins one.

Only these tags carry the C core, which the repository keeps above the module directory. A branch or a commit (@main, a pseudo-version) does not build.

Versions up to v0.15.0 are published as github.com/hellobertrand/zxc/wrappers/go.

Quick Start

package main

import (
    "fmt"
    "log"

    zxc "github.com/hellobertrand/zxc/bindings/go"
)

func main() {
    data := []byte("Hello, ZXC from Go!")

    // Compress
    compressed, err := zxc.Compress(data, zxc.WithLevel(zxc.LevelDefault))
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Compressed %d => %d bytes\n", len(data), len(compressed))

    // Decompress
    original, err := zxc.Decompress(compressed)
    if err != nil {
        log.Fatal(err)
    }
    fmt.Printf("Decompressed: %s\n", original)
}

CompressTo writes into a caller-supplied buffer (size it with CompressBound). Both Compress and CompressTo accept empty input and emit a minimal valid frame. Pass zxc.WithSeekable(true) to append a seek table for random access via zxc.OpenBytes. Decompress allocates the size the archive's footer declares: on untrusted input, cap it with zxc.WithMaxOutputSize(n).

Compression writes no checksums unless zxc.WithChecksum(true). Decompression verifies those an archive carries, on every path; zxc.WithChecksum(false) opts out (SetChecksum(false) on a Seekable). The block API is the exception: a bare block does not say whether it has a checksum, so it is off by default and CompressBlock and DecompressBlock must agree.

Streaming Files

// Multi-threaded file compression
n, err := zxc.CompressFile("input.bin", "output.zxc",
    zxc.WithLevel(zxc.LevelCompact),
    zxc.WithThreads(4),
    zxc.WithChecksum(true),
)

// Decompress, verifying the checksums
n, err = zxc.DecompressFile("output.zxc", "restored.bin")

Testing

cd zxc/bindings/go
go test -v -count=1 ./...

Benchmarks

go test -bench=. -benchmem ./...

License

BSD-3-Clause - see LICENSE.

Documentation

Overview

Package zxc provides Go bindings to the ZXC high-performance lossless compression library.

ZXC is optimised for fast decompression speed: it is designed for "Write Once, Read Many" workloads such as ML datasets, game assets, firmware images and caches.

Quick Start

compressed, err := zxc.Compress(data)
if err != nil { log.Fatal(err) }

original, err := zxc.Decompress(compressed)
if err != nil { log.Fatal(err) }

Streaming (file-based)

n, err := zxc.CompressFile("input.bin", "output.zxc")
n, err  = zxc.DecompressFile("output.zxc", "restored.bin")

Index

Constants

View Source
const (
	// VersionMajor is the major version of the underlying C library.
	VersionMajor = C.ZXC_VERSION_MAJOR

	// VersionMinor is the minor version of the underlying C library.
	VersionMinor = C.ZXC_VERSION_MINOR

	// VersionPatch is the patch version of the underlying C library.
	VersionPatch = C.ZXC_VERSION_PATCH
)
View Source
const DictSizeMax = int(C.ZXC_DICT_SIZE_MAX)

DictSizeMax is the maximum dictionary content size in bytes (65535).

View Source
const HufTableSize = int(C.ZXC_HUF_TABLE_SIZE)

HufTableSize is the size in bytes of the shared literal Huffman table carried by a .zxd file (packed 4-bit code lengths for 256 symbols).

Variables

View Source
var (
	ErrMemory       = &Error{Code: int(C.ZXC_ERROR_MEMORY), Name: "memory allocation failed"}
	ErrDstTooSmall  = &Error{Code: int(C.ZXC_ERROR_DST_TOO_SMALL), Name: "destination buffer too small"}
	ErrSrcTooSmall  = &Error{Code: int(C.ZXC_ERROR_SRC_TOO_SMALL), Name: "source buffer too small"}
	ErrBadMagic     = &Error{Code: int(C.ZXC_ERROR_BAD_MAGIC), Name: "invalid magic word"}
	ErrBadVersion   = &Error{Code: int(C.ZXC_ERROR_BAD_VERSION), Name: "unsupported format version"}
	ErrBadHeader    = &Error{Code: int(C.ZXC_ERROR_BAD_HEADER), Name: "corrupted header"}
	ErrBadChecksum  = &Error{Code: int(C.ZXC_ERROR_BAD_CHECKSUM), Name: "checksum verification failed"}
	ErrCorruptData  = &Error{Code: int(C.ZXC_ERROR_CORRUPT_DATA), Name: "corrupted compressed data"}
	ErrBadOffset    = &Error{Code: int(C.ZXC_ERROR_BAD_OFFSET), Name: "invalid match offset"}
	ErrOverflow     = &Error{Code: int(C.ZXC_ERROR_OVERFLOW), Name: "buffer overflow detected"}
	ErrIO           = &Error{Code: int(C.ZXC_ERROR_IO), Name: "I/O error"}
	ErrNullInput    = &Error{Code: int(C.ZXC_ERROR_NULL_INPUT), Name: "null input pointer"}
	ErrBadBlockType = &Error{Code: int(C.ZXC_ERROR_BAD_BLOCK_TYPE), Name: "unknown block type"}
	ErrBadBlockSize = &Error{Code: int(C.ZXC_ERROR_BAD_BLOCK_SIZE), Name: "invalid block size"}
	ErrDictRequired = &Error{Code: int(C.ZXC_ERROR_DICT_REQUIRED), Name: "archive requires a dictionary"}
	ErrDictMismatch = &Error{Code: int(C.ZXC_ERROR_DICT_MISMATCH), Name: "dictionary ID mismatch"}
	ErrDictTooLarge = &Error{Code: int(C.ZXC_ERROR_DICT_TOO_LARGE), Name: "dictionary exceeds maximum size"}
	ErrBadLevel     = &Error{Code: int(C.ZXC_ERROR_BAD_LEVEL), Name: "compression level out of range"}
	ErrBadParam     = &Error{Code: int(C.ZXC_ERROR_BAD_PARAM), Name: "parameter out of range"}
	ErrInvalidData  = errors.New("zxc: invalid compressed data")

	// ErrBadHufTable is returned when a shared literal Huffman table does not
	// have the required [HufTableSize] length.
	ErrBadHufTable = errors.New("zxc: shared Huffman table must be HufTableSize bytes")

	// ErrDictUnsupported is returned by the push streaming API when dictionary
	// options are supplied: the push-stream format carries no dictionary ID, so
	// dictionary compression would produce undecodable archives.
	ErrDictUnsupported = &Error{Code: int(C.ZXC_ERROR_DICT_UNSUPPORTED), Name: "dictionary not supported by this API"}

	// ErrSeekableInUse is returned when ReadAt calls Close, SetDict or a nested
	// DecompressRange on its [Seekable], which would free or share what the
	// running call uses.
	ErrSeekableInUse = errors.New("zxc: seekable handle in use by the running call")
)

Sentinel errors for each ZXC error code.

Functions

func Compress

func Compress(data []byte, opts ...Option) ([]byte, error)

Compress compresses data using the ZXC algorithm.

Options: WithLevel, WithChecksum, WithSeekable, WithDict.

out, err := zxc.Compress(data, zxc.WithLevel(zxc.LevelCompact))

func CompressBlockBound

func CompressBlockBound(inputSize int) uint64

CompressBlockBound returns the maximum compressed size for a single block of inputSize bytes (no file framing, no EOF, no footer).

func CompressBound

func CompressBound(inputSize int) uint64

CompressBound returns the maximum compressed size for an input of the given size. Use this to pre-allocate output buffers.

func CompressFile

func CompressFile(input, output string, opts ...Option) (int64, error)

CompressFile compresses src to dst using multi-threaded streaming.

This is the recommended method for large files. It uses an asynchronous pipeline with separate reader, worker, and writer threads.

A failed call leaves an existing output intact, because a regular output is written to a temporary file renamed over it. That does not hold when output's directory refuses new files: the output is then truncated and written in place, not atomically. A regular input and output must be different files; ErrBadParam otherwise.

Options: WithLevel, WithChecksum, WithThreads, WithSeekable, WithDict.

n, err := zxc.CompressFile("input.bin", "output.zxc",
    zxc.WithLevel(zxc.LevelCompact), zxc.WithThreads(4))

func CompressTo

func CompressTo(data []byte, output []byte, opts ...Option) (int, error)

CompressTo compresses data into a pre-allocated output buffer. Returns the number of bytes written. Empty input yields a minimal frame, as with Compress.

Options: same as Compress.

func Decompress

func Decompress(data []byte, opts ...Option) ([]byte, error)

Decompress decompresses ZXC-compressed data.

The output size is read from the compressed data footer. For pre-allocated buffers, use DecompressTo. Checksums the archive carries are verified, unless WithChecksum is false.

Options: WithChecksum, WithDict, WithDictHuf, WithDictionary, WithMaxOutputSize.

func DecompressBlockBound

func DecompressBlockBound(uncompressedSize int) uint64

DecompressBlockBound returns the minimum destination buffer size required by Dctx.DecompressBlock for a block of uncompressedSize bytes.

The fast decoder uses speculative wild-copy writes and needs a small tail pad beyond the declared uncompressed size. Callers that cannot oversize their destination buffer should use Dctx.DecompressBlockSafe instead.

func DecompressFile

func DecompressFile(input, output string, opts ...Option) (int64, error)

DecompressFile decompresses src to dst using multi-threaded streaming. The output is handled as by CompressFile. Checksums the archive carries are verified, unless WithChecksum is false.

Options: WithChecksum, WithThreads, WithDict.

n, err := zxc.DecompressFile("compressed.zxc", "output.bin")

func DecompressTo

func DecompressTo(data []byte, output []byte, opts ...Option) (int, error)

DecompressTo decompresses data into a pre-allocated output buffer, which an empty archive lets be empty. Returns the number of bytes written.

Options: same as Decompress; output bounds the size, not WithMaxOutputSize.

func DecompressedSize

func DecompressedSize(data []byte) (uint64, error)

DecompressedSize returns the original uncompressed size the footers store, summed over concatenated archives, 0 for an empty archive. Returns 0, ErrInvalidData if the data is too small or invalid.

func DefaultLevel

func DefaultLevel() int

DefaultLevel returns the default compression level (currently 3).

func DetectZxc

func DetectZxc(data []byte) bool

DetectZxc reports whether data starts with the ZXC file magic word.

Useful for content-type sniffing in containers / object stores that need to decide which decoder to dispatch (e.g. OCI media-type negotiation). The check is cheap and side-effect free; it does not validate the rest of the header or the footer.

func DictGetID

func DictGetID(zxd []byte) uint32

DictGetID returns the dictionary ID stored in a serialized .zxd file buffer, or 0 if the buffer is not a valid .zxd file. 0 is also a valid ID: DictLoad tells them apart.

func DictHuf

func DictHuf(zxd []byte) []byte

DictHuf returns a copy of the shared literal Huffman table stored in a .zxd file buffer, or nil if the buffer is not a valid .zxd file.

func DictID

func DictID(content []byte) uint32

DictID computes the deterministic 32-bit ID of raw dictionary content. Returns 0 for empty content.

func DictLoad

func DictLoad(zxd []byte) (content []byte, id uint32, err error)

DictLoad validates a .zxd file buffer and returns a copy of its dictionary content along with the dictionary ID. Prefer LoadDictionary for the full (content, table, id) bundle.

func DictSave

func DictSave(content, hufLengths []byte) ([]byte, error)

DictSave serializes dictionary content and its shared literal Huffman table (HufTableSize bytes, from TrainDictHuf) into the .zxd file format. The stored dictionary ID covers both content and table.

func EstimateCctxSize

func EstimateCctxSize(srcSize, level int) uint64

EstimateCctxSize returns an accurate estimate of the memory a compression context reserves when compressing a single block of srcSize bytes at the given compression level via Cctx.CompressBlock.

The estimate covers all per-chunk working buffers (chain table, literals, sequence/token/offset/extras buffers) plus the fixed hash tables and cache-line alignment padding. At level 6+ it also accounts for the optimal-parser scratch. It scales roughly linearly with srcSize and is intended for integrators that need an accurate memory budget.

Returns 0 if srcSize is 0 or negative.

func FileDecompressedSize

func FileDecompressedSize(path string) (int64, error)

FileDecompressedSize reads the original uncompressed size from the footer of a ZXC compressed file without performing decompression. The file is opened in "rb" mode; the underlying file position is restored internally.

func GetDictID

func GetDictID(archive []byte) uint32

GetDictID returns the dictionary ID recorded in a compressed .zxc archive header, or 0 if the archive was not compressed with a dictionary (or is too small / invalid). 0 is also a valid ID: RequiresDict tells them apart.

func LibraryCodename

func LibraryCodename() string

LibraryCodename returns the release code name reported by the linked native libzxc (e.g. "Hydrogen"). Informational only; compare versions with LibraryVersion.

func LibraryVersion

func LibraryVersion() string

LibraryVersion returns the version string reported by the linked native libzxc.

func MaxLevel

func MaxLevel() int

MaxLevel returns the maximum supported compression level (currently 7).

func MinLevel

func MinLevel() int

MinLevel returns the minimum supported compression level (currently 1).

func RequiresDict added in v1.0.3

func RequiresDict(archive []byte) (bool, error)

RequiresDict reports whether a compressed .zxc archive needs a dictionary, from its header flag alone: a required dictionary may have ID 0. Only the first 16 bytes are read. It returns an error for an invalid header.

func SeekTableSize

func SeekTableSize(numBlocks uint64) int

SeekTableSize returns the encoded byte size of a seek table covering numBlocks data blocks. Use this to size a destination buffer for WriteSeekTable. Returns 0 when that size does not fit a size_t.

func TrainDict

func TrainDict(samples [][]byte, maxSize int) ([]byte, error)

TrainDict trains a dictionary from a corpus of samples.

It analyses the samples to select byte sequences that maximise LZ77 match coverage, returning raw dictionary content suitable for WithDict, DictSave, or DictID. maxSize caps the trained dictionary size; values <= 0 or greater than DictSizeMax are clamped to DictSizeMax.

At least one non-empty sample is required.

func TrainDictHuf

func TrainDictHuf(samples [][]byte, dict []byte) ([]byte, error)

TrainDictHuf trains the shared literal Huffman table for an already-trained dictionary (see TrainDict). It compresses the samples with the dictionary and derives canonical code lengths from the real post-LZ literal distribution. The returned HufTableSize-byte table is required by DictSave and can be attached with WithDictHuf.

func Version

func Version() (int, int, int)

Version returns the library version as (major, minor, patch).

func VersionString

func VersionString() string

VersionString returns the library version as a "major.minor.patch" string, computed from the compile-time constants in the C header.

For the version reported by the dynamically-linked native library (useful for detecting ABI mismatch), call LibraryVersion.

func WriteSeekTable

func WriteSeekTable(dst []byte, compSizes []uint32) (int, error)

WriteSeekTable writes a seek table (header + entries) into dst. compSizes is the slice of per-block on-disk compressed sizes, in order.

Most callers do not need this directly: the file and streaming APIs already emit a seek table when WithSeekable is enabled.

Types

type CStream

type CStream struct {
	// contains filtered or unexported fields
}

CStream is a push-based, single-threaded compression stream — the Go counterpart of the C [zxc_cstream]. Use it to integrate ZXC into event loops, callback-driven libraries, or non-blocking network protocols where the CompressFile FILE*-based pipeline is not appropriate.

CStream is not safe for concurrent use; one goroutine per stream. Always defer a call to CStream.Close; a finalizer frees a dropped stream only once the garbage collector runs.

func NewCStream

func NewCStream(opts ...Option) (*CStream, error)

NewCStream creates a push compression stream.

Honoured options: WithLevel, WithChecksum. WithThreads and WithSeekable are ignored (the push API is single-threaded and never emits a seek table). WithDict/WithDictionary return ErrDictUnsupported: the push-stream format carries no dictionary ID, so dictionary compression would produce undecodable archives.

func (*CStream) Close

func (c *CStream) Close() error

Close releases the stream and all internal buffers. Safe to call multiple times.

func (*CStream) Compress

func (c *CStream) Compress(out, in []byte) (consumed, produced int, pending int64, err error)

Compress pushes bytes from in into the stream and writes compressed bytes to out. Returns:

  • consumed: bytes read from in.
  • produced: bytes written into out.
  • pending: bytes still staged inside the stream (drain out and call again with the same or new in to continue).

A return of (consumed, produced, 0, nil) means in was fully consumed and no compressed bytes remain pending. Calling with an empty in is valid (drain-only mode).

func (*CStream) End

func (c *CStream) End(out []byte) (produced int, pending int64, err error)

End finalises the stream by flushing the residual block, then writing the EOF block and the file footer to out. Call repeatedly while pending > 0, draining out between calls.

After End returns (produced, 0, nil), the stream is in DONE state; further calls return ErrNullInput. Always call CStream.Close to release the native resources.

func (*CStream) InSize

func (c *CStream) InSize() int

InSize returns the suggested input chunk size for best throughput.

func (*CStream) OutSize

func (c *CStream) OutSize() int

OutSize returns the suggested output chunk size to never trigger a partial drain.

type Cctx

type Cctx struct {
	// contains filtered or unexported fields
}

Cctx is a reusable compression context for the Block API.

It wraps an opaque C handle that is freed by Cctx.Close. Create with NewCctx and always defer a call to Close to release the native memory. A context dropped without Close is freed by a finalizer, but only once the garbage collector runs, which native memory alone never triggers.

Cctx is not safe for concurrent use; one goroutine per context.

func NewCctx

func NewCctx(opts ...Option) (*Cctx, error)

NewCctx creates a new compression context.

WithLevel, WithChecksum, WithDict and WithDictHuf become the defaults for every Cctx.CompressBlock call that does not override them. The level and the table length are validated here; the context carves for a dictionary on first use.

func (*Cctx) Close

func (c *Cctx) Close() error

Close releases the native resources held by the context. Safe to call multiple times.

func (*Cctx) CompressBlock

func (c *Cctx) CompressBlock(src, dst []byte, opts ...Option) (int, error)

CompressBlock compresses a single block using the context. Output format is [block_header(8B) + payload (+ optional checksum 4B)]. Use CompressBlockBound to size dst.

Per-call WithLevel / WithChecksum override the values given to NewCctx; when omitted, the creation-time settings apply. WithDict/WithDictHuf fall back to NewCctx's, except that a per-call WithDict takes only the table given with it. A block carries no dictionary id, so pass the same pair to Dctx.DecompressBlock. Nor does it say whether it has a checksum, off by default: enable WithChecksum on both sides or neither.

type DStream

type DStream struct {
	// contains filtered or unexported fields
}

DStream is a push-based, single-threaded decompression stream — the Go counterpart of the C [zxc_dstream]. Always defer a call to DStream.Close; as with CStream, a finalizer is only a safety net.

func NewDStream

func NewDStream(opts ...Option) (*DStream, error)

NewDStream creates a push decompression stream.

Honoured options: WithChecksum, verifying unless false. WithThreads is ignored. WithDict/WithDictionary return ErrDictUnsupported (see NewCStream).

func (*DStream) Close

func (d *DStream) Close() error

Close releases the stream and all internal buffers. Safe to call multiple times.

func (*DStream) Decompress

func (d *DStream) Decompress(out, in []byte) (consumed, produced int, err error)

Decompress pushes compressed bytes from in into the stream and writes decompressed bytes to out. Returns:

  • consumed: bytes read from in.
  • produced: bytes written into out.

Each call stops at the end of a frame, consumed pointing just past it: a caller after one frame stops there once DStream.Finished is true. A later call with more input decodes the next frame (concatenated archives); input that does not open with the magic word is an error.

func (*DStream) Finished

func (d *DStream) Finished() bool

Finished reports whether the input so far ends on a validated footer; more input starts the next frame. Useful to detect truncated streams: if the input source is drained and Finished returns false, the stream ended prematurely.

func (*DStream) InSize

func (d *DStream) InSize() int

InSize returns the suggested input chunk size for the decompressor.

func (*DStream) OutSize

func (d *DStream) OutSize() int

OutSize returns the suggested output chunk size for the decompressor.

type Dctx

type Dctx struct {
	// contains filtered or unexported fields
}

Dctx is a reusable decompression context for the Block API. Always defer a call to Dctx.Close; as with Cctx, a finalizer is only a safety net.

Dctx is not safe for concurrent use; one goroutine per context.

func NewDctx

func NewDctx(opts ...Option) (*Dctx, error)

NewDctx creates a new decompression context.

WithChecksum, WithDict and WithDictHuf become the defaults for every decode call that does not override them, mirroring NewCctx. Unlike frame decoding, verification is off unless requested: see Dctx.DecompressBlock.

func (*Dctx) Close

func (d *Dctx) Close() error

Close releases the native resources held by the context.

func (*Dctx) DecompressBlock

func (d *Dctx) DecompressBlock(src, dst []byte, opts ...Option) (int, error)

DecompressBlock decompresses a single block produced by Cctx.CompressBlock.

dst should be at least DecompressBlockBound(uncompressedSize) to enable the fast decode path. For a strictly-sized destination buffer use Dctx.DecompressBlockSafe instead. WithDict/WithDictHuf fall back to NewDctx's, except that a per-call WithDict takes only the table given with it, and must match those used at compression: a block carries no dictionary id. Nor does it say whether it has a checksum, so nothing is verified by default: enable WithChecksum on both sides or neither.

func (*Dctx) DecompressBlockSafe

func (d *Dctx) DecompressBlockSafe(src, dst []byte, opts ...Option) (int, error)

DecompressBlockSafe is a strict-sized variant of Dctx.DecompressBlock: it accepts a destination buffer sized exactly to the uncompressed length, with no tail-pad required. Slightly slower than the fast path; output is bit-identical. Takes the same WithChecksum and WithDict/WithDictHuf; a dictionary decodes through the bounce path, so dst may hold more than the strict tail.

type Dictionary

type Dictionary struct {
	// contains filtered or unexported fields
}

Dictionary bundles a trained dictionary's LZ-window content and its shared literal Huffman table, so callers never juggle the pair by hand.

Create one with TrainDictionary (from samples) or LoadDictionary (from .zxd bytes); attach it with WithDictionary or Seekable.SetDictionary.

func LoadDictionary

func LoadDictionary(zxd []byte) (*Dictionary, error)

LoadDictionary parses .zxd bytes into an owned Dictionary.

func TrainDictionary

func TrainDictionary(samples [][]byte) (*Dictionary, error)

TrainDictionary trains a complete dictionary (content + shared table) from a corpus of samples in one call.

func (*Dictionary) Content

func (d *Dictionary) Content() []byte

Content returns the raw LZ-window content bytes.

func (*Dictionary) Huf

func (d *Dictionary) Huf() []byte

Huf returns the 128-byte shared literal Huffman table.

func (*Dictionary) ID

func (d *Dictionary) ID() uint32

ID returns the dictionary ID binding the (content, table) pair, as recorded in .zxd files and archive headers.

func (*Dictionary) Save

func (d *Dictionary) Save() ([]byte, error)

Save serializes the dictionary back to .zxd file bytes.

type Error

type Error struct {
	Code int
	Name string
}

Error represents a ZXC library error.

func (*Error) Error

func (e *Error) Error() string

type FrameInfo

type FrameInfo struct {
	DecompressedSize uint64 // source bytes the frame decodes to
	CompressedSize   uint64 // compressed bytes of the frame, footer included
	Digest           uint64 // archive digest; 0 when HasChecksum is false
	BlockSize        int
	DictID           uint32 // dictionary the frame needs; 0 for none
	FormatVersion    uint8
	HasChecksum      bool
	HasSeekTable     bool
}

FrameInfo is what a frame's header and footer declare.

func GetFrameInfo

func GetFrameInfo(data []byte) (FrameInfo, error)

GetFrameInfo reads a frame's header and footer, without decoding. The frame must span all of data: concatenated archives are refused, DecompressedSize gives their total.

type Level

type Level int

Level represents a ZXC compression level.

const (
	// LevelFastest provides the fastest compression, best for real-time
	// applications (level 1).
	LevelFastest Level = C.ZXC_LEVEL_FASTEST

	// LevelFast provides fast compression, good for real-time applications
	// (level 2).
	LevelFast Level = C.ZXC_LEVEL_FAST

	// LevelDefault is the recommended default: ratio > LZ4, decode speed > LZ4
	// (level 3).
	LevelDefault Level = C.ZXC_LEVEL_DEFAULT

	// LevelBalanced provides good ratio with good decode speed (level 4).
	LevelBalanced Level = C.ZXC_LEVEL_BALANCED

	// LevelCompact provides high density: storage, firmware and assets
	// (level 5).
	LevelCompact Level = C.ZXC_LEVEL_COMPACT

	// LevelDensity provides high density: Huffman-coded literals on top
	// of LevelCompact plus a price-based optimal LZ77 parser (level 6).
	LevelDensity Level = C.ZXC_LEVEL_DENSITY

	// LevelUltra provides maximum density: Huffman-coded literals and sequence
	// tokens with a deep parse. Slowest compression, best ratio (level 7).
	LevelUltra Level = C.ZXC_LEVEL_ULTRA
)

func AllLevels

func AllLevels() []Level

AllLevels returns all available compression levels from fastest to most compact.

type Option

type Option func(*options)

Option configures compression or decompression.

func WithChecksum

func WithChecksum(enabled bool) Option

WithChecksum controls checksums. Compression writes them when true; off by default. Decompression verifies those an archive carries unless false; an archive without checksums decodes either way. Seekable takes Seekable.SetChecksum instead.

The Block API is the exception: a bare block does not say whether it carries a checksum, so it is off on both sides by default and both sides must agree.

func WithDict

func WithDict(dict []byte) Option

WithDict sets a pre-trained dictionary used for compression or decompression. The same dictionary content must be supplied to both Compress and Decompress (the dictionary ID stored in the archive header is validated against it). An empty slice clears the dictionary.

Train a dictionary with TrainDict or load one from a .zxd file with DictLoad. The content size must not exceed DictSizeMax.

func WithDictHuf

func WithDictHuf(huf []byte) Option

WithDictHuf sets the dictionary's shared literal Huffman table (HufTableSize bytes, from TrainDictHuf or DictHuf). It is ignored without WithDict. The archive's dictionary ID binds the (dict, table) pair, so the same table must be supplied at decompression time.

func WithDictionary

func WithDictionary(d *Dictionary) Option

WithDictionary attaches a Dictionary (content + shared table) in one call. A nil Dictionary clears it, as an empty WithDict does.

func WithLevel

func WithLevel(l Level) Option

WithLevel sets the compression level. A level outside [MinLevel, MaxLevel] is refused with ErrBadLevel; 0 selects LevelDefault.

func WithMaxOutputSize

func WithMaxOutputSize(n uint64) Option

WithMaxOutputSize makes Decompress refuse, with ErrDstTooSmall and before allocating, an archive whose footer declares more than n bytes. There is no limit by default: a small forged archive can declare far more than the machine can allocate, which is a fatal, unrecoverable error in Go, so set this on untrusted input. Other entry points write to caller-supplied storage and ignore it.

func WithSeekable

func WithSeekable(enabled bool) Option

WithSeekable enables seek table generation for random-access decompression.

func WithThreads

func WithThreads(n int) Option

WithThreads sets the number of worker threads for streaming operations. A value of 0 means auto-detect the CPU core count; a negative one, or more than the library's maximum (512), is refused with ErrBadParam.

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

Reader is an io.ReadCloser that decompresses the ZXC frames read from an underlying reader: concatenated archives decode as one stream.

Reader is not safe for concurrent use.

func NewReader

func NewReader(r io.Reader, opts ...Option) (*Reader, error)

NewReader returns a Reader that decompresses from r.

Honoured options: WithChecksum, verifying unless false. WithThreads is ignored.

func (*Reader) Close

func (r *Reader) Close() error

Close releases the underlying DStream. The wrapped io.Reader is NOT closed. Safe to call multiple times.

func (*Reader) Multistream

func (r *Reader) Multistream(ok bool)

Multistream controls whether the reader decodes concatenated archives as one stream (true, the default) or stops after the first frame, returning io.EOF there, as on a source that stays open after it. Bytes read ahead past that frame are then lost to the caller, as with compress/gzip.Reader.Multistream.

func (*Reader) Read

func (r *Reader) Read(p []byte) (int, error)

Read decompresses bytes into p. It reads the source until it ends, so concatenated archives decode as one stream; on a source that stays open after one frame, set Reader.Multistream to false. Returns io.EOF once the source ends on a validated footer (or the first frame does, without multistream), io.ErrUnexpectedEOF if it ends before one.

type Seekable

type Seekable struct {
	// contains filtered or unexported fields
}

Seekable is a handle to a seekable ZXC archive.

Build one with Open (file-backed) or OpenBytes (in-memory). Checksums the archive carries are verified; Seekable.SetChecksum opts out. Always defer a call to Seekable.Close to release the native resources. A handle dropped without Close is released by a finalizer once the garbage collector runs; until then it keeps its file open (locked, on Windows), its source pinned and its reader reachable.

A Seekable handle is single-threaded: callers must not invoke its methods from more than one goroutine concurrently. From ReadAt, Close, SetDict and a nested DecompressRange return ErrSeekableInUse.

func Open

func Open(path string) (*Seekable, error)

Open opens a seekable archive from a file path.

The file is opened in binary read mode through the C runtime and remains open for the lifetime of the returned handle. Close releases both the archive handle and the underlying FILE*.

func OpenBytes

func OpenBytes(data []byte) (*Seekable, error)

OpenBytes opens a seekable archive from an in-memory buffer.

The library requires the source buffer to remain valid for the lifetime of the handle, so data is pinned (not copied) until Seekable.Close — opening a large archive costs no extra memory. The caller must not modify data while the handle is open.

func OpenReader

func OpenReader(r io.ReaderAt, size int64) (*Seekable, error)

OpenReader opens a seekable archive backed by a user-supplied io.ReaderAt. Use this to plug any storage that supports positional reads behind the seekable API: an *os.File, an *bytes.Reader, an HTTP range-request client, an S3 object, a custom VFS.

size must be the total compressed-archive size in bytes (use f.Stat().Size() for an *os.File). The library invokes ReadAt three times during the call (header, footer, EOF/SEK block headers), then during each DecompressRange call once per seek table group the range covers and once per block; BlockCompressedSize reads the block's group per call.

The caller's reader must remain valid until Seekable.Close is called. ReadAt may be invoked from any goroutine but never concurrently in the current single-threaded API; a future multi-threaded entry point will require ReadAt to be safe for concurrent use.

func (*Seekable) BlockCompressedSize

func (s *Seekable) BlockCompressedSize(blockIdx uint64) (size uint32, ok bool, err error)

BlockCompressedSize returns the on-disk size of a specific block (block header + payload + optional per-block checksum), read from its seek table group and checked against bounds only. ok is false if blockIdx is out of range or the handle is closed; err is ErrInvalidData if the group is unreadable or invalid.

func (*Seekable) BlockDecompressedSize

func (s *Seekable) BlockDecompressedSize(blockIdx uint64) (uint32, bool)

BlockDecompressedSize returns the decompressed size of a specific block. The second return value is false if blockIdx is out of range or the handle has been closed.

func (*Seekable) Close

func (s *Seekable) Close() error

Close releases the native resources associated with the handle. Safe to call multiple times; subsequent calls are no-ops. From ReadAt it returns ErrSeekableInUse and releases nothing.

func (*Seekable) DecompressRange

func (s *Seekable) DecompressRange(dst []byte, offset uint64, length int) (int, error)

DecompressRange decompresses length bytes starting at offset (in the original uncompressed byte stream) into dst.

Only the blocks overlapping the requested range are read and decompressed. dst must be at least length bytes long. Returns the number of bytes written, which equals length on success.

func (*Seekable) DecompressedSize

func (s *Seekable) DecompressedSize() uint64

DecompressedSize returns the total decompressed size of the archive in bytes. Returns 0 if the handle has been closed.

func (*Seekable) NumBlocks

func (s *Seekable) NumBlocks() uint64

NumBlocks returns the total number of data blocks in the archive (excluding the EOF marker block). Returns 0 if the handle has been closed.

Derived from the footer, never stored, so only the archive size bounds it.

func (*Seekable) SetChecksum

func (s *Seekable) SetChecksum(enabled bool) error

SetChecksum turns per-block checksum verification on or off.

On from the moment the handle opens, as in the one-shot API. No effect on an archive without checksums. Applies from the next call.

func (*Seekable) SetDict

func (s *Seekable) SetDict(dict, hufLengths []byte) error

SetDict attaches a pre-trained dictionary to the seekable handle so that subsequent Seekable.DecompressRange calls can decode blocks that were compressed with that dictionary. It must be called before decoding a range through a dictionary-compressed frame; call it once per dictionary when concatenated frames use several.

The dictionary content must match the one used at compression time; its ID must be one a frame of the archive declares, unless no frame needs one: then it is ignored. When the archive was compressed with a shared literal Huffman table, pass the same table as hufLengths (HufTableSize bytes, see DictHuf); pass nil otherwise. Both buffers are copied internally by the library. Passing an empty dict is an error.

func (*Seekable) SetDictionary

func (s *Seekable) SetDictionary(d *Dictionary) error

SetDictionary attaches a Dictionary (content + shared table) in one call.

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer is an io.WriteCloser that compresses bytes written to it and forwards the resulting ZXC frame to an underlying writer.

The caller MUST call Writer.Close to flush the residual block, EOF marker and footer; closing the underlying writer is the caller's responsibility. A Writer dropped without Close has its native memory freed by a finalizer, but the output it wrote is truncated: no finalizer can complete the frame.

Writer is not safe for concurrent use.

func NewWriter

func NewWriter(w io.Writer, opts ...Option) (*Writer, error)

NewWriter returns a Writer that compresses into w using a single-threaded push pipeline.

Honoured options: WithLevel, WithChecksum. WithThreads and WithSeekable are ignored (push API is single-threaded).

func (*Writer) Close

func (w *Writer) Close() error

Close flushes any buffered data, writes the EOF block + footer, and releases the underlying CStream. The wrapped io.Writer is NOT closed.

Safe to call multiple times; subsequent calls are no-ops.

func (*Writer) Write

func (w *Writer) Write(p []byte) (int, error)

Write compresses p and forwards the produced bytes to the underlying writer. Returns the number of bytes consumed from p (always len(p) on success).

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL