PMTiles
Read PMTiles v3 single-file tile archives: header, directories, tile lookup and tile bytes.
Implements PMTiles. Spec v0.2.0; every port passes the same 81 conformance cases.
Swift 0.2.0Nim v0.2.0Zig v0.2.0
Install
.package(url: "https://github.com/Xenoglyphiq/pmtiles-swift", from: "0.2.0"),
// in your targetdependencies: [.product(name: "PMTiles", package: "pmtiles-swift"), .product(name: "PMTilesIO", package: "pmtiles-swift")]nimble install pmtileszig fetch --save git+https://github.com/Xenoglyphiq/pmtiles-zig#v0.2.0const pmtiles = b.dependency("pmtiles", .{ .target = target, .optimize = optimize });exe.root_module.addImport("pmtiles", pmtiles.module("pmtiles"));exe.root_module.addImport("pmtiles_io", pmtiles.module("pmtiles_io"));Examples
The same three examples exist in every port, runnable as-is from each repository's examples/ folder.
Print an archive's header
// Canonical example `inspect_archive`: decode a local archive's header and print it.// Usage: swift run inspect_archive [path]import Foundationimport PMTiles
let path = CommandLine.arguments.dropFirst().first ?? ".spec/conformance/cases/archives/small.pmtiles"guard let file = FileHandle(forReadingAtPath: path) else { print("cannot open \(path)") exit(1)}let first127 = [UInt8](file.readData(ofLength: 127))do { let h = try decodeHeader(first127) print("zooms \(h.minZoom)-\(h.maxZoom), tile type \(h.tileType), tile compression \(h.tileCompression)") print("bounds lon \(h.bounds.minLon)...\(h.bounds.maxLon), lat \(h.bounds.minLat)...\(h.bounds.maxLat)") print("center (\(h.center.lon), \(h.center.lat)) at zoom \(h.centerZoom)")} catch { print("not a PMTiles v3 archive: \(error)") exit(1)}## Canonical example `inspect_archive`: read the first 127 bytes of a local## archive, decode the header, and print the zooms, bounds and tile type.#### Usage: inspect_archive [path] (default: the conformance suite's small archive)import std/osimport pmtiles
let path = if paramCount() >= 1: paramStr(1) else: currentSourcePath().parentDir.parentDir / ".spec/conformance/cases/archives/small.pmtiles"
try: var head = newSeq[byte](headerSize) let f = open(path) let n = f.readBytes(head, 0, headerSize) f.close() head.setLen(n) let h = decodeHeader(head) echo "zooms ", h.minZoom, "-", h.maxZoom, " (center zoom ", h.centerZoom, ")" echo "bounds lon ", h.bounds.minLon, " to ", h.bounds.maxLon, ", lat ", h.bounds.minLat, " to ", h.bounds.maxLat echo "tile type ", h.tileType, ", tile compression ", h.tileCompressionexcept IOError as e: stderr.writeLine "cannot read ", path, ": ", e.msg quit 1except PMTilesError as e: stderr.writeLine e.kind, ": ", e.code quit 1//! Canonical example `inspect_archive`: read the first 127 bytes of a local//! archive, decode the header, and print the zooms, bounds and tile type.//!//! Usage: `inspect_archive [path]` (default: the spec's small test archive).const std = @import("std");const pmtiles = @import("pmtiles");
pub fn main(init: std.process.Init) !void { const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); const path = if (args.len > 1) args[1] else ".spec/conformance/cases/archives/small.pmtiles";
const file = try std.Io.Dir.cwd().openFile(io, path, .{}); defer file.close(io); var buf: [pmtiles.header_len]u8 = undefined; const n = try file.readPositionalAll(io, &buf, 0);
var diag: pmtiles.Diagnostics = .{}; const h = pmtiles.decodeHeader(buf[0..n], &diag) catch |err| { std.debug.print("{s}: {s}\n", .{ @errorName(err), diag.code }); return err; }; const tile_type = std.enums.tagName(pmtiles.TileType, h.tile_type) orelse "unknown"; std.debug.print("{s}\n zooms {d}-{d}\n bounds lon {d}..{d}, lat {d}..{d}\n tile type {s}\n", .{ path, h.min_zoom, h.max_zoom, h.bounds.min_lon, h.bounds.max_lon, h.bounds.min_lat, h.bounds.max_lat, tile_type, });}Fetch one tile by z/x/y
// Canonical example `fetch_one_tile`: read one tile by z/x/y from a local archive.// Usage: swift run fetch_one_tile [path] [z/x/y]import PMTilesIO
let args = Array(CommandLine.arguments.dropFirst())let path = args.first ?? ".spec/conformance/cases/archives/small.pmtiles"let parts = (args.count > 1 ? args[1] : "2/1/3").split(separator: "/").compactMap { UInt32($0) }let coord = TileCoord(z: UInt8(parts[0]), x: parts[1], y: parts[2])
do { let source = try FileSource(path: path) if let tile = try await getTile(source, coord) { print("\(coord.z)/\(coord.x)/\(coord.y): \(tile.count) bytes") } else { print("\(coord.z)/\(coord.x)/\(coord.y): not found") }} catch { print("error: \(error)")}## Canonical example `fetch_one_tile`: open a local archive as a source, fetch## one tile, and print its byte count or "not found".#### Usage: fetch_one_tile [path] [z/x/y] (default: the conformance suite's small## archive, tile 2/1/3)import std/[os, strutils]import pmtiles/io
let path = if paramCount() >= 1: paramStr(1) else: currentSourcePath().parentDir.parentDir / ".spec/conformance/cases/archives/small.pmtiles"let arg = if paramCount() >= 2: paramStr(2) else: "2/1/3"
proc parseCoord(s: string): TileCoord = let p = s.split('/') if p.len != 3: raise newException(ValueError, "expected z/x/y") let (z, x, y) = (parseUInt(p[0]), parseUInt(p[1]), parseUInt(p[2])) if z > 255 or x > high(uint32) or y > high(uint32): raise newException(ValueError, "out of range") TileCoord(z: uint8(z), x: uint32(x), y: uint32(y))
try: let coord = parseCoord(arg) let tile = getTile(fileSource(path), coord) if tile.isSome: echo coord.z, "/", coord.x, "/", coord.y, ": ", tile.get.len, " bytes" else: echo coord.z, "/", coord.x, "/", coord.y, ": not found"except ValueError: stderr.writeLine "expected z/x/y, got ", arg quit 2except PMTilesError as e: stderr.writeLine e.kind, ": ", e.code quit 1//! Canonical example `fetch_one_tile`: open a local archive as a source,//! fetch one tile by z/x/y, and print its byte count or "not found".//!//! Usage: `fetch_one_tile [path [z/x/y]]` (default: the spec's small test//! archive, tile 2/1/3).const std = @import("std");const pmtiles = @import("pmtiles");const pmtiles_io = @import("pmtiles_io");
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); const path = if (args.len > 1) args[1] else ".spec/conformance/cases/archives/small.pmtiles"; const zxy = if (args.len > 2) args[2] else "2/1/3";
var parts = std.mem.splitScalar(u8, zxy, '/'); const coord: pmtiles.TileCoord = .{ .z = try std.fmt.parseInt(u8, parts.next().?, 10), .x = try std.fmt.parseInt(u32, parts.next() orelse return error.BadCoord, 10), .y = try std.fmt.parseInt(u32, parts.next() orelse return error.BadCoord, 10), };
var file: pmtiles_io.FileSource = try .open(io, std.Io.Dir.cwd(), path); defer file.close();
var diag: pmtiles.Diagnostics = .{}; const tile = pmtiles_io.getTile(gpa, file.source(), coord, .{}, &diag) catch |err| { std.debug.print("{s}: {s}\n", .{ @errorName(err), diag.code }); return err; }; if (tile) |bytes| { defer gpa.free(bytes); std.debug.print("tile {s}: {d} bytes\n", .{ zxy, bytes.len }); } else { std.debug.print("tile {s}: not found\n", .{zxy}); }}Read metadata over HTTP
// Canonical example `remote_metadata`: read an archive's metadata over HTTP range requests.// Usage: swift run remote_metadata [url]import Foundationimport PMTilesIO
let url = URL(string: CommandLine.arguments.dropFirst().first ?? "https://pmtiles.io/protomaps(vector)ODbL_firenze.pmtiles")!do { print(try await readMetadata(HTTPSource(url: url)))} catch { print("error: \(error)")}## Canonical example `remote_metadata`: read an archive's metadata over HTTP## range requests and print the JSON. Build with `-d:ssl` (examples/config.nims## sets it).#### Usage: remote_metadata [url]import std/osimport pmtiles/io
let url = if paramCount() >= 1: paramStr(1) else: "https://pmtiles.io/protomaps(vector)ODbL_firenze.pmtiles"
try: echo readMetadata(httpSource(url))except PMTilesError as e: stderr.writeLine e.kind, ": ", e.code, " (", e.msg, ")" quit 1//! Canonical example `remote_metadata`: read an archive's metadata over HTTP//! range requests and print the JSON.//!//! `HttpSource` is a complete `Source` built on `std.http.Client`: each read//! is one `GET` with a `Range` header. It asks for `Accept-Encoding: identity`,//! because some servers otherwise gzip the response and apply the range to//! the gzipped bytes. A `200` reply (range ignored) is the whole file, which//! it slices itself; `416` means the range starts past the end.//!//! Usage: `remote_metadata [url]`. Needs the network.const std = @import("std");const pmtiles = @import("pmtiles");const pmtiles_io = @import("pmtiles_io");
const default_url = "https://pmtiles.io/protomaps(vector)ODbL_firenze.pmtiles";
const HttpSource = struct { client: *std.http.Client, url: []const u8,
fn source(self: *HttpSource) pmtiles_io.Source { return .{ .ptr = self, .vtable = &vtable }; }
const vtable: pmtiles_io.Source.VTable = .{ .readRange = readRange };
fn readRange(ptr: *anyopaque, gpa: std.mem.Allocator, offset: u64, len: u64) pmtiles_io.Source.ReadError![]u8 { const self: *HttpSource = @ptrCast(@alignCast(ptr)); if (len == 0) return gpa.alloc(u8, 0); const n = std.math.cast(usize, len) orelse return error.ReadFailed; const last = std.math.add(u64, offset, len - 1) catch return error.ReadFailed;
var range_buf: [64]u8 = undefined; const range = std.fmt.bufPrint(&range_buf, "bytes={d}-{d}", .{ offset, last }) catch unreachable; const uri = std.Uri.parse(self.url) catch return error.ReadFailed; var req = self.client.request(.GET, uri, .{ .headers = .{ .accept_encoding = .{ .override = "identity" } }, .extra_headers = &.{.{ .name = "Range", .value = range }}, // A 200 reply may be left half-read, so don't reuse connections. .keep_alive = false, }) catch return error.ReadFailed; defer req.deinit(); req.sendBodiless() catch return error.ReadFailed; var redirect_buf: [8 * 1024]u8 = undefined; var response = req.receiveHead(&redirect_buf) catch return error.ReadFailed; if (response.head.content_encoding != .identity) return error.ReadFailed;
var transfer_buf: [4096]u8 = undefined; const body = response.reader(&transfer_buf); switch (response.head.status) { .partial_content => {}, // The server ignored the range and sent the whole file. .ok => body.discardAll64(offset) catch |err| switch (err) { error.EndOfStream => return gpa.alloc(u8, 0), error.ReadFailed => return error.ReadFailed, }, .range_not_satisfiable => return gpa.alloc(u8, 0), else => return error.ReadFailed, } const buf = try gpa.alloc(u8, n); errdefer gpa.free(buf); const got = body.readSliceShort(buf) catch return error.ReadFailed; return gpa.realloc(buf, got); }};
pub fn main(init: std.process.Init) !void { const gpa = init.gpa; const io = init.io; const args = try init.minimal.args.toSlice(init.arena.allocator()); const url = if (args.len > 1) args[1] else default_url;
var client: std.http.Client = .{ .allocator = gpa, .io = io }; defer client.deinit(); var http: HttpSource = .{ .client = &client, .url = url };
var diag: pmtiles.Diagnostics = .{}; const metadata = pmtiles_io.readMetadata(gpa, http.source(), .{}, &diag) catch |err| { std.debug.print("{s}: {s}\n", .{ @errorName(err), diag.code }); return err; }; defer gpa.free(metadata); std.debug.print("{s}\n", .{metadata});}Ports
| Language | Package | Release | Spec | Conformance |
|---|---|---|---|---|
| Swift | PMTiles | 0.2.0 | v0.2.0 | core ✓ io ✓ full ✓ (81/81) |
| Nim | pmtiles | v0.2.0 | v0.2.0 | core ✓ io ✓ full ✓ (81/81) |
| Zig | pmtiles | v0.2.0 | v0.2.0 | core ✓ io ✓ full ✓ (81/81) |
Performance
Median time, and ratio to the reference implementation measured in the same session. The spec's target is within 2×.
| Port | get_tile, PMTilesReader | get_tile, stateless | get_tile, Reader |
|---|---|---|---|
| Reference | Rust pmtiles 0.24.1: 165.1 ms | Rust pmtiles 0.24.1: 165.1 ms | Rust pmtiles 0.24.1: 165.1 ms |
| Swift | 344.9 ms (2.09×) | 359.6 ms (2.18×) | — |
| Nim | — | 222.8 ms (1.35×) | — |
| Zig | — | 280.4 ms (1.70×) | 272.7 ms (1.65×) |
Spec and source
- Behavior spec and machine-readable contract
- Conformance cases (81)
- Decisions and benchmark method
- Swift port: Xenoglyphiq/pmtiles-swift
- Nim port: Xenoglyphiq/pmtiles-nim
- Zig port: Xenoglyphiq/pmtiles-zig