SPB Git

Repository Public BSD-3-Clause

PMTilesHeader.swift 12.8 KB 257 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project          : ORIX Maps9// File             : Infrastructure/package-builder/Sources/PackageBuilderKit/PMTilesHeader.swift10// Module           : PackageBuilderKit11// Repository       : https://git.spboucher.ai/orix-maps12// Created          : 2026-11-2513// Last Modified    : 2026-11-2514//15// =============================================================================16// AUTHOR & PROFESSIONAL AFFILIATION17// =============================================================================18//19// Author           : Simon-Pierre Boucher20// Position         : Professor of Finance21// Institution      : Université du Québec en Outaouais (UQO)22// Department       : Département des sciences administratives23// Organization     : SP Boucher24//25// Website          : https://spboucher.ai26// Git              : https://git.spboucher.ai27//28// =============================================================================29// OFFICIAL CONTACT DIRECTORY30// =============================================================================31//32// General          : info@spboucher.ai33// Professional     : contact@spboucher.ai34// Direct           : simon@spboucher.ai35// Research         : research@spboucher.ai36// Development      : dev@spboucher.ai37// Support          : support@spboucher.ai38// Security/Admin   : admin@spboucher.ai39// Notifications    : notifications@spboucher.ai40//41// Preferred Contact: support@spboucher.ai42//43// =============================================================================44// COPYRIGHT & INTELLECTUAL PROPERTY45// =============================================================================46//47// Copyright (c) 202648// Simon-Pierre Boucher49//50// All rights reserved where applicable.51//52// This file is governed by the applicable project license,53// copyright notices, institutional agreements and relevant law.54//55// Unless expressly authorized by the applicable license or56// rights holder, copying, redistribution, sublicensing,57// publication and commercial exploitation are not permitted.58//59// Existing third-party rights and notices remain unaffected.60//61// =============================================================================62// CONFIDENTIALITY & SECURITY63// =============================================================================64//65// Classification   : Public66// Distribution     : Public repository; use is governed by the project license67// Security Contact : admin@spboucher.ai68//69// Access to this source does not independently grant permission70// to redistribute or disclose confidential materials.71//72// Do not embed credentials, private keys, access tokens,73// certificates or confidential personal information.74//75// =============================================================================76// LICENSE & MAINTENANCE77// =============================================================================78//79// License          : Proprietary, all rights reserved (see license file)80// License File     : LICENSE81// Maintainer       : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788import Foundation89import ORIXGeoCore9091/// The fixed 127-byte header of a PMTiles version 3 archive (https://github.com/protomaps/PMTiles, spec v3).92/// Only the header is read: the builder needs the zoom range and the bounds, nothing else.93public struct PMTilesHeader: Sendable, Equatable {94    public static let length = 12795    public static let magic = Array("PMTiles".utf8)9697    public enum TileType: UInt8, Sendable { case unknown = 0, mvt = 1, png = 2, jpeg = 3, webp = 4, avif = 5 }9899    public var rootDirectoryOffset: UInt64100    public var rootDirectoryLength: UInt64101    public var metadataOffset: UInt64102    public var metadataLength: UInt64103    public var leafDirectoriesOffset: UInt64104    public var leafDirectoriesLength: UInt64105    public var tileDataOffset: UInt64106    public var tileDataLength: UInt64107    public var addressedTiles: UInt64108    public var tileEntries: UInt64109    public var tileContents: UInt64110    public var clustered: Bool111    public var internalCompression: UInt8112    public var tileCompression: UInt8113    public var tileTypeRaw: UInt8114    public var minZoom: UInt8115    public var maxZoom: UInt8116    public var minLonE7: Int32117    public var minLatE7: Int32118    public var maxLonE7: Int32119    public var maxLatE7: Int32120    public var centerZoom: UInt8121    public var centerLonE7: Int32122    public var centerLatE7: Int32123124    public var tileType: TileType { TileType(rawValue: tileTypeRaw) ?? .unknown }125126    /// The bounds of the archive, nil when the header does not carry usable ones.127    public var bounds: BoundingBox? {128        let box = BoundingBox(minLat: Double(minLatE7) / 1e7, minLon: Double(minLonE7) / 1e7, maxLat: Double(maxLatE7) / 1e7, maxLon: Double(maxLonE7) / 1e7)129        guard box.isValid, box.minLat < box.maxLat, box.minLon < box.maxLon else { return nil }130        return box131    }132133    public enum ParseError: Error, Sendable, Equatable {134        case io(String)135        /// The file is shorter than the 127-byte header.136        case tooShort(length: UInt64)137        case badMagic138        /// PMTiles version other than 3.139        case unsupportedVersion(UInt8)140        /// A section (root directory, metadata, leaf directories, tile data) does not fit in the file.141        case sectionOutOfFile(String)142        case invalidZoomRange(min: UInt8, max: UInt8)143        case missingRootDirectory144    }145146    /// Parses the header bytes. `fileSize`, when known, is used to check that every section lies inside the file.147    public static func parse(_ data: Data, fileSize: UInt64? = nil) throws(ParseError) -> PMTilesHeader {148        guard data.count >= length else { throw .tooShort(length: UInt64(data.count)) }149        let b = [UInt8](data.prefix(length))150        guard Array(b[0..<7]) == magic else { throw .badMagic }151        guard b[7] == 3 else { throw .unsupportedVersion(b[7]) }152        func u64(_ o: Int) -> UInt64 { (0..<8).reduce(UInt64(0)) { $0 | UInt64(b[o + $1]) << (8 * UInt64($1)) } }153        func i32(_ o: Int) -> Int32 { Int32(bitPattern: (0..<4).reduce(UInt32(0)) { $0 | UInt32(b[o + $1]) << (8 * UInt32($1)) }) }154        let h = PMTilesHeader(155            rootDirectoryOffset: u64(8), rootDirectoryLength: u64(16), metadataOffset: u64(24), metadataLength: u64(32),156            leafDirectoriesOffset: u64(40), leafDirectoriesLength: u64(48), tileDataOffset: u64(56), tileDataLength: u64(64),157            addressedTiles: u64(72), tileEntries: u64(80), tileContents: u64(88), clustered: b[96] == 1,158            internalCompression: b[97], tileCompression: b[98], tileTypeRaw: b[99], minZoom: b[100], maxZoom: b[101],159            minLonE7: i32(102), minLatE7: i32(106), maxLonE7: i32(110), maxLatE7: i32(114), centerZoom: b[118],160            centerLonE7: i32(119), centerLatE7: i32(123))161        guard h.minZoom <= h.maxZoom, h.maxZoom <= 30 else { throw .invalidZoomRange(min: h.minZoom, max: h.maxZoom) }162        guard h.rootDirectoryLength > 0, h.rootDirectoryOffset >= UInt64(length) else { throw .missingRootDirectory }163        if let fileSize {164            for (name, offset, size) in [("root directory", h.rootDirectoryOffset, h.rootDirectoryLength), ("metadata", h.metadataOffset, h.metadataLength),165                                         ("leaf directories", h.leafDirectoriesOffset, h.leafDirectoriesLength), ("tile data", h.tileDataOffset, h.tileDataLength)] {166                let (end, overflow) = offset.addingReportingOverflow(size)167                guard !overflow, end <= fileSize else { throw .sectionOutOfFile(name) }168            }169        }170        return h171    }172173    /// Reads the header of a file.174    public static func read(_ url: URL) throws(ParseError) -> PMTilesHeader {175        let handle: FileHandle176        do { handle = try FileHandle(forReadingFrom: url) } catch { throw .io(error.localizedDescription) }177        defer { try? handle.close() }178        let size: UInt64179        let data: Data180        do {181            size = try handle.seekToEnd()182            try handle.seek(toOffset: 0)183            data = try handle.read(upToCount: length) ?? Data()184        } catch { throw .io(error.localizedDescription) }185        return try parse(data, fileSize: size)186    }187188    public func encoded() -> Data {189        var b = [UInt8](repeating: 0, count: Self.length)190        b.replaceSubrange(0..<7, with: Self.magic)191        b[7] = 3192        func put64(_ v: UInt64, _ o: Int) { for i in 0..<8 { b[o + i] = UInt8(truncatingIfNeeded: v >> (8 * UInt64(i))) } }193        func put32(_ v: Int32, _ o: Int) { let u = UInt32(bitPattern: v); for i in 0..<4 { b[o + i] = UInt8(truncatingIfNeeded: u >> (8 * UInt32(i))) } }194        put64(rootDirectoryOffset, 8); put64(rootDirectoryLength, 16); put64(metadataOffset, 24); put64(metadataLength, 32)195        put64(leafDirectoriesOffset, 40); put64(leafDirectoriesLength, 48); put64(tileDataOffset, 56); put64(tileDataLength, 64)196        put64(addressedTiles, 72); put64(tileEntries, 80); put64(tileContents, 88)197        b[96] = clustered ? 1 : 0; b[97] = internalCompression; b[98] = tileCompression; b[99] = tileTypeRaw198        b[100] = minZoom; b[101] = maxZoom199        put32(minLonE7, 102); put32(minLatE7, 106); put32(maxLonE7, 110); put32(maxLatE7, 114)200        b[118] = centerZoom; put32(centerLonE7, 119); put32(centerLatE7, 123)201        return Data(b)202    }203}204205/// Synthetic files for tests and benchmarks. They are structurally valid but contain no map: never ship them.206public enum Fixtures {207    /// Writes a PMTiles v3 archive with a valid header, an empty root directory, empty JSON metadata and a tile data208    /// section of pseudo-random filler, of exactly `size` bytes (at least 130).209    public static func writePMTiles(to url: URL, size: Int, bounds: BoundingBox, minZoom: UInt8 = 0, maxZoom: UInt8 = 14, seed: UInt64 = 1) throws {210        let fixed = PMTilesHeader.length + 1 + 2211        let filler = max(0, size - fixed)212        let center = bounds.center.e7213        let header = PMTilesHeader(214            rootDirectoryOffset: UInt64(PMTilesHeader.length), rootDirectoryLength: 1, metadataOffset: UInt64(PMTilesHeader.length + 1), metadataLength: 2,215            leafDirectoriesOffset: UInt64(fixed), leafDirectoriesLength: 0, tileDataOffset: UInt64(fixed), tileDataLength: UInt64(filler),216            addressedTiles: 0, tileEntries: 0, tileContents: 0, clustered: true, internalCompression: 1, tileCompression: 1,217            tileTypeRaw: PMTilesHeader.TileType.mvt.rawValue, minZoom: minZoom, maxZoom: maxZoom,218            minLonE7: Int32((bounds.minLon * 1e7).rounded()), minLatE7: Int32((bounds.minLat * 1e7).rounded()),219            maxLonE7: Int32((bounds.maxLon * 1e7).rounded()), maxLatE7: Int32((bounds.maxLat * 1e7).rounded()),220            centerZoom: minZoom, centerLonE7: center.lon, centerLatE7: center.lat)221        var prefix = header.encoded()222        prefix.append(0)                      // root directory: zero entries (varint 0), no compression223        prefix.append(Data("{}".utf8))        // metadata224        try writeFile(url, prefix: prefix, fillerBytes: filler, seed: seed)225    }226227    /// Writes `size` pseudo-random bytes (stand-in for a search index or a routing graph in benchmarks).228    public static func writeBlob(to url: URL, size: Int, seed: UInt64 = 1) throws {229        try writeFile(url, prefix: Data(), fillerBytes: size, seed: seed)230    }231232    private static func writeFile(_ url: URL, prefix: Data, fillerBytes: Int, seed: UInt64) throws {233        FileManager.default.createFile(atPath: url.path, contents: nil)234        let handle = try FileHandle(forWritingTo: url)235        defer { try? handle.close() }236        try handle.write(contentsOf: prefix)237        var state = seed == 0 ? 0x9E37_79B9_7F4A_7C15 : seed238        var remaining = fillerBytes239        let chunkSize = 4 << 20240        while remaining > 0 {241            let n = min(chunkSize, remaining)242            var chunk = Data(count: n)243            chunk.withUnsafeMutableBytes { (buffer: UnsafeMutableRawBufferPointer) in244                var i = 0245                while i + 8 <= n {246                    state ^= state << 13; state ^= state >> 7; state ^= state << 17247                    buffer.storeBytes(of: state, toByteOffset: i, as: UInt64.self)248                    i += 8249                }250                while i < n { state ^= state << 13; state ^= state >> 7; state ^= state << 17; buffer[i] = UInt8(truncatingIfNeeded: state); i += 1 }251            }252            try handle.write(contentsOf: chunk)253            remaining -= n254        }255    }256}257
Files main
Menu

Theme