GzipLib — GZIP/Deflate Compression

Compress and decompress data using the GZIP/deflate algorithm. Ideal for compressing single data streams (strings or files) — widely used in web protocols, file storage, and data transmission. 10 functions.

CategoryCountDescription
Error Handling1gziperror
String Compression3gzip$, gzipex$, gunzip$
File Compression3gzipfile, gzipfileex, gunzipfile
Utility3gzipratio, gzipsize, gzipcsize
FeatureDescription
Compression Levels1 (fastest) to 9 (best), default 6
String OutputCompressed strings are Base64-encoded for text-safe handling
File FormatCreates/reads ZLib-compressed .gz files
UTF-8String functions properly handle international characters
Error Codes6 error codes via gziperror()

Error Handling

All functions set an internal error code retrievable with gziperror().

CodeConstantDescription
0ERR_NONENo error
1ERR_COMPRESSIONCompression failed
2ERR_DECOMPRESSIONDecompression failed
3ERR_INVALID_ARGUMENTInvalid argument (empty input where not allowed)
4ERR_FILE_ERRORFile read/write error
5ERR_INVALID_LEVELInvalid compression level (must be 1–9)
FunctionSignatureDescription
gziperror()gziperror@Error code from last GzipLib operation (0–5)
╯ plan9basic
compressed$ = gzip$("Hello World")
if gziperror() <> 0 then
    println "Compression failed: "; gziperror()
endif

String Compression

FunctionSignatureDescription
gzip$(string$)gzip$@$Compress string with default level (6), returns Base64-encoded data
gzipex$(string$, level)gzipex$@$nCompress with specific level (1–9), returns Base64-encoded data
gunzip$(compressed$)gunzip$@$Decompress Base64-encoded GZIP data back to original string
╯ plan9basic
' Default compression (level 6)
original$ = "Hello World! This is a test string."
compressed$ = gzip$(original$)
println "Original: "; len(original$)
println "Compressed: "; len(compressed$)

' Decompress and verify
restored$ = gunzip$(compressed$)
if original$ = restored$ then
    println "Round-trip successful!"
endif
╯ plan9basic
' Compare compression levels
data$ = "Lorem ipsum dolor sit amet, consectetur adipiscing elit..."

fast$ = gzipex$(data$, 1)
println "Level 1 (fast): "; len(fast$); " chars"

best$ = gzipex$(data$, 9)
println "Level 9 (best): "; len(best$); " chars"
LevelSpeedCompressionUse Case
1FastestLowestReal-time streaming, large volumes
6BalancedGoodDefault — general purpose
9SlowestBestArchival, bandwidth-critical
ⓘ Note: String compression functions return Base64-encoded data for safe handling in text formats (JSON, XML, databases). The actual compressed binary data is smaller than the Base64 representation.

File Compression

FunctionSignatureDescription
gzipfile(source$, dest$)gzipfile@$$Compress file to .gz with default level (1=success, 0=failure)
gzipfileex(source$, dest$, level)gzipfileex@$$nCompress file with specific level 1–9 (1=success, 0=failure)
gunzipfile(source$, dest$)gunzipfile@$$Decompress .gz file (1=success, 0=failure)
╯ plan9basic
' Compress a file (default level)
if gzipfile("document.txt", "document.txt.gz") = 1 then
    println "File compressed!"
else
    println "Failed: "; gziperror()
endif

' Compress with maximum compression
result = gzipfileex("largefile.dat", "largefile.dat.gz", 9)
if result = 1 then
    println "Compressed with max compression"
endif

' Decompress
if gunzipfile("archive.txt.gz", "archive.txt") = 1 then
    println "File decompressed!"
else
    println "Failed: "; gziperror()
endif
⚠ Warning: File operations set ERR_FILE_ERROR (4) if the source file cannot be read or the destination cannot be written. Always check gziperror() on failure.

Utility Functions

FunctionSignatureDescription
gzipratio(original$, compressed$)gzipratio@$$Compression ratio (compressed/original). <1.0 = compression, >1.0 = expansion
gzipsize(string$)gzipsize@$Size in bytes of string (UTF-8 encoded)
gzipcsize(compressed$)gzipcsize@$Actual compressed size in bytes (before Base64 encoding)
╯ plan9basic
text$ = "The quick brown fox jumps over the lazy dog. "
text$ = text$ + text$ + text$ + text$

compressed$ = gzip$(text$)

println "Original size:   "; gzipsize(text$); " bytes"
println "Compressed size: "; gzipcsize(compressed$); " bytes"
println "Base64 length:   "; len(compressed$); " chars"

ratio = gzipratio(text$, compressed$)
println "Ratio: "; ratio
println "Space saved: "; int((1 - ratio) * 100); "%"
ⓘ Note: gzipcsize() reports the actual binary compressed size, which is smaller than the Base64 string length. Use this for accurate compression statistics.

Complete Examples

Basic String Compression

