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
- Variables
- func Compress(data []byte, opts ...Option) ([]byte, error)
- func CompressBlockBound(inputSize int) uint64
- func CompressBound(inputSize int) uint64
- func CompressFile(input, output string, opts ...Option) (int64, error)
- func CompressTo(data []byte, output []byte, opts ...Option) (int, error)
- func Decompress(data []byte, opts ...Option) ([]byte, error)
- func DecompressBlockBound(uncompressedSize int) uint64
- func DecompressFile(input, output string, opts ...Option) (int64, error)
- func DecompressTo(data []byte, output []byte, opts ...Option) (int, error)
- func DecompressedSize(data []byte) (uint64, error)
- func DefaultLevel() int
- func DetectZxc(data []byte) bool
- func DictGetID(zxd []byte) uint32
- func DictHuf(zxd []byte) []byte
- func DictID(content []byte) uint32
- func DictLoad(zxd []byte) (content []byte, id uint32, err error)
- func DictSave(content, hufLengths []byte) ([]byte, error)
- func EstimateCctxSize(srcSize, level int) uint64
- func FileDecompressedSize(path string) (int64, error)
- func GetDictID(archive []byte) uint32
- func LibraryCodename() string
- func LibraryVersion() string
- func MaxLevel() int
- func MinLevel() int
- func RequiresDict(archive []byte) (bool, error)
- func SeekTableSize(numBlocks uint64) int
- func TrainDict(samples [][]byte, maxSize int) ([]byte, error)
- func TrainDictHuf(samples [][]byte, dict []byte) ([]byte, error)
- func Version() (int, int, int)
- func VersionString() string
- func WriteSeekTable(dst []byte, compSizes []uint32) (int, error)
- type CStream
- type Cctx
- type DStream
- type Dctx
- type Dictionary
- type Error
- type FrameInfo
- type Level
- type Option
- type Reader
- type Seekable
- func (s *Seekable) BlockCompressedSize(blockIdx uint64) (size uint32, ok bool, err error)
- func (s *Seekable) BlockDecompressedSize(blockIdx uint64) (uint32, bool)
- func (s *Seekable) Close() error
- func (s *Seekable) DecompressRange(dst []byte, offset uint64, length int) (int, error)
- func (s *Seekable) DecompressedSize() uint64
- func (s *Seekable) NumBlocks() uint64
- func (s *Seekable) SetChecksum(enabled bool) error
- func (s *Seekable) SetDict(dict, hufLengths []byte) error
- func (s *Seekable) SetDictionary(d *Dictionary) error
- type Writer
Constants ¶
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 )
const DictSizeMax = int(C.ZXC_DICT_SIZE_MAX)
DictSizeMax is the maximum dictionary content size in bytes (65535).
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 ¶
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 ¶
Compress compresses data using the ZXC algorithm.
Options: WithLevel, WithChecksum, WithSeekable, WithDict.
out, err := zxc.Compress(data, zxc.WithLevel(zxc.LevelCompact))
func CompressBlockBound ¶
CompressBlockBound returns the maximum compressed size for a single block of inputSize bytes (no file framing, no EOF, no footer).
func CompressBound ¶
CompressBound returns the maximum compressed size for an input of the given size. Use this to pre-allocate output buffers.
func CompressFile ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DictID computes the deterministic 32-bit ID of raw dictionary content. Returns 0 for empty content.
func DictLoad ¶
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 ¶
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 ¶
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 ¶
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 ¶
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
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 ¶
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 ¶
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 ¶
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 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 ¶
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 ¶
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 ¶
Close releases the stream and all internal buffers. Safe to call multiple times.
func (*CStream) Compress ¶
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 ¶
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.
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 ¶
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 ¶
Close releases the native resources held by the context. Safe to call multiple times.
func (*Cctx) CompressBlock ¶
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 ¶
NewDStream creates a push decompression stream.
Honoured options: WithChecksum, verifying unless false. WithThreads is ignored. WithDict/WithDictionary return ErrDictUnsupported (see NewCStream).
func (*DStream) Close ¶
Close releases the stream and all internal buffers. Safe to call multiple times.
func (*DStream) Decompress ¶
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 ¶
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.
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 ¶
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) DecompressBlock ¶
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 ¶
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 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 ¶
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 )
type Option ¶
type Option func(*options)
Option configures compression or decompression.
func WithChecksum ¶
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 ¶
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 ¶
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 ¶
WithLevel sets the compression level. A level outside [MinLevel, MaxLevel] is refused with ErrBadLevel; 0 selects LevelDefault.
func WithMaxOutputSize ¶
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 ¶
WithSeekable enables seek table generation for random-access decompression.
func WithThreads ¶
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 ¶
NewReader returns a Reader that decompresses from r.
Honoured options: WithChecksum, verifying unless false. WithThreads is ignored.
func (*Reader) Close ¶
Close releases the underlying DStream. The wrapped io.Reader is NOT closed. Safe to call multiple times.
func (*Reader) Multistream ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
DecompressedSize returns the total decompressed size of the archive in bytes. Returns 0 if the handle has been closed.
func (*Seekable) NumBlocks ¶
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 ¶
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 ¶
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 ¶
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).