Something went wrong. Try again.
Brotli (RFC 7932) compression and decompression for Zig 0.17, with sans-I/O streaming cores and std.Io adapters.
Something went wrong. Try again.
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! Feeds a stream through the decompressor in pieces of a chosen size.
const std = @import("std");const brotli = @import("brotli");
pub const Trailing = enum { reject, allow };
/// Decompresses `input` handing the decompressor at most `in_step` bytes of/// input and `out_step` bytes of room at a time, and returns the output. An/// input that ends before the stream does fails with `error.Truncated`; bytes/// after the end of the stream fail with `error.TrailingData` unless/// `trailing` allows them.pub fn decompress(gpa: std.mem.Allocator, input: []const u8, in_step: usize, out_step: usize, trailing: Trailing) ![]u8 { var d: brotli.Decompressor = .init(gpa, .{}); defer d.deinit(); var out: std.ArrayList(u8) = .empty; defer out.deinit(gpa);
var in_pos: usize = 0; var in_end: usize = @min(input.len, in_step); while (true) { try out.ensureUnusedCapacity(gpa, out_step); const room = out.unusedCapacitySlice()[0..out_step]; const r = try d.decompress(input[in_pos..in_end], room); in_pos += r.read; out.items.len += r.written; switch (r.status) { .done => { if (in_pos != input.len and trailing == .reject) return error.TrailingData; return out.toOwnedSlice(gpa); }, .need_input => { std.debug.assert(in_pos == in_end); if (in_end == input.len) return error.Truncated; in_end = @min(input.len, in_end + in_step); }, .need_output => { // Unread input is passed again, topped up to a full step. in_end = @min(input.len, @max(in_end, in_pos + in_step)); }, } }}