Sample code for 30+ languages & platforms
Zig

Compress Text from StringBuilder to Gzip (BinData Output)

See more Gzip Examples

This example demonstrates how to use the CompressSb method to compress text stored in a StringBuilder into Gzip format.

The text is first converted to its byte representation using the specified character set (in this case, UTF-8). These bytes are then compressed, and the resulting Gzip data is written to a BinData object in memory.

This approach is useful when working with dynamically generated text that you want to compress without first writing it to a file. The example also shows how the compressed data can optionally be saved to a .gz file.

Chilkat Zig Downloads

Zig
const std = @import("std");
const chilkat = @import("chilkat");

pub fn main(init: std.process.Init) !void {
    const alloc = init.arena.allocator();

    // This example demonstrates how to compress text contained in a StringBuilder
    // into Gzip format, storing the compressed result in a BinData object.

    const gzip = try chilkat.Gzip.init();
    defer gzip.deinit();
    const sb = try chilkat.StringBuilder.init();
    defer sb.deinit();
    const bd = try chilkat.BinData.init();
    defer bd.deinit();

    // Add some text to the StringBuilder:
    sb.append("The quick brown fox jumps over the lazy dog.") catch {};

    // Compress the text using UTF-8 encoding:
    gzip.compressSb(sb, "utf-8", bd) catch {
        std.debug.print("{s}\n", .{try gzip.getLastErrorText(alloc)});
        return;
    };

    // The BinData now contains the Gzip-compressed bytes.
    std.debug.print("Compression successful.\n", .{});
    std.debug.print("Compressed size (bytes): {d}\n", .{bd.getNumBytes()});

    // (Optional) Save to a .gz file:
    bd.writeFile("text.gz") catch {
        std.debug.print("{s}\n", .{try bd.getLastErrorText(alloc)});
        return;
    };

    std.debug.print("Gzip file written to text.gz\n", .{});
}