Sample code for 30+ languages & platforms
Zig Requires Chilkat v11.0.0+

Compress String Feed to Base64

See more Compression Examples

This example receives incoming text data in chunks, compresses as a stream, and accumulates the compressed data in base64.

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 assumes the Chilkat API to have been previously unlocked.
    // See Global Unlock Sample for sample code.

    const sb_compressed_base64 = try chilkat.StringBuilder.init();
    defer sb_compressed_base64.deinit();

    const compress = try chilkat.Compression.init();
    defer compress.deinit();
    compress.setAlgorithm("deflate");
    compress.setCharset("utf-8");
    compress.setEncodingMode("base64");

    compress.setFirstChunk(true);
    compress.setLastChunk(false);

    const bd_compressed = try chilkat.BinData.init();
    defer bd_compressed.deinit();
    const sb_uncompressed_chunk = try chilkat.StringBuilder.init();
    defer sb_uncompressed_chunk.deinit();

    var i: i32 = 0;
    i = 0;
    while (i <= 24) : (i += 1) {
        if (i == 24) {
            compress.setLastChunk(true);
        }

        sb_uncompressed_chunk.clear();
        sb_uncompressed_chunk.appendInt(i) catch {};
        sb_uncompressed_chunk.append(": This is a line of data to be compressed...\r\n") catch {};

        compress.compressSb(sb_uncompressed_chunk, bd_compressed) catch {};

        compress.setFirstChunk(false);
    }

    std.debug.print("The base64 encoded compressed text:\n", .{});
    std.debug.print("{s}\n", .{try bd_compressed.getEncoded(alloc, "base64")});

    // Decompress in one call:
    const original_text = try compress.decompressStringENC(alloc, try bd_compressed.getEncoded(alloc, "base64"));
    std.debug.print("{s}\n", .{original_text});
}