lz4 compression and tests

This commit is contained in:
Peterino2 2026-11-03 19:33:59 -07:00
parent 3d4be7570e
commit ce85abe197
4 changed files with 560 additions and 2 deletions

View File

@ -37,17 +37,24 @@ pub fn build(b: *std.Build) void {
}, },
}); });
const bindings = b.addTranslateC(.{
.root_source_file = b.path("src/bindings.h"),
.optimize = optimize,
.target = target,
});
const lz4_zig = b.addModule("lz4_zig", .{ const lz4_zig = b.addModule("lz4_zig", .{
.target = target, .target = target,
.optimize = optimize, .optimize = optimize,
.pic = pic, .pic = pic,
.strip = strip, .strip = strip,
.link_libc = true, .link_libc = true,
.root_source_file = b.path("lz4.zig"), .root_source_file = b.path("src/lz4.zig"),
}); });
lz4_zig.linkLibrary(lz4); lz4_zig.linkLibrary(lz4);
lz4_zig.addImport("c", bindings.createModule());
const tests = b.addTes(.{ .root_module = lz4_zig }); const tests = b.addTest(.{ .root_module = lz4_zig });
const run_tests = b.addRunArtifact(tests); const run_tests = b.addRunArtifact(tests);
run_tests.addPassthruArgs(); run_tests.addPassthruArgs();

View File

@ -0,0 +1,5 @@
#pragma once
#include "lz4.h"
#include "lz4hc.h"
#include "lz4frame.h"

View File

