silk.compress.deflate.

Compress bytes as raw DEFLATE, zlib, or gzip, in steps or all at once, with zlib's levels, strategies, and flush modes.

When to use#

Use an Encoder to write .gz files, zlib streams, or HTTP bodies with Content-Encoding: gzip or deflate, in steps and with fixed memory. Use Encoder.encode to compress one complete buffer. Use an EncodeWriter to compress what code writes to the ambient silk.io.writer.Writer, such as a silk.compress.tar.TarWriter archive. Choose the container with silk.compress.inflate.Format, and decode with silk.compress.inflate.Decoder.

Details#

The encoder follows the design of zlib: a sliding window of up to 32 KiB with hash chains, greedy matching for levels 1 to 3, lazy matching for levels 4 to 9, and blocks that use stored, fixed Huffman, or dynamic Huffman codes, whichever is smallest. Level 0 writes stored blocks. Encoder.make allocates all storage one time. Later calls do not allocate and do not keep a borrow of your buffers. The output is deterministic, and with the same options, input and flushes it is byte for byte what zlib 1.3.1 writes, in steps that consume and write what zlib's deflate does with the same input and output lengths. Gzip uses timestamp zero, no optional fields, and operating system byte 255, which zlib sets to the system it was built for; Encoder.setGzipSystem changes it.

Examples#

Compress a buffer with zlib framing#

silk
import silk.mem.allocator { Allocator, OutOfMemoryError }
import silk.core.effect { Effect }
import silk.compress.deflate { EncodeError, Encoder, Options }
import silk.compress.inflate { Format }

pub effect fn main() -> i32
  ! OutOfMemoryError | EncodeError {
  let mut allocator = Allocator.systemAllocatorProvider()
  let input = b"abcabcabcabcabcabcabcabcabcabc"
  let mut output: [u8; 64] = [0; 64]
  let written = run Encoder.encode(input, &mut output, Format.Zlib, Options.make(6))
    |> Effect.provideMut<Allocator>(&mut allocator)
  // A zlib stream starts with 0x78 and is much shorter than the repeated input.
  if output[0] != 120 || written >= input.length {
    return 1
  }
  return 0
}

Import as Encoder with import silk.compress.deflate { Encoder }.

Public declarations: 10.

Strategy#

silk
pub enum Strategy

How the encoder looks for repeated data.

The values match zlib's strategies. Default suits most data.

Default#

silk
Default

Find matches with the effort that the level sets.

Filtered#

silk
Filtered

Like Default, but drop short matches, for data made of small values with a random spread, such as the output of a filter or predictor.

HuffmanOnly#

silk
HuffmanOnly

Do not look for matches. Each byte is a literal in a Huffman block.

Rle#

silk
Rle

Look only for runs of one repeated byte, at distance 1. It is fast and suits images such as PNG rows.

Fixed#

silk
Fixed

Use the fixed Huffman codes of DEFLATE in each compressed block, never dynamic codes.

Flush#

silk
pub enum Flush

What a call to Encoder.step must finish before it returns.

The values match zlib's flush modes. Use None while more input follows, and Finish with the last input.

None#

silk
None

Compress as the encoder sees fit. Output can lag behind the input.

Partial#

silk
Partial

Write all input in a block, then an empty fixed block, as zlib's Z_PARTIAL_FLUSH does. The output can end within a byte.

Sync#

silk
Sync

Write all input, then an empty stored block (00 00 ff ff), so that the output ends on a byte and a decoder can decode all of it. This is zlib's Z_SYNC_FLUSH.

Full#

silk
Full

Like Sync, then forget the history, so that a decoder can start at this point. Compression becomes worse. This is zlib's Z_FULL_FLUSH.

Block#

silk
Block

Write all input and end the current block, without the bytes that Sync adds. Up to 7 bits of the block stay in the encoder until the next call. This is zlib's Z_BLOCK.

Finish#

silk
Finish

Write all input, end the stream, and write the checksum trailer. After it finishes, the encoder accepts no more input.

EncodeStatus#

silk
pub enum EncodeStatus

