---
url: https://wvlet.org/uni/core/compression.md
---
# Compression

`Zstd` and `Gzip` compress byte arrays and files with no extra dependency. Parquet, Arrow, and
other formats use more codecs, listed [below](#codecs-by-format).

| API | JVM | Node.js | Browser | Native | Implementation |
|-----|-----|---------|---------|--------|----------------|
| `Zstd`, byte arrays | Yes | Yes | Yes | Yes | Pure Scala |
| `Zstd`, files | Yes | Yes | No | Yes | Pure Scala |
| `Gzip`, byte arrays and files | Yes | Yes | No | Yes | The platform's zlib |

## Zstandard

`Zstd` compresses in pure Scala on every platform, including browsers (byte arrays only there).

```scala
import wvlet.uni.io.Zstd

// In-memory compression, with an optional level from 1 (fastest) to 22 (default: 3)
val data = "hello world".getBytes("UTF-8")
val zstdData = Zstd.compress(data, level = 9)
val restored = Zstd.decompress(zstdData)

// Set the largest decompressed size to accept (default: 256 MiB)
val limited = Zstd.decompress(zstdData, maxSize = 64 * 1024 * 1024)

// Files readable and writable with the zstd command. Whole files are held in memory
Zstd.compressFile("data.json", "data.json.zst")
Zstd.decompressFile("data.json.zst", "data.json")
```

Levels 10 to 22 are accepted and compress as level 9. Decompression reads all frames of the input
and verifies their checksums; `compress` writes no checksum. Data over `maxSize` fails with
`ZstdSizeLimitException`. Malformed data and frames that need a dictionary fail with its parent
`ZstdException`, an `IOException`.

## Gzip

```scala
import wvlet.uni.io.Gzip

// In-memory compression
val data = "hello world".getBytes("UTF-8")
val gzipped = Gzip.compress(data)
val original = Gzip.decompress(gzipped)

// Files: streamed on the JVM and Native, and read whole on Node.js
Gzip.compressFile("large.txt", "large.txt.gz")
Gzip.decompressFile("large.txt.gz", "large.txt")
```

`Gzip.decompress` has no size limit. Corrupt data fails with an `IOException`.

## Codecs by format

These codecs are built into Uni. Readers detect the codec, and writers take it as an option.

| Codec | Parquet | Arrow IPC (write) | Iceberg Avro metadata (read) |
|-------|---------|-------------------|------------------------------|
| Zstandard | Read, write | Yes | Yes |
| Snappy | Read, write (default) | No | Yes |
| LZ4 | Read, write as `LZ4_RAW`; read the deprecated `LZ4` | LZ4 frames | No |
| Gzip / DEFLATE | Gzip: read, write (writes not in browsers) | No | DEFLATE |
| Brotli | Read | No | No |

Elsewhere:

* [MPC1 files](/cloud/plazma) use gzip by default, or no compression.
* [HTTP servers](/http/server#request-decompression) decode gzip and deflate request bodies.

See [Parquet](/cloud/parquet) and [Arrow IPC](/cloud/arrow) for their compression options.
