SPB Git

Repository Public

NativeContainer.swift 27.3 KB 500 lines swift

1// ORIX Docs2// File: Packages/ORIXDocsKit/Sources/DocFormats/NativeContainer.swift3// Description: The native .orixdoc container: a single ZIP holding a mimetype marker, a manifest with SHA-256 checksums,4//              document.json, image assets and preserved DOCX parts. Strict reading, validation and best-effort recovery.5//6// Author: Simon-Pierre Boucher7// Contact: contact@spboucher.ai8import Foundation9import CryptoKit10import Compression11import DocModel12import DocContainer1314/// The manifest stored as `manifest.json`.15public struct NativeManifest: Codable, Sendable, Equatable {16    public struct Generator: Codable, Sendable, Equatable {17        public var name: String18        public var version: String19    }20    public struct Entry: Codable, Sendable, Equatable {21        public enum Role: String, Codable, Sendable { case mimetype, document, asset, preserved }22        /// Entry name inside the ZIP.23        public var name: String24        public var size: Int25        /// Lower-case hexadecimal SHA-256 of the uncompressed bytes.26        public var sha256: String27        public var role: Role28        /// Asset id, or original DOCX part name of a preserved part.29        public var key: String?30        public var mimeType: String?31    }32    /// Version of the container layout (entry names, manifest fields).33    public var containerVersion: Int34    /// Version of the document.json schema (`DocumentModel.schemaVersion`).35    public var schemaVersion: Int36    public var generator: Generator37    public var created: Date38    public var entries: [Entry]39}4041public enum NativeContainer {42    public static let mimeType = "application/vnd.orix.docs+zip"43    public static let containerVersion = 144    public static let generatorVersion = "1.0"45    static let mimetypeEntry = "mimetype"46    static let manifestEntry = "manifest.json"47    static let documentEntry = "document.json"4849    // MARK: Writing5051    public static func write(_ doc: DocumentModel, generator: String = "ORIX Docs") throws -> Data {52        try write(doc, generator: generator, created: Date())53    }5455    static func write(_ doc: DocumentModel, generator: String, created: Date) throws -> Data {56        let json: Data57        do { json = try NativeJSON.encoder().encode(doc) } catch {58            throw FormatError.unreadable("the document cannot be encoded (\(error.localizedDescription))")59        }60        return try pack(documentJSON: json, schemaVersion: doc.schemaVersion, assets: doc.assets, preserved: doc.preservedParts,61                        generator: generator, created: created)62    }6364    /// Assembles a container around an already encoded document.json.65    static func pack(documentJSON: Data, schemaVersion: Int, assets: [String: Asset], preserved: [String: Data],66                     generator: String, created: Date, extraEntries: [(String, Data)] = []) throws -> Data {67        var payload: [(entry: NativeManifest.Entry, data: Data, compress: Bool)] = []68        func entry(_ name: String, _ data: Data, _ role: NativeManifest.Entry.Role, key: String? = nil, mime: String? = nil) -> NativeManifest.Entry {69            NativeManifest.Entry(name: name, size: data.count, sha256: sha256(data), role: role, key: key, mimeType: mime)70        }71        let mime = Data(mimeType.utf8)72        payload.append((entry(mimetypeEntry, mime, .mimetype), mime, false))73        payload.append((entry(documentEntry, documentJSON, .document), documentJSON, true))74        var names: Set<String> = [mimetypeEntry, manifestEntry, documentEntry]75        func unique(_ wanted: String) -> String {76            var name = wanted, n = 177            while names.contains(name) { n += 1; name = wanted + "~\(n)" }78            names.insert(name)79            return name80        }81        for id in assets.keys.sorted() {82            guard let asset = assets[id] else { continue }83            let name = unique("assets/\(safeFileName(id)).\(asset.fileExtension)")84            // Already-compressed image formats are stored; deflating them wastes time for nothing.85            let compressible = !["image/png", "image/jpeg", "image/gif", "image/heic", "image/webp"].contains(asset.mimeType)86            payload.append((entry(name, asset.data, .asset, key: id, mime: asset.mimeType), asset.data, compressible))87        }88        for (index, part) in preserved.keys.sorted().enumerated() {89            guard let data = preserved[part] else { continue }90            var relative = part91            while relative.hasPrefix("/") { relative.removeFirst() }92            let candidate = "preserved/" + relative93            let name = unique(isSafeEntryName(candidate) && !relative.isEmpty ? candidate : "preserved/_part\(index + 1).bin")94            payload.append((entry(name, data, .preserved, key: part), data, true))95        }96        let manifest = NativeManifest(containerVersion: containerVersion, schemaVersion: schemaVersion,97                                      generator: .init(name: generator, version: generatorVersion), created: created, entries: payload.map(\.entry))98        let manifestData = try NativeJSON.encoder(pretty: true).encode(manifest)99        do {100            var zip = ZipWriter()101            try zip.add(mimetypeEntry, mime, compress: false)102            try zip.add(manifestEntry, manifestData)103            for item in payload.dropFirst() { try zip.add(item.entry.name, item.data, compress: item.compress) }104            for (name, data) in extraEntries { try zip.add(name, data) }105            return zip.finalize()106        } catch let e as ZipError {107            throw FormatError.from(e)108        }109    }110111    // MARK: Strict reading112113    /// Strict read: any integrity failure throws FormatError.integrityCheckFailed.114    public static func read(_ data: Data) throws -> ImportResult { try read(data, migrator: .standard) }115116    static func read(_ data: Data, migrator: SchemaMigrator) throws -> ImportResult {117        let opened = try open(data, migrator: migrator)118        if let first = opened.problems.first { throw FormatError.integrityCheckFailed(first) }119        guard let json = opened.documentJSON else { throw FormatError.integrityCheckFailed("document.json is missing") }120        var warnings = WarningCollector()121        var doc = try decodeDocument(json, migrator: migrator, warnings: &warnings)122        doc.assets = opened.assets123        doc.preservedParts = opened.preserved124        if !opened.unknownEntries.isEmpty {125            warnings.add(.info, "Unknown container entries",126                         "\(opened.unknownEntries.count) entr\(opened.unknownEntries.count == 1 ? "y" : "ies") not listed in the manifest were ignored: "127                         + opened.unknownEntries.prefix(5).joined(separator: ", ") + (opened.unknownEntries.count > 5 ? "…" : ""))128        }129        reportMissingAssets(doc, &warnings)130        return ImportResult(document: doc, warnings: warnings.warnings)131    }132133    /// Human-readable integrity problems, empty when the container is sound.134    public static func validate(_ data: Data) -> [String] {135        do {136            let opened = try open(data, migrator: .standard)137            var problems = opened.problems138            if problems.isEmpty, let json = opened.documentJSON {139                var w = WarningCollector()140                do { _ = try decodeDocument(json, migrator: .standard, warnings: &w) } catch { problems.append(describe(error)) }141            }142            return problems143        } catch {144            return [describe(error)]145        }146    }147148    private struct Opened {149        var manifest: NativeManifest150        var documentJSON: Data?151        var assets: [String: Asset] = [:]152        var preserved: [String: Data] = [:]153        var unknownEntries: [String] = []154        var problems: [String] = []155    }156157    /// Opens the archive and checks every manifest entry. Structural failures throw; per-entry failures are collected.158    private static func open(_ data: Data, migrator: SchemaMigrator) throws -> Opened {159        guard data.count <= FormatLimits.maxContainerBytes else { throw FormatError.tooLarge("the file is larger than \(FormatLimits.maxContainerBytes) bytes") }160        let zip: ZipReader161        do { zip = try ZipReader(data: data) } catch let e as ZipError {162            if e == .notAZipArchive, looksLikeContainer(data) { throw FormatError.integrityCheckFailed("the file is truncated or its ZIP directory is damaged") }163            throw FormatError.from(e)164        }165        func bytes(_ name: String) throws -> Data? {166            do { return try zip.data(for: name) } catch let e as ZipError { throw FormatError.from(e) }167        }168        guard zip.names.first == mimetypeEntry, let mime = try? zip.data(for: mimetypeEntry) else {169            throw FormatError.unreadable("the file is not an ORIX Docs document (no mimetype marker)")170        }171        guard String(decoding: mime, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) == mimeType else {172            throw FormatError.unreadable("the file is not an ORIX Docs document (unexpected mimetype)")173        }174        guard zip.contains(manifestEntry) else { throw FormatError.integrityCheckFailed("manifest.json is missing") }175        guard let manifestData = try bytes(manifestEntry) else { throw FormatError.integrityCheckFailed("manifest.json is missing") }176        let manifest: NativeManifest177        do { manifest = try NativeJSON.decoder().decode(NativeManifest.self, from: manifestData) } catch {178            throw FormatError.integrityCheckFailed("manifest.json cannot be decoded")179        }180        guard manifest.containerVersion <= containerVersion else { throw FormatError.unsupportedVersion(manifest.containerVersion) }181        guard manifest.schemaVersion <= migrator.targetVersion else { throw FormatError.unsupportedVersion(manifest.schemaVersion) }182183        var opened = Opened(manifest: manifest)184        var listed: Set<String> = [manifestEntry]185        for entry in manifest.entries {186            guard listed.insert(entry.name).inserted else { opened.problems.append("\(entry.name) is listed twice in the manifest"); continue }187            let content: Data188            do {189                guard let d = try zip.data(for: entry.name) else { opened.problems.append("\(entry.name) is listed in the manifest but missing"); continue }190                content = d191            } catch let e as ZipError {192                opened.problems.append(e.description)193                continue194            }195            guard content.count == entry.size else { opened.problems.append("\(entry.name) has \(content.count) bytes, the manifest records \(entry.size)"); continue }196            guard sha256(content) == entry.sha256.lowercased() else { opened.problems.append("\(entry.name) fails its SHA-256 checksum"); continue }197            switch entry.role {198            case .mimetype: break199            case .document: if entry.name == documentEntry { opened.documentJSON = content }200            case .asset:201                let id = entry.key ?? assetID(fromEntryName: entry.name)202                opened.assets[id] = Asset(id: id, mimeType: entry.mimeType ?? mimeType(forExtension: (entry.name as NSString).pathExtension), data: content)203            case .preserved:204                opened.preserved[entry.key ?? String(entry.name.dropFirst("preserved/".count))] = content205            }206        }207        if !listed.contains(documentEntry) { opened.problems.append("document.json is not listed in the manifest") }208        if !listed.contains(mimetypeEntry) { opened.problems.append("mimetype is not listed in the manifest") }209        opened.unknownEntries = zip.names.filter { !listed.contains($0) }210        return opened211    }212213    private static func decodeDocument(_ json: Data, migrator: SchemaMigrator, warnings: inout WarningCollector) throws -> DocumentModel {214        var data = json215        guard let tree = (try? JSONSerialization.jsonObject(with: json)) as? [String: Any] else {216            throw FormatError.integrityCheckFailed("document.json is not a JSON object")217        }218        let migrated = try migrator.migrate(tree)219        if !migrated.applied.isEmpty {220            guard let upgraded = try? JSONSerialization.data(withJSONObject: migrated.json) else {221                throw FormatError.unreadable("a schema migration produced an invalid document")222            }223            data = upgraded224            warnings.add(.info, "Document format upgraded",225                         "The document was written with schema \(migrated.applied[0]) and has been upgraded to schema \(migrator.targetVersion).")226        }227        do {228            var doc = try NativeJSON.decoder().decode(DocumentModel.self, from: data)229            doc.schemaVersion = DocumentModel.currentSchemaVersion230            return doc231        } catch {232            throw FormatError.unreadable("document.json does not match the document schema (\(describe(error)))")233        }234    }235236    // MARK: Recovery237238    /// Best-effort read of a damaged file: recovers document.json when it is intact (or its checksum fails but it still decodes),239    /// skips damaged assets, and reports everything as warnings.240    public static func recover(_ data: Data) throws -> ImportResult { try recover(data, migrator: .standard) }241242    static func recover(_ data: Data, migrator: SchemaMigrator) throws -> ImportResult {243        guard data.count <= FormatLimits.maxContainerBytes else { throw FormatError.tooLarge("the file is larger than \(FormatLimits.maxContainerBytes) bytes") }244        var warnings = WarningCollector()245        // The local-header scan does not need the central directory (lost when a file is truncated) and returns entries whose CRC fails.246        var salvaged = LocalEntryScanner.scan(data)247        if let zip = try? ZipReader(data: data) {248            for name in zip.names where salvaged[name] == nil {249                if let d = try? zip.data(for: name) { salvaged[name] = LocalEntryScanner.Entry(data: d, crcValid: true) }250            }251        } else {252            warnings.add(.approximated, "Damaged container", "The ZIP directory is missing or damaged; entries were recovered by scanning the file.")253        }254        guard !salvaged.isEmpty else { throw FormatError.unreadable("no readable entry was found in the file") }255        if let mime = salvaged[mimetypeEntry]?.data, String(decoding: mime, as: UTF8.self).trimmingCharacters(in: .whitespacesAndNewlines) != mimeType {256            warnings.add(.approximated, "Damaged container", "The mimetype marker is not the ORIX Docs one.")257        }258        var manifest: NativeManifest?259        // A manifest that fails its own CRC cannot vouch for anything: it is ignored.260        if let m = salvaged[manifestEntry], m.crcValid { manifest = try? NativeJSON.decoder().decode(NativeManifest.self, from: m.data) }261        if manifest == nil { warnings.add(.approximated, "Damaged container", "The manifest is missing or unreadable; checksums could not be verified.") }262        if let m = manifest, m.schemaVersion > migrator.targetVersion || m.containerVersion > containerVersion {263            throw FormatError.unsupportedVersion(max(m.schemaVersion, m.containerVersion))264        }265        let listed = Dictionary((manifest?.entries ?? []).map { ($0.name, $0) }, uniquingKeysWith: { a, _ in a })266267        guard let docEntry = salvaged[documentEntry] else { throw FormatError.unreadable("document.json could not be recovered") }268        if let m = listed[documentEntry], sha256(docEntry.data) != m.sha256.lowercased() || !docEntry.crcValid {269            warnings.add(.approximated, "Damaged container", "document.json fails its checksum but could still be decoded; check the text carefully.")270        } else if !docEntry.crcValid {271            warnings.add(.approximated, "Damaged container", "document.json fails its CRC but could still be decoded; check the text carefully.")272        }273        var doc: DocumentModel274        do { doc = try decodeDocument(docEntry.data, migrator: migrator, warnings: &warnings) } catch let e as FormatError {275            if case .unsupportedVersion = e { throw e }276            throw FormatError.unreadable("document.json is damaged beyond recovery")277        }278279        var handled: Set<String> = [mimetypeEntry, manifestEntry, documentEntry]280        if let manifest {281            for entry in manifest.entries where entry.role == .asset || entry.role == .preserved {282                handled.insert(entry.name)283                let label = entry.role == .asset ? "Damaged images" : "Damaged preserved parts"284                guard let found = salvaged[entry.name] else {285                    warnings.add(.dropped, label, "\(entry.name) is missing from the file.")286                    continue287                }288                guard found.crcValid, found.data.count == entry.size, sha256(found.data) == entry.sha256.lowercased() else {289                    warnings.add(.dropped, label, "\(entry.name) is damaged and was skipped.")290                    continue291                }292                if entry.role == .asset {293                    let id = entry.key ?? assetID(fromEntryName: entry.name)294                    doc.assets[id] = Asset(id: id, mimeType: entry.mimeType ?? mimeType(forExtension: (entry.name as NSString).pathExtension), data: found.data)295                } else {296                    doc.preservedParts[entry.key ?? String(entry.name.dropFirst("preserved/".count))] = found.data297                }298            }299        }300        // Entries the manifest does not describe (or every entry when the manifest is lost): accepted when their CRC holds.301        for (name, found) in salvaged.sorted(by: { $0.key < $1.key }) where !handled.contains(name) {302            guard manifest == nil else { continue }303            if name.hasPrefix("assets/") {304                guard found.crcValid else { warnings.add(.dropped, "Damaged images", "\(name) is damaged and was skipped."); continue }305                let id = assetID(fromEntryName: name)306                let mime = ImageSupport.sniffMime(found.data) ?? mimeType(forExtension: (name as NSString).pathExtension)307                doc.assets[id] = Asset(id: id, mimeType: mime, data: found.data)308            } else if name.hasPrefix("preserved/") {309                guard found.crcValid else { warnings.add(.dropped, "Damaged preserved parts", "\(name) is damaged and was skipped."); continue }310                doc.preservedParts[String(name.dropFirst("preserved/".count))] = found.data311            }312        }313        reportMissingAssets(doc, &warnings)314        return ImportResult(document: doc, warnings: warnings.warnings)315    }316317    // MARK: Helpers318319    private static func reportMissingAssets(_ doc: DocumentModel, _ warnings: inout WarningCollector) {320        var missing = 0321        doc.forEachParagraphEverywhere { p, _, _ in322            for r in p.runs { if case .image(let image)? = r.inline, doc.assets[image.asset] == nil { missing += 1 } }323        }324        for note in doc.notes.values { for p in note.paragraphs { for r in p.runs { if case .image(let image)? = r.inline, doc.assets[image.asset] == nil { missing += 1 } } } }325        if missing > 0 {326            warnings.add(.dropped, "Missing images", "\(missing) image\(missing == 1 ? "" : "s") of the document ha\(missing == 1 ? "s" : "ve") no data in the file; a placeholder is shown instead.")327        }328    }329330    static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() }331332    private static func describe(_ error: Error) -> String {333        if let e = error as? FormatError { return e.description }334        if let e = error as? DecodingError {335            switch e {336            case .keyNotFound(let key, let ctx): return "missing key \(key.stringValue) at \(path(ctx))"337            case .typeMismatch(_, let ctx), .valueNotFound(_, let ctx), .dataCorrupted(let ctx): return "\(ctx.debugDescription) at \(path(ctx))"338            @unknown default: return "decoding error"339            }340        }341        return String(describing: error)342    }343    private static func path(_ ctx: DecodingError.Context) -> String {344        ctx.codingPath.isEmpty ? "the root" : ctx.codingPath.map(\.stringValue).joined(separator: ".")345    }346347    private static func looksLikeContainer(_ data: Data) -> Bool {348        data.count >= 4 && data.prefix(4).elementsEqual([0x50, 0x4B, 0x03, 0x04])349    }350351    private static func isSafeEntryName(_ name: String) -> Bool {352        if name.isEmpty || name.hasPrefix("/") || name.hasSuffix("/") || name.contains("\\") || name.contains("\0") || name.contains(":") { return false }353        return !name.split(separator: "/", omittingEmptySubsequences: false).contains { $0 == ".." || $0.isEmpty }354    }355356    /// Asset ids become file names; anything outside [A-Za-z0-9._-] is hex-escaped so the name stays portable.357    static func safeFileName(_ id: String) -> String {358        var out = ""359        for u in id.unicodeScalars {360            if (u.isASCII && (u.properties.isAlphabetic || ("0"..."9").contains(Character(u)))) || u == "-" || u == "_" { out.unicodeScalars.append(u) }361            else { out += String(format: "%%%X", u.value).replacingOccurrences(of: "%", with: "=") }362        }363        return out.isEmpty ? "asset" : out364    }365366    private static func assetID(fromEntryName name: String) -> String {367        ((name as NSString).lastPathComponent as NSString).deletingPathExtension368    }369370    static func mimeType(forExtension ext: String) -> String {371        switch ext.lowercased() {372        case "jpg", "jpeg": return "image/jpeg"373        case "png": return "image/png"374        case "gif": return "image/gif"375        case "tif", "tiff": return "image/tiff"376        case "pdf": return "application/pdf"377        case "heic": return "image/heic"378        default: return "application/octet-stream"379        }380    }381}382383/// JSON coding shared by document.json and manifest.json: sorted keys and ISO-8601 dates.384/// Dates carry a fractional part (up to nine digits) so a date read back is bit-identical to the one written.385enum NativeJSON {386    static func encoder(pretty: Bool = false) -> JSONEncoder {387        let e = JSONEncoder()388        e.outputFormatting = pretty ? [.sortedKeys, .prettyPrinted, .withoutEscapingSlashes] : [.sortedKeys, .withoutEscapingSlashes]389        e.dateEncodingStrategy = .custom { date, encoder in390            var c = encoder.singleValueContainer()391            try c.encode(string(from: date))392        }393        return e394    }395    static func decoder() -> JSONDecoder {396        let d = JSONDecoder()397        d.dateDecodingStrategy = .custom { decoder in398            let c = try decoder.singleValueContainer()399            let s = try c.decode(String.self)400            guard let date = date(from: s) else { throw DecodingError.dataCorruptedError(in: c, debugDescription: "invalid ISO-8601 date \(s)") }401            return date402        }403        return d404    }405406    static func string(from date: Date) -> String {407        let t = date.timeIntervalSinceReferenceDate408        guard t.isFinite else { return "2001-01-01T00:00:00Z" }409        let whole = t.rounded(.down)410        var digits = String(format: "%.9f", t - whole)        // "0.123456789"411        var seconds = whole412        if digits.hasPrefix("1") { seconds += 1; digits = "0.000000000" }413        let base = Date(timeIntervalSinceReferenceDate: seconds).formatted(.iso8601)   // 2026-11-21T12:34:56Z414        var fraction = String(digits.dropFirst(2))415        while fraction.hasSuffix("0") { fraction.removeLast() }416        return fraction.isEmpty ? base : String(base.dropLast()) + "." + fraction + "Z"417    }418419    static func date(from s: String) -> Date? {420        var text = s, fraction = 0.0421        if let dot = text.firstIndex(of: ".") {422            let after = text[text.index(after: dot)...]423            let digits = after.prefix { $0.isASCII && $0.isNumber }424            guard !digits.isEmpty, let f = Double("0." + digits) else { return nil }425            fraction = f426            text = String(text[..<dot]) + String(after.dropFirst(digits.count))427        }428        guard let base = try? Date(text, strategy: .iso8601) else { return nil }429        return Date(timeIntervalSinceReferenceDate: base.timeIntervalSinceReferenceDate + fraction)430    }431}432433/// Walks the local file headers of a ZIP from the start of the file. Unlike `ZipReader` it needs no central directory and434/// hands back entries whose CRC-32 fails (flagged), which is what recovery of a damaged or truncated container needs.435enum LocalEntryScanner {436    struct Entry { var data: Data; var crcValid: Bool }437438    static func scan(_ data: Data, limits: ZipLimits = .standard) -> [String: Entry] {439        let bytes = [UInt8](data)440        var out: [String: Entry] = [:]441        var total = 0442        var p = 0443        func u16(_ o: Int) -> Int { Int(bytes[o]) | Int(bytes[o + 1]) << 8 }444        func u32(_ o: Int) -> Int { Int(bytes[o]) | Int(bytes[o + 1]) << 8 | Int(bytes[o + 2]) << 16 | Int(bytes[o + 3]) << 24 }445        func nextSignature(from start: Int) -> Int? {446            var i = start447            while i + 4 <= bytes.count {448                if bytes[i] == 0x50, bytes[i + 1] == 0x4B, bytes[i + 2] == 0x03, bytes[i + 3] == 0x04 { return i }449                i += 1450            }451            return nil452        }453        while let start = nextSignature(from: p), start + 30 <= bytes.count, out.count < limits.maxEntries {454            let flags = u16(start + 6), method = u16(start + 8)455            let crc = UInt32(truncatingIfNeeded: u32(start + 14))456            let csize = u32(start + 18), usize = u32(start + 22)457            let nameLen = u16(start + 26), extraLen = u16(start + 28)458            let dataStart = start + 30 + nameLen + extraLen459            p = start + 4460            guard nameLen > 0, start + 30 + nameLen <= bytes.count else { continue }461            let name = String(decoding: bytes[(start + 30)..<(start + 30 + nameLen)], as: UTF8.self)462            // Entries with a data descriptor (sizes unknown here), encryption or exotic methods are left to ZipReader.463            guard flags & 0x9 == 0, method == 0 || method == 8, isPlausible(name), usize <= limits.maxEntrySize,464                  dataStart <= bytes.count, total + usize <= limits.maxTotalSize else { continue }465            let available = min(csize, bytes.count - dataStart)466            let raw = Data(bytes[dataStart..<(dataStart + available)])467            var content: Data?468            if method == 0 {469                content = available == csize && csize == usize ? raw : nil470            } else {471                content = available == csize ? inflate(raw, expected: usize) : nil472            }473            guard let content, out[name] == nil else { continue }474            total += content.count475            out[name] = Entry(data: content, crcValid: CRC32.checksum(content) == crc)476            p = dataStart + csize477        }478        return out479    }480481    private static func isPlausible(_ name: String) -> Bool {482        !name.hasPrefix("/") && !name.hasSuffix("/") && !name.contains("\\") && !name.contains("\0") && !name.contains("\u{FFFD}")483            && !name.split(separator: "/", omittingEmptySubsequences: false).contains("..")484    }485486    private static func inflate(_ raw: Data, expected: Int) -> Data? {487        if expected == 0 { return Data() }488        var out = Data(count: expected + 1)489        let written: Int = out.withUnsafeMutableBytes { dst in490            raw.withUnsafeBytes { src in491                guard let d = dst.bindMemory(to: UInt8.self).baseAddress, let s = src.bindMemory(to: UInt8.self).baseAddress else { return 0 }492                return compression_decode_buffer(d, expected + 1, s, raw.count, nil, COMPRESSION_ZLIB)493            }494        }495        guard written == expected else { return nil }496        out.count = expected497        return out498    }499}500
Files main
Menu

Theme