What the encoder needs after a successful Encoder.step.

NeedInput#

silk
NeedInput

All input is consumed and the flush was None. Call again with more input, or with a flush.

NeedOutput#

silk
NeedOutput

The output buffer is full. Call again with a new output buffer, the input that was not consumed, and the same flush.

Flushed#

silk
Flushed

All input is consumed and the flush, other than None or Finish, is complete.

Finished#

silk
Finished

The stream, with its trailer, is complete.

EncodeProgress#

silk
pub struct EncodeProgress

The result of one successful Encoder.step.

Field consumed#

silk
pub consumed: usize

The number of input bytes that this call consumed, from the start of the input.

Field written#

silk
pub written: usize

The number of output bytes that this call wrote, from the start of the output.

Field status#

silk
pub status: EncodeStatus

What the encoder needs next.

EncodeErrorKind#

silk
pub enum EncodeErrorKind

The cause of an EncodeError.

InvalidOptions#

silk
InvalidOptions

A level, window size, memory level, or strategy is outside its range, or raw or gzip framing asks for 8 window bits.

InvalidUse#

silk
InvalidUse

The call is not allowed now: a dictionary after the stream started or with gzip framing, input after the stream finished, or any step after a failure.

OutputFull#

silk
OutputFull

Encoder.encode filled the output buffer before the stream was complete.

Implementation Debug for EncodeErrorKind#

silk
impl Debug for EncodeErrorKind

Operation debug#

silk
effect fn debug(self: &Self, formatter: &mut Formatter) -> ()
    ! WriterError
    ? &mut Writer

Writes the name of the variant, such as InvalidOptions.

EncodeError#

silk
pub struct EncodeError

An encoding failure, with the progress of the call before it failed.

Gotchas#

After a failed Encoder.step, discard the stream. Each later step fails with InvalidUse until you call Encoder.reset.

Field kind#

silk
pub kind: EncodeErrorKind

The cause of the failure.

Field consumed#

silk
pub consumed: usize

The number of input bytes that the call consumed before it failed.

Field written#

silk
pub written: usize

The number of output bytes that the call wrote before it failed.

Implementation Debug for EncodeError#

silk
impl Debug for EncodeError

Operation debug#

silk
effect fn debug(self: &Self, formatter: &mut Formatter) -> ()
    ! WriterError
    ? &mut Writer

Writes the fields, as EncodeError { kind: ..., consumed: ..., written: ... }.

Options#

silk
pub struct Options

The settings of an Encoder, with the ranges and meanings of zlib's deflateInit2.

Field level#

silk
pub level: u32

The effort, from 0 to 9. 0 stores the data without compression, 1 is the fastest, and 9 is the smallest. 6 is zlib's default.

Field windowBits#

silk
pub windowBits: u32

The base-2 logarithm of the window, from 8 to 15. A larger window finds more matches and uses more memory. 8 is treated as 9, as zlib does, and only with zlib framing.

Field memoryLevel#

silk
pub memoryLevel: u32

How much memory the match table and the block buffer use, from 1 to 9. 8 is zlib's default.

Field strategy#

silk
pub strategy: Strategy

How the encoder looks for repeated data.

Field hash#

silk
pub hash: Hash

How the encoder finds earlier occurrences of the next bytes.

Hash#

silk
pub enum Hash

How an Encoder finds earlier occurrences of the next bytes. Each choice writes the bytes of a zlib that uses it, and each is the same on every target.

Rolling#

silk
Rolling

zlib's rolling hash of 3 bytes, in a table of 1 << (memoryLevel + 7) entries. The output is byte for byte zlib 1.3.1's.

Multiplicative#

silk
Multiplicative

The hash of Chromium's zlib, which Node.js and Chrome use: a multiplicative hash of 4 bytes, in a table of at least 1 << 15 entries. Its chains have fewer collisions, so it is faster at levels 4 to 9 and compresses about as well. The output is byte for byte Chromium zlib's (revision 09a1572 of Node 24).

Implementation Options#

silk
impl Options

Associated function make#