╯ string_compress.bas
' Basic string compression with verification
println "=== GZIP String Compression ==="

original$ = "The quick brown fox jumps over the lazy dog. "
original$ = original$ + original$ + original$ + original$

println "Original length: "; len(original$)

compressed$ = gzip$(original$)
if gziperror() <> 0 then
    println "Error: "; gziperror()
    end
endif

println "Compressed (Base64): "; len(compressed$)
println "Actual compressed: "; gzipcsize(compressed$); " bytes"

ratio = gzipratio(original$, compressed$)
println "Ratio: "; ratio
println "Space saved: "; int((1 - ratio) * 100); "%"

restored$ = gunzip$(compressed$)
if original$ = restored$ then
    println ""
    println "Verification: SUCCESS"
else
    println ""
    println "Verification: FAILED"
endif

File Compression Utility

╯ file_compress.bas
' Interactive file compression
let filename$ = ""

function onFilename$(result$)
    if result$ = "" then
        println "No filename provided."
        return ""
    endif
    if fileexists(result$, 0) = 0 then
        println "File not found: "; result$
        return ""
    endif
    filename$ = result$
    input "Compression", "Level (1-9, default 6):", "6", onLevel$
    return ""
endfunction

function onLevel$(result$) local level, outfile$
    if result$ = "" then
        level = 6
    else
        level = val(result$)
        if level < 1 or level > 9 then
            level = 6
        endif
    endif
    
    outfile$ = filename$ + ".gz"
    println "Compressing "; filename$; " -> "; outfile$
    println "Level: "; level
    
    if gzipfileex(filename$, outfile$, level) = 1 then
        println "Success!"
    else
        println "Failed: "; gziperror()
    endif
    return ""
endfunction

println "=== File Compression ==="
input "Compress", "File to compress:", "", onFilename$

Compress JSON Data

╯ compress_json.bas
' Compress JSON for storage/transmission
println "=== Compress JSON ==="

json# = json_object#()
json_sets#(json#, "name", "John Doe")
json_setn#(json#, "age", 30)
json_sets#(json#, "email", "john@example.com")
json_sets#(json#, "city", "New York")

jsonStr$ = json_stringify$(json#)
println "JSON: "; jsonStr$

compressed$ = gzip$(jsonStr$)

println "Original: "; gzipsize(jsonStr$); " bytes"
println "Compressed: "; gzipcsize(compressed$); " bytes"
println ""
println "Base64 for transmission:"
println compressed$

Batch File Compression

╯ batch_compress.bas
' Compress multiple files
println "=== Batch Compression ==="

files# = sdim#(5)
files#$[1] = "readme.txt"
files#$[2] = "data.csv"
files#$[3] = "config.ini"
files#$[4] = "log.txt"
files#$[5] = "notes.md"

successCount = 0
failCount = 0

for i = 1 to 5
    filename$ = files#$[i]
    if fileexists(filename$, 0) = 1 then
        outfile$ = filename$ + ".gz"
        if gzipfile(filename$, outfile$) = 1 then
            println "OK:   "; filename$
            successCount = successCount + 1
        else
            println "FAIL: "; filename$; " (Error: "; gziperror(); ")"
            failCount = failCount + 1
        endif
    else
        println "SKIP: "; filename$; " (not found)"
    endif
next

println ""
println "Done: "; successCount; " compressed, "; failCount; " failed"

Technical Notes

TopicDetails
Base64 encodingString functions return Base64-encoded data for safe use in text formats. Actual compressed bytes are ~33% smaller than the Base64 string length.
Compression levels1 = fastest/largest, 6 = default/balanced, 9 = best/slowest. Differences are most noticeable on large data.
MemoryLarge strings or files may require significant memory during compression/decompression.
File formatgzipfile / gunzipfile create/read ZLib-compressed files compatible with standard GZIP utilities.
UTF-8String functions use UTF-8 encoding, properly handling international characters.
Small dataVery small strings may actually expand after compression (ratio > 1.0) due to compression overhead.

Quick Reference

FunctionSignatureDescription
gziperror()gziperror@Last error code (0–5)
gzip$(string$)gzip$@$Compress string (default level 6, Base64 output)
gzipex$(string$, level)gzipex$@$nCompress with level 1–9 (Base64 output)
gunzip$(compressed$)gunzip$@$Decompress Base64 GZIP data to string
gzipfile(src$, dst$)gzipfile@$$Compress file to .gz (1/0)
gzipfileex(src$, dst$, level)gzipfileex@$$nCompress file with level (1/0)
gunzipfile(src$, dst$)gunzipfile@$$Decompress .gz file (1/0)
gzipratio(orig$, comp$)gzipratio@$$Compression ratio (<1.0 = compressed)
gzipsize(string$)gzipsize@$UTF-8 byte size of string
gzipcsize(compressed$)gzipcsize@$Actual compressed byte size (before Base64)

10 functions across 4 categories.