Alpha.16 · standard library

Gzip decoding

Decode gzip incrementally with checked trailers, bounded work and an explicit total output budget.

These pages describe alpha.16. Host I/O requires the native toolchain; browser capabilities are limited. Browse the stdlib guides.

All standard library modules

Decode gzip incrementally with checked trailers, bounded work and an explicit total output budget.

Import

import stdlib/compression/gzip as gzip

For an async function, select the async module instead:

import stdlib/compression/gzip/async as gzip

Await effectful operations. In the signatures below, an ordinary effectful function becomes async under the async import; parameter and result types stay the same. Pure functions and value methods remain ordinary calls. The two imports share their value and error types.

create_decoder()

create_decoder(output_limit: Nat): Result[GzipDecoder,GzipError]

Parameters

  • output_limit: Nat — total decoded-byte budget, from zero through 256 MiB.

Returns: Result[GzipDecoder,GzipError].

Creates an invocation-owned decoder. A zero budget can decode an empty member. At most 64 decoder slots may be allocated per invocation; slots are not reused.

Errors: UnsupportedOutputLimit, decoder unavailability, resource limits and unsupported-host errors are reported.

decode_chunk()

decode_chunk(decoder: GzipDecoder, data: Bytes, finish: Bool): Result[GzipChunk,GzipError]

Parameters

  • decoder: GzipDecoder — live decoder.
  • data: Bytes — at most 65,536 compressed bytes, including any unconsumed bytes from the preceding step.
  • finish: Bool — true when no further input will follow.

Returns: Result[GzipChunk,GzipError].

Each step consumes part or all of the input and produces at most 65,536 output bytes. Advance only by consumed; preserve the remaining bytes for the next call. Checks concatenated gzip members and trailers. Successful final input stops further decoding but does not close the handle. The async form performs one bounded native step, then yields.

Errors: An oversized chunk is rejected before mutation. Invalid gzip, truncated final input or an exhausted total budget stops decoding; close the decoder afterwards. DecoderStopped rejects further decoding after completion/failure.

close()

close(decoder: GzipDecoder): Result[Unit,GzipError]

Parameters

  • decoder: GzipDecoder — owned decoder, including a finished or failed decoder.

Returns: Result[Unit,GzipError].

Releases the decoder and invalidates every alias. Completion alone is not cleanup.

Errors: Closed or foreign handles return InvalidDecoder.

GzipChunk

record GzipChunk { consumed: Nat, data: Bytes, finished: Bool }
  • consumed is the number of bytes consumed from this call’s input.
  • data is this step’s decoded output.
  • finished tells the caller that decoding has finished.

Never assume all supplied input was consumed or concatenate output without enforcing your application’s memory budget.

Cancellation

Copies alias one decoder. Cancellation before a native step makes no mutation; cancellation after it does not undo decoding. Task/VM teardown closes resources. An allocation failure after mutation closes the resource so it cannot be reused in an uncertain state.

GzipError

record GzipError { operation: GzipOperation, kind: GzipErrorKind, native: HostError }

operation records creation with its output limit, a decode call with input byte count/final-input flag, or close. Use problem.kind for control flow and render for a human-readable explanation. The native field preserves the original failure. Host-backed native errors contain operation: Str, code: Str and native_code: Nat; a zero native number means no host error number was supplied.

enum GzipErrorKind {
  InvalidDecoder, ChunkTooLarge, UnsupportedOutputLimit, OutputLimitExceeded,
  DecoderStopped, DecodeFailed, IncompleteInput, DecoderUnavailable,
  InvalidArgument, ResourceLimit, UnsupportedHost, OtherFailure
}

GzipError.render()

pure render(): Str

Parameters

None.

Returns: Str, a human-readable explanation of this error, including the available operation and failure details.

Pure. Use the structured error fields for control flow; the wording is diagnostic text and must not be parsed.

Example

Decode the complete gzip example, including unconsumed input and explicit close.

Complete example: async gzip

import stdlib/compression/gzip/async as gzip
import stdlib/encoding/utf8 as utf8
import stdlib/console/async as console
import stdlib/host/async as host

// A complete gzip member containing "hello"; no external file is required.
pure compressed_greeting(): Bytes {
  mut data = bytes()
  for value in [31, 139, 8, 0, 0, 0, 0, 0, 0, 19, 203, 72, 205, 201, 201, 7, 0, 134, 166, 16, 54, 5, 0, 0, 0] { data = data.push(value) }
  data
}

async decode_small_message(data: Bytes): Result[Bytes,Str] {
  // This recipe accepts one complete, small message with a 1 KiB output budget.
  match await gzip.create_decoder(1024) {
    Error(problem) => Error(problem.render()),
    Ok(decoder) => {
      mut result: Result[Bytes,Str] = Ok(bytes())
      mut offset: Nat = 0
      mut finished = false
      mut failed = false
      while !finished && !failed {
        match await gzip.decode_chunk(decoder, data.slice(offset, data.len()), true) {
          Error(problem) => { result = Error(problem.render()); failed = true },
          Ok(chunk) => {
            offset = offset + chunk.consumed
            finished = chunk.finished
            result = match result {
              Error(message) => Error(message),
              Ok(output) => Ok(output.join(chunk.data))
            }
          }
        }
      }
      // Unlike SHA-256 finish, completing gzip decoding does not close the handle.
      match await gzip.close(decoder) {
        Ok(closed) => result,
        Error(cleanup) => match result {
          Ok(output) => Error(cleanup.render()),
          Error(message) => Error(message + "\nCleanup also failed: " + cleanup.render())
        }
      }
    }
  }
}

async main(): Unit {
  match await decode_small_message(compressed_greeting()) {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(data) => match utf8.decode(data) {
      Error(decode_error) => {
        reported = await console.write_error_line("The decompressed message is not valid UTF-8.")
        await host.exit(1)
      },
      Ok(message) => match await console.write_line(message) {
        Error(write_error) => await host.exit(1), Ok(written) => ()
      }
    }
  }
}

Implementation: view source on GitHub.

Keep exploring

Explore Panackelty.