Grav v1.14.0

Zip

import "std/data" (included in import "std") · namespace std.data

ZIP archives, written (each entry stored or deflated, whichever is smaller) and read, compatible with zip/unzip, Python's zipfile and the rest (and so with .docx, .xlsx and .jar files, which are ZIPs). Reading checks each entry's CRC, inflates with a size limit (maxEntryBytes, 1 GiB by default) so a small archive cannot expand into gigabytes, and extractTo refuses names that would land outside its folder ("zip slip"). ZIP64 (over 4 GiB) is not supported.

grav
import "std"

fn main() {
    let z = new ZipWriter()
    z.addText("readme.txt", "hello")
    z.add("data/rows.csv", Bytes.fromString(Str.repeat("1,2,3\n", 1000)))
    let bytes = z.toBytes()

    let r = ZipReader.open(bytes)
    for (e in r.entries()) { print("${e.name}: ${e.size} bytes, method ${e.method}") }
    print(r.readText("readme.txt"))
    print(bytes.size() < 300)                 // 6 KB of rows in under 300 bytes
}
Output
readme.txt: 5 bytes, method 0
data/rows.csv: 6000 bytes, method 8
hello
true

class ZipLe

Little-endian numbers, as ZIP writes them.

Static members

  • static fn put(b: Bytes, v: long, width: int)
  • static fn get(b: Bytes, at: int, width: int) -> long

class ZipEntry

One file in an archive.

Constructors

  • new ZipEntry(name: string, method: int, crc: long, compressedSize: long, size: long, offset: long)

Fields

  • name: string
  • method: int — 0 stored, 8 deflated.
  • crc: long
  • compressedSize: long
  • size: long
  • offset: long
  • dosTime: int = 0 — MS-DOS date and time, as stored.
  • dosDate: int = 0

Methods

  • fn isDirectory() -> bool

class ZipWriter

Constructors

  • new ZipWriter()

Methods

  • fn add(name: string, data: Bytes, compress: bool = true) -> ZipWriter — Adds a file (deflated when that makes it smaller, unless compress is false).
  • fn addText(name: string, text: string) -> ZipWriter
  • fn addDirectory(name: string) -> ZipWriter — An empty directory entry ("logs/").
  • fn toBytes() -> Bytes — The archive.

class ZipReader

Static members

  • static fn open(data: Bytes) -> ZipReader — Reads an archive's directory; ValueError when it is not a ZIP.

Fields

  • maxEntryBytes: long = 1 << 30 — The largest entry read() inflates (bytes).

Methods

  • fn entries() -> Array<ZipEntry>
  • fn names() -> Array<string>
  • fn has(name: string) -> bool
  • fn entry(name: string) -> ZipEntry
  • fn read(name: string) -> Bytes — An entry's bytes (CRC-checked); ValueError when missing or corrupt.
  • fn readText(name: string) -> string
  • fn readEntry(e: ZipEntry) -> Bytes
  • fn extractTo(dir: string) -> Array<string> — Writes every entry under dir (folders made as needed); refuses names that would land outside it ("../", absolute paths). The paths written.

Edit this page on GitHub