silk
pub fn make(level: u32) -> Options

Returns options with level, a 32 KiB window, memory level 8, the default strategy, and zlib's rolling hash, the defaults of zlib's deflateInit.

Encoder#

silk
pub struct Encoder

A streaming DEFLATE, zlib, or gzip encoder that owns its window, tables, and output buffer.

When to use#

Use it to compress data that arrives in parts, or to control flushing, as zlib's deflate does. Make one with Encoder.make, call Encoder.step with each part of the input, and end with Flush.Finish. Call Encoder.reset to compress another stream with the same storage.

Details#

Encoder.make allocates all storage one time: about 2 << windowBits bytes of window, 2 << windowBits bytes of chains, 2 << (memoryLevel + 7) bytes of hash heads, and 7 << (memoryLevel + 6) bytes of block and output buffers. Later calls do not allocate and do not keep a borrow of your buffers, so you can move the encoder between threads between calls.

Gotchas#

Compressed bytes can wait in the encoder until a flush. Use Flush.Sync to make all input so far decodable.

Implementation Encoder#

silk
impl Encoder

Associated function make#

silk
pub effect fn make(format: Format, options: Options) -> Encoder
    ! OutOfMemoryError | EncodeError
    ? &mut Allocator

Returns an encoder for one stream in format with options, with storage from the ambient Allocator.

Errors#

  • EncodeError with InvalidOptions if an option is outside its range, checked before the allocation.

  • OutOfMemoryError if the Allocator fails.

Method reset#

silk
pub fn reset(self: &mut Self) -> ()

Starts a new stream with the same format, options, and storage, as zlib's deflateReset does.

It does not allocate. It drops the input and output that the encoder holds, any dictionary, and a failure. Parameters set with Encoder.setParameters stay.

Method setGzipSystem#

silk
pub fn setGzipSystem(self: &mut Self, system: u8) -> ()

Sets the operating system byte of the gzip header, which is 255 (unknown) by default.

Details#

zlib writes the system it was built for: 3 on Unix, 19 on macOS, 10 on Windows. Set it before the first step of a stream. It stays across Encoder.reset. Other formats ignore it.

Method setDictionary#

silk
pub fn setDictionary(self: &mut Self, dictionary: &[u8]) -> Result<(), EncodeError>

Loads dictionary as data that the stream can refer to, as zlib's deflateSetDictionary does.

Details#

Only the last bytes that fit in the window are used. With zlib framing, load it before the first step: the header names the dictionary by its Adler-32, and the decoder must load the same dictionary. With raw framing, load it before the first step or after a step that consumed all of its input with a flush, and the decoder must load the same dictionary at the same place without being told.

Errors#

InvalidUse with gzip framing, with zlib framing after the first step, while the encoder holds input that is not compressed yet, or after a failure.

Method setParameters#

silk
pub fn setParameters(self: &mut Self, level: u32, strategy: Strategy) -> Result<(), EncodeError>

Changes the level and strategy for the data after this call, as zlib's deflateParams does.

Details#

If the change needs another way of compressing (a new strategy, or a level on the other side of 0, 1 to 3, and 4 to 9) and a step ran before, the next Encoder.step first ends the block of the input it holds with the old settings, as Flush.Block does, and only then applies the new settings. Otherwise the new settings apply at once.

Errors#

InvalidOptions if level is more than 9. InvalidUse after a failure or after the stream finished.

Method step#

silk
pub fn step(self: &mut Self, input: &[u8], output: &mut [u8], flush: Flush) -> Result<
    EncodeProgress,
    EncodeError,
  >

Compresses from input into output and returns how much it consumed and wrote.

Details#

On the next call, give only the input after the consumed prefix. You can give a new output buffer of any length. Call with Flush.None while more input follows. A flush finishes only when the step returns Flushed, or Finished for Flush.Finish. Until then, call again with the same flush. A second flush of the same kind with no new input writes nothing.

The steps follow zlib's deflate: with the same options, the same input and output lengths, and the same flushes, each step consumes and writes what zlib 1.3.1 does.

Gotchas#