@ -0,0 +1,473 @@
// imported definitions
pub const Preferences = c.LZ4F_preferences_t;
pub const ContentCheckSumEnabled = c.LZ4F_contentChecksumEnabled;
pub const Max64KB = c.LZ4F_max64KB;
pub const Cctx = c.LZ4F_cctx;
pub const Dctx = c.LZ4F_dctx;
fn getErrorName(code: c.LZ4F_errorCode_t) ?[]const u8 {
const x = c.LZ4F_getErrorName(code);
if (x) |msg| {
return std.mem.span(msg);
}
return null;
}
fn defaultPreferences() Preferences {
var p = std.mem.zeroes(Preferences);
p.frameInfo.blockSizeID = Max64KB;
p.frameInfo.contentChecksumFlag = ContentCheckSumEnabled;
return p;
}
const Lz4WriterOptions = struct {
chunk_size: usize = 64 * 1024,
buffer: []u8, // caller should pass in working buffer
};
pub const Lz4Writer = struct {
writer: std.Io.Writer,
base_writer: *std.Io.Writer,
allocator: std.mem.Allocator,
compressed: []u8,
buffer: []u8,
ownedBuffer: bool = false,
active: bool = true,
chunk_size: usize,
context: ?*Cctx = null,
// options: Lz4WriterOptions,
// last lz4 error, inspect it with getErrorName()
lz4_error: ?usize = null,
pub fn init(allocator: std.mem.Allocator, base_writer: *std.Io.Writer, options: Lz4WriterOptions) !@This() {
var context: ?*Cctx = null;
// create compression context and allocate buffers based on preferences
const created = c.LZ4F_createCompressionContext(
&context,
c.LZ4F_VERSION,
);
if (c.LZ4F_isError(created) != 0)
return error.Lz4InitialiationFailed;
errdefer _ = c.LZ4F_freeCompressionContext(context);
const prefs = defaultPreferences();
const capacity = @max(c.LZ4F_compressBound(options.chunk_size, &prefs), c.LZ4F_HEADER_SIZE_MAX);
const compressed = try allocator.alloc(u8, capacity);
errdefer allocator.free(compressed);
// write out initial header and frame to compressed buffer
const n = c.LZ4F_compressBegin(
context,
compressed.ptr,
compressed.len,
&prefs,
);
if (c.LZ4F_isError(n) != 0)
return error.Lz4InitialiationFailed;
// flush the compressed buffer to the output writer.
try base_writer.writeAll(compressed[0..n]);
const newWriter: std.Io.Writer = .{
.vtable = &.{ .drain = drain, .flush = flush },
.buffer = options.buffer,
};
return .{
.writer = newWriter,
.base_writer = base_writer,
.buffer = options.buffer,
.context = context,
.allocator = allocator,
.compressed = compressed,
.chunk_size = options.chunk_size,
};
}
pub fn deinit(self: *@This()) void {
_ = c.LZ4F_freeCompressionContext(self.context);
self.allocator.free(self.compressed);
self.* = undefined;
}
pub fn checkCodes(self: *@This(), result: usize) std.Io.Writer.Error!usize {
if (c.LZ4F_isError(result) != 0) {
self.lz4_error = result;
return error.WriteFailed;
}
return result;
}
fn poison(self: *@This()) void {
self.active = false;
self.writer = .failing;
}
fn compress(self: *@This(), bytes: []const u8) std.Io.Writer.Error!void {
var remaining = bytes;
while (remaining.len != 0) {
const n = @min(remaining.len, self.chunk_size);
const written = try self.checkCodes(
c.LZ4F_compressUpdate(
self.context,
self.compressed.ptr,
self.compressed.len,
remaining.ptr,
n,
null,
),
);
try self.base_writer.writeAll(self.compressed[0..written]);
remaining = remaining[n..];
}
}
fn drainBuffered(self: *@This()) !void {
try self.compress(self.writer.buffer[0..self.writer.end]);
self.writer.end = 0;
}
fn drain(w: *std.Io.Writer, data: []const []const u8, splat: usize) std.Io.Writer.Error!usize {
const self: *@This() = @fieldParentPtr("writer", w);
errdefer self.poison();
try self.drainBuffered();
var i: usize = 0;
const d1 = data[0 .. data.len - 1];
while (d1[i].len == 0) : (i += 1) {}
const d = d1[i];
if (i != data.len - 1) {
const n = @min(d.len, self.chunk_size);
try self.compress(d[0..n]);
return n;
}
if (splat != 0 and d.len != 0) {
const n = @min(d.len, self.chunk_size);
try self.compress(d[0..n]);
return n;
}
return 0;
}
fn flush(w: *std.Io.Writer) std.Io.Writer.Error!void {
const self: *@This() = @fieldParentPtr("writer", w);
errdefer self.poison();
try self.drainBuffered();
const n = try self.checkCodes(c.LZ4F_flush(
self.context,
self.compressed.ptr,
self.compressed.len,
null,
));
try self.base_writer.writeAll(self.compressed[0..n]);
try self.base_writer.flush();
}
/// Completes one frame. Further writes fail.
pub fn finish(self: *@This()) std.Io.Writer.Error!void {
if (!self.active) return error.WriteFailed;
defer self.poison();
try self.drainBuffered();
const n = try self.checkCodes(c.LZ4F_compressEnd(
self.context,
self.compressed.ptr,
self.compressed.len,
null,
));
try self.base_writer.writeAll(self.compressed[0..n]);
try self.base_writer.flush();
}
};
const Lz4ReaderOptions = struct {
chunk_size: usize = 64 * 1024,
buffer: []u8,
};
pub const Reader = struct {
reader: std.Io.Reader,
base_reader: *std.Io.Reader,
allocator: std.mem.Allocator,
context: ?*Dctx,
decoded: []u8 = undefined,
decoded_seek: usize = 0,
decoded_end: usize = 0,
frame_done: bool = false,
failure: ?Failure = null,
lz4_error: ?usize = null,
pub const Failure = error{
InvalidFrame,
TruncatedFrame,
SourceReadFailed,
};
pub fn init(
allocator: std.mem.Allocator,
base_reader: *std.Io.Reader,
options: Lz4ReaderOptions,
) !@This() {
if (options.chunk_size == 0 or options.buffer.len == 0) {
return error.InvalidBufferSize;
}
var context: ?*Dctx = null;
const created = c.LZ4F_createDecompressionContext(&context, c.LZ4F_VERSION);
if (c.LZ4F_isError(created) != 0)
return error.Lz4InitializationFailed;
errdefer _ = c.LZ4F_freeDecompressionContext(context);
const decoded = try allocator.alloc(u8, options.chunk_size);
return .{
.reader = .{
.vtable = &.{ .stream = stream },
.buffer = options.buffer,
.seek = 0,
.end = 0,
},
.base_reader = base_reader,
.allocator = allocator,
.context = context,
.decoded = decoded,
};
}
/// Releases resources without consuming the input or closing the source.
pub fn deinit(self: *@This()) void {
_ = c.LZ4F_freeDecompressionContext(self.context);
self.allocator.free(self.decoded);
self.* = undefined;
}
fn fail(self: *@This(), reason: Failure) std.Io.Reader.Error {
self.failure = reason;
return error.ReadFailed;
}
pub fn checkCodes(self: *@This(), result: usize) std.Io.Reader.Error!usize {
if (c.LZ4F_isError(result) != 0) {
self.lz4_error = result;
return self.fail(error.InvalidFrame);
}
return result;
}
fn stream(r: *std.Io.Reader, w: *std.Io.Writer, limit: std.Io.Limit) std.Io.Reader.StreamError!usize {
const self: *@This() = @fieldParentPtr("reader", r);
if (limit == .nothing) return 0;
if (self.decoded_seek == self.decoded_end)
try self.refill();
const bytes = limit.slice(self.decoded[self.decoded_seek..self.decoded_end]);
const written = try w.write(bytes);
self.decoded_seek += written;
return written;
}
/// After reading the payload, verify the footer/checksum and require that
/// no plaintext remains. Leaves subsequent frames in the underlying reader.
pub fn finish(self: *@This()) !void {
_ = self.reader.takeByte() catch |err| switch (err) {
error.EndOfStream => return,
error.ReadFailed => {
if (self.failure) |reason| return reason;
return error.ReadFailed;
},
};
return error.TrailingData;
}
// Only refill after the previous scratch output has been consumed.
fn refill(self: *@This()) std.Io.Reader.Error!void {
if (self.failure != null) return error.ReadFailed;
if (self.frame_done) return error.EndOfStream;
self.decoded_seek = 0;
self.decoded_end = 0;
while (true) {
const input = self.base_reader.buffered();
var consumed: usize = input.len;
var produced: usize = self.decoded.len;
const hint = try self.checkCodes(c.LZ4F_decompress(
self.context,
self.decoded.ptr,
&produced,
input.ptr,
&consumed,
null,
));
self.base_reader.toss(consumed);
self.decoded_end = produced;
// zero means frame + footer is done,
self.frame_done = hint == 0;
if (produced != 0) return;
if (self.frame_done) return error.EndOfStream;
if (consumed == 0) {
if (input.len != 0)
return self.fail(error.InvalidFrame);
_ = self.base_reader.peekGreedy(1) catch |err|
{
return self.fail(switch (err) {
error.EndOfStream => error.TruncatedFrame,
error.ReadFailed => error.SourceReadFailed,
});
};
}
}
}
};
test "lz4 reader,writer" {
var fatbuffer: [64 * 1024]u8 = undefined;
var writerBuffer: [1024 * 1024 * 10]u8 = undefined;
var base_writer = std.Io.Writer.fixed(&writerBuffer);
var writer = try Lz4Writer.init(std.testing.allocator, &base_writer, .{ .buffer = &fatbuffer });
const testString = @embedFile("LICENSE");
try writer.writer.writeAll(testString);
try writer.writer.writeAll(testString);
try writer.writer.flush();
try writer.finish();
defer writer.deinit();
var base_reader = std.Io.Reader.fixed(base_writer.buffered());
var read_buffer: [32]u8 = undefined;
var reader = try Reader.init(std.testing.allocator, &base_reader, .{
.buffer = &read_buffer,
.chunk_size = 17,
});
defer reader.deinit();
var restored: [testString.len]u8 = undefined;
for (0..2) |_| {
try reader.reader.readSliceAll(&restored);
try std.testing.expectEqualStrings(testString, &restored);
}
try reader.finish();
try std.testing.expectEqual(@as(usize, 0), base_reader.bufferedLen());
const xxd = @import("test/xxd.zig");
var xxdwriter = std.Io.Writer.Allocating.init(std.testing.allocator);
defer xxdwriter.deinit();
try xxd.xxdWriteAscii(&xxdwriter.writer, writerBuffer[0..base_writer.end], .{});
try xxdwriter.writer.writeAll("----\n");
try xxdwriter.writer.print("compressedBytes: {d}, uncompressed: {d}", .{ base_writer.end, testString.len * 3 });
try xxdwriter.writer.writeAll("----\n");
try xxd.xxdWriteAscii(&xxdwriter.writer, "wu tang clan coming at you", .{});
try xxdwriter.writer.flush();
const slice = try xxdwriter.toOwnedSlice();
defer std.testing.allocator.free(slice);
std.debug.print("{s} \n", .{slice});
}
const c = @import("c");
const std = @import("std");
fn testFrame(bytes: []const u8) ![]u8 {
const prefs = defaultPreferences();
const output = try std.testing.allocator.alloc(u8, c.LZ4F_compressFrameBound(bytes.len, &prefs));
defer std.testing.allocator.free(output);
const n = c.LZ4F_compressFrame(output.ptr, output.len, bytes.ptr, bytes.len, &prefs);
try std.testing.expect(c.LZ4F_isError(n) == 0);
return std.testing.allocator.dupe(u8, output[0..n]);
}
test "reader handles fragmented input and multiple blocks" {
const payload = try std.testing.allocator.alloc(u8, 200_000);
defer std.testing.allocator.free(payload);
for (payload, 0..) |*byte, i| byte.* = @truncate(i);
const frame = try testFrame(payload);
defer std.testing.allocator.free(frame);
var source = std.Io.Reader.fixed(frame);
var source_buffer: [1]u8 = undefined;
var fragmented = source.limited(.unlimited, &source_buffer);
var buffer: [16]u8 = undefined;
var reader = try Reader.init(std.testing.allocator, &fragmented.interface, .{
.buffer = &buffer,
.chunk_size = 31,
});
defer reader.deinit();
var output = std.Io.Writer.Allocating.init(std.testing.allocator);
defer output.deinit();
try std.testing.expectEqual(payload.len, try reader.reader.streamRemaining(&output.writer));
try reader.finish();
try std.testing.expectEqualSlices(u8, payload, output.written());
}
test "reader validates empty frames and leaves following frames untouched" {
const frame = try testFrame("");
defer std.testing.allocator.free(frame);
const pair = try std.mem.concat(std.testing.allocator, u8, &.{ frame, frame });
defer std.testing.allocator.free(pair);
var source = std.Io.Reader.fixed(pair);
var buffer: [16]u8 = undefined;
for (0..2) |i| {
var reader = try Reader.init(std.testing.allocator, &source, .{ .buffer = &buffer });
defer reader.deinit();
try reader.finish();
try std.testing.expectEqual((1 - i) * frame.len, source.bufferedLen());
}
}
test "reader reports truncated frames and checksum errors" {
const frame = try testFrame("a repeated payload a repeated payload");
defer std.testing.allocator.free(frame);
var buffer: [16]u8 = undefined;
for (0..frame.len) |len| {
var source = std.Io.Reader.fixed(frame[0..len]);
var reader = try Reader.init(std.testing.allocator, &source, .{ .buffer = &buffer });
defer reader.deinit();
var output = std.Io.Writer.Allocating.init(std.testing.allocator);
defer output.deinit();
try std.testing.expectError(error.ReadFailed, reader.reader.streamRemaining(&output.writer));
try std.testing.expectEqual(error.TruncatedFrame, reader.failure.?);
try std.testing.expectError(error.TruncatedFrame, reader.finish());
}
frame[frame.len - 1] ^= 1;
var source = std.Io.Reader.fixed(frame);
var reader = try Reader.init(std.testing.allocator, &source, .{ .buffer = &buffer });
defer reader.deinit();
var output = std.Io.Writer.Allocating.init(std.testing.allocator);
defer output.deinit();
try std.testing.expectError(error.ReadFailed, reader.reader.streamRemaining(&output.writer));
try std.testing.expectEqual(error.InvalidFrame, reader.failure.?);
try std.testing.expect(reader.lz4_error != null);
}
test "reader finish rejects unread plaintext" {
const frame = try testFrame("payload");
defer std.testing.allocator.free(frame);
var source = std.Io.Reader.fixed(frame);
var buffer: [16]u8 = undefined;
var reader = try Reader.init(std.testing.allocator, &source, .{ .buffer = &buffer });
defer reader.deinit();
try std.testing.expectError(error.TrailingData, reader.finish());
}

View File

@ -0,0 +1,73 @@
const std = @import("std");
pub const Endian = enum {
big,
little,
};
pub const XxdOptions = struct {
wordSize: u32 = 8, // bits; must be a nonzero multiple of 8
// Preserve the existing convention: little prints bytes in input order;
// big reverses the bytes within each word. ASCII always uses input order.
endian: Endian = .little,
wordsPerGroup: u32 = 2,
groupsPerLine: u32 = 8,
groupSplit: u32 = 4, // extra space every N groups; 0 disables it
showAddress: bool = true,
showAscii: bool = false,
};
pub const Error = std.Io.Writer.Error || error{InvalidOptions};
/// Writes a hex dump. Does not allocate or flush the caller's writer.
pub fn xxdWrite(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) Error!void {
if (options.wordSize == 0 or options.wordSize % 8 != 0 or options.wordsPerGroup == 0 or options.groupsPerLine == 0) return error.InvalidOptions;
const bytes_per_word: usize = options.wordSize / 8;
const words_per_line = std.math.mul(usize, options.wordsPerGroup, options.groupsPerLine) catch return error.InvalidOptions;
const bytes_per_line = std.math.mul(usize, bytes_per_word, words_per_line) catch return error.InvalidOptions;
var offset: usize = 0;
while (offset < bytes.len) {
const row = bytes[offset..][0..@min(bytes_per_line, bytes.len - offset)];
if (options.showAddress) try writer.print("{x:0>8}: ", .{offset});
const word_count = if (options.showAscii) words_per_line else (row.len - 1) / bytes_per_word + 1;
for (0..word_count) |word_index| {
if (word_index > 0 and word_index % options.wordsPerGroup == 0) {
try writer.writeByte(' ');
const group_index = word_index / options.wordsPerGroup;
if (options.groupSplit != 0 and group_index % options.groupSplit == 0) {
try writer.writeByte(' ');
}
}
const start = @min(word_index * bytes_per_word, row.len);
const word = row[start..][0..@min(bytes_per_word, row.len - start)];
for (0..word.len) |i| {
const index = if (options.endian == .little) i else word.len - 1 - i;
try writeByteAsHex(word[index], writer);
}
if (options.showAscii) {
// Pad missing bytes so every row's ASCII starts in the same column.
for (word.len..bytes_per_word) |_| try writer.writeAll(" ");
}
}
if (options.showAscii) {
try writer.writeAll(" | ");
for (row) |byte| try writer.writeByte(if (byte >= 0x20 and byte <= 0x7e) byte else '.');
}
try writer.writeByte('\n');
offset += row.len;
}
}
/// Hex plus printable ASCII, with '.' for control and non-ASCII bytes.
/// For separate byte columns, set wordsPerGroup = 1 and groupsPerLine = 16.
pub fn xxdWriteAscii(writer: *std.Io.Writer, bytes: []const u8, options: XxdOptions) Error!void {
var ascii_options = options;
ascii_options.showAscii = true;
try xxdWrite(writer, bytes, ascii_options);
}
inline fn writeByteAsHex(byte: u8, writer: *std.Io.Writer) std.Io.Writer.Error!void {
const digits = "0123456789ABCDEF";
try writer.writeAll(&.{ digits[byte >> 4], digits[byte & 0xf] });
}