As in zlib, if a Sync or Full flush fills the output, the step after it can write the marker of the flush again. Give more than 6 bytes of output when a flush starts to avoid it.

Errors#

InvalidUse with input after the stream finished, or after an earlier failure.

Associated function encodedBound#

silk
pub fn encodedBound(length: usize, format: Format) -> Option<usize>

Returns the most bytes that Encoder.encode can write for length input bytes in format, with any options, or None if that count does not fit in usize.

Details#

An output buffer of this size never fails with OutputFull. The bound is length + length / 8 + length / 64 + 6 plus the container: 0 bytes for raw DEFLATE, 10 for zlib with room for a dictionary id, and 18 for gzip.

Associated function encode#

silk
pub effect fn encode(input: &[u8], output: &mut [u8], format: Format, options: Options) -> usize
    ! OutOfMemoryError | EncodeError
    ? &mut Allocator

Compresses all of input into the start of output in format with options, and returns the encoded length.

Details#

It makes an Encoder with storage from the ambient Allocator, runs one step with Flush.Finish, and releases the storage before it returns. Input and output must not overlap, as enforced by their shared and exclusive borrows.

Errors#

  • OutputFull if output fills before the stream is complete. It never occurs when output holds at least Encoder.encodedBound(input.length, format) bytes. Discard the partial stream.

  • InvalidOptions if an option is outside its range.

  • OutOfMemoryError if the Allocator fails.

EncodeWriter#

silk
pub struct EncodeWriter<W>

A Writer that compresses the bytes it receives and writes the stream to another Writer.

When to use#

Use it to write a .gz file, a zlib stream, or a compressed HTTP body from code that writes to the ambient Writer, such as silk.compress.tar.TarWriter, without first collecting the uncompressed bytes. Make one with EncodeWriter.make around the destination, provide it with Effect.provideMut<Writer>(&mut writer), and end the stream with EncodeWriter.finish.

Details#

Each write runs the Encoder with Flush.None and sends its output to the destination in pieces of at most 16 KiB. Writer.flush runs a Flush.Sync, so that a decoder can decode all bytes written so far, and then flushes the destination. EncodeWriter.finish writes the end of the stream and its checksum trailer, flushes the destination, and returns it.

Gotchas#

Dropping the writer does not end the stream. Without EncodeWriter.finish, the destination holds a stream with no end. Each flush makes the stream a little longer and compression a little worse, so flush only when a reader waits for the bytes.

Implementation EncodeWriter<W>#

silk
impl<W> EncodeWriter<W>

Associated function make#

silk
pub effect fn make(destination: W, format: Format, options: Options) -> EncodeWriter<W>
    ! OutOfMemoryError | EncodeError
    ? &mut Allocator

Returns a writer that compresses into destination in format with options, with the encoder's storage from the ambient Allocator.

Errors#

  • EncodeError with InvalidOptions if an option is outside its range.

  • OutOfMemoryError if the Allocator fails.

Implementation EncodeWriter<W>#

silk
impl<W: Writer> EncodeWriter<W>

Method finish#

silk
pub effect fn finish(self: Self) -> W ! WriterError

Ends the stream with its trailer, flushes the destination, and returns it.

Errors#

  • WriterError if the destination fails, or if an earlier write failed. The destination is dropped.

Implementation Writer for EncodeWriter<W>#

silk
impl<W: Writer> Writer for EncodeWriter<W>

Operation writeAll#

silk
effect fn writeAll(self: &mut Self, val: &[u8]) -> () ! WriterError ? &mut Writer

Operation flush#

silk
effect fn flush(self: &mut Self) -> () ! WriterError ? &mut Writer

Category: Data formats.

Profiles: aarch64-apple-darwin, aarch64-unknown-linux-gnu, aarch64-unknown-linux-gnu-no-libc, x86_64-unknown-linux-gnu, x86_64-unknown-linux-gnu-no-libc, wasm32-unknown-unknown, wasm32-wasip1, wasm32-wasip2, x86_64-pc-windows-msvc, wasm64-unknown-unknown.

View the source of this page