SPB Git

Repository Public

BinaryCoding.swift 7.6 KB 210 lines swift

1// =============================================================================2//                  SP BOUCHER | SOFTWARE & RESEARCH3//             ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project          : QYVORA7// File             : Sources/QyvoraStorage/BinaryCoding.swift8// Module           : Qyvora Storage9// Repository       : https://git.spboucher.ai/qyvora10// Project Website  : Not specified11// Created          : 2026-12-0412// Last Modified    : 2026-12-0413//14// Author           : Simon-Pierre Boucher15// Position         : Professor of Finance16// Institution      : Université du Québec en Outaouais (UQO)17// Organization     : SP Boucher18// Website          : https://spboucher.ai19// Git              : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development      : dev@spboucher.ai23// Support          : support@spboucher.ai24// Security/Admin   : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License          : None specified (no license file in this repository)33//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041import QyvoraMath4243/// Big-endian binary writer used by every QYVORA container format (vault file, backup file, identity objects).44/// All integers are unsigned and big-endian; variable fields carry an explicit length prefix.45public struct ByteWriter: Sendable {46    public private(set) var bytes: Bytes = []4748    public init() {}4950    public mutating func u8(_ v: UInt8) { bytes.append(v) }5152    public mutating func u16(_ v: UInt16) {53        bytes.append(UInt8(truncatingIfNeeded: v >> 8))54        bytes.append(UInt8(truncatingIfNeeded: v))55    }5657    public mutating func u32(_ v: UInt32) { bytes += Endian.be32(v) }58    public mutating func u64(_ v: UInt64) { bytes += Endian.be64(v) }59    public mutating func raw(_ b: Bytes) { bytes += b }6061    /// One length byte followed by the data (at most 255 bytes, checked by precondition: caller-controlled sizes only).62    public mutating func prefixed8(_ b: Bytes) {63        precondition(b.count <= 0xff, "field too long for an 8-bit length")64        u8(UInt8(b.count))65        raw(b)66    }6768    /// Two length bytes followed by the data (at most 65 535 bytes).69    public mutating func prefixed16(_ b: Bytes) {70        precondition(b.count <= 0xffff, "field too long for a 16-bit length")71        u16(UInt16(b.count))72        raw(b)73    }7475    /// Four length bytes followed by the data.76    public mutating func prefixed32(_ b: Bytes) {77        precondition(UInt64(b.count) <= UInt64(UInt32.max), "field too long for a 32-bit length")78        u32(UInt32(b.count))79        raw(b)80    }81}8283/// Errors of the strict binary reader.84public enum ByteReaderError: Error, Equatable, Sendable {85    /// The input ends before the field does.86    case truncated87    /// Bytes remain after the last field.88    case trailingBytes89    /// A length prefix exceeds the limit accepted for that field.90    case lengthOutOfRange91}9293/// Strict big-endian reader: every read is bounds-checked and never traps on malformed input.94public struct ByteReader: Sendable {95    private let bytes: Bytes96    public private(set) var offset = 09798    public init(_ bytes: Bytes) { self.bytes = bytes }99100    public var remaining: Int { bytes.count - offset }101102    public mutating func raw(_ count: Int) throws(ByteReaderError) -> Bytes {103        guard count >= 0, count <= remaining else { throw .truncated }104        defer { offset += count }105        return Bytes(bytes[offset..<offset + count])106    }107108    public mutating func u8() throws(ByteReaderError) -> UInt8 {109        guard remaining >= 1 else { throw .truncated }110        defer { offset += 1 }111        return bytes[offset]112    }113114    public mutating func u16() throws(ByteReaderError) -> UInt16 {115        let b = try raw(2)116        return UInt16(b[0]) << 8 | UInt16(b[1])117    }118119    public mutating func u32() throws(ByteReaderError) -> UInt32 {120        let b = try raw(4)121        return b.reduce(UInt32(0)) { $0 << 8 | UInt32($1) }122    }123124    public mutating func u64() throws(ByteReaderError) -> UInt64 {125        let b = try raw(8)126        return b.reduce(UInt64(0)) { $0 << 8 | UInt64($1) }127    }128129    public mutating func prefixed8() throws(ByteReaderError) -> Bytes {130        try raw(Int(try u8()))131    }132133    public mutating func prefixed16(max: Int = 0xffff) throws(ByteReaderError) -> Bytes {134        let n = Int(try u16())135        guard n <= max else { throw .lengthOutOfRange }136        return try raw(n)137    }138139    public mutating func prefixed32(max: Int) throws(ByteReaderError) -> Bytes {140        let n = UInt64(try u32())141        guard n <= UInt64(max) else { throw .lengthOutOfRange }142        return try raw(Int(n))143    }144145    /// Fails when bytes remain: containers do not tolerate trailing data.146    public func finish() throws(ByteReaderError) {147        guard remaining == 0 else { throw .trailingBytes }148    }149}150151/// Base64url (RFC 4648, section 5) without padding. Decoding is strict: any character outside the alphabet,152/// any padding and any non-canonical trailing bits are rejected.153public enum Base64URL {154    private static let alphabet = Bytes("ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_".utf8)155156    private static let reverse: [UInt8] = {157        var t = [UInt8](repeating: 0xff, count: 256)158        for (i, c) in alphabet.enumerated() { t[Int(c)] = UInt8(i) }159        return t160    }()161162    public static func encode(_ bytes: Bytes) -> String {163        var out = Bytes()164        out.reserveCapacity((bytes.count * 4 + 2) / 3)165        var i = 0166        while i + 3 <= bytes.count {167            let v = UInt32(bytes[i]) << 16 | UInt32(bytes[i + 1]) << 8 | UInt32(bytes[i + 2])168            out.append(alphabet[Int(v >> 18)])169            out.append(alphabet[Int(v >> 12 & 63)])170            out.append(alphabet[Int(v >> 6 & 63)])171            out.append(alphabet[Int(v & 63)])172            i += 3173        }174        let rest = bytes.count - i175        if rest == 1 {176            let v = UInt32(bytes[i]) << 16177            out.append(alphabet[Int(v >> 18)])178            out.append(alphabet[Int(v >> 12 & 63)])179        } else if rest == 2 {180            let v = UInt32(bytes[i]) << 16 | UInt32(bytes[i + 1]) << 8181            out.append(alphabet[Int(v >> 18)])182            out.append(alphabet[Int(v >> 12 & 63)])183            out.append(alphabet[Int(v >> 6 & 63)])184        }185        return String(decoding: out, as: UTF8.self)186    }187188    public static func decode(_ text: String) -> Bytes? {189        let input = Bytes(text.utf8)190        guard input.count % 4 != 1 else { return nil }191        var out = Bytes()192        out.reserveCapacity(input.count * 3 / 4)193        var acc: UInt32 = 0194        var bits = 0195        for c in input {196            let v = reverse[Int(c)]197            guard v != 0xff else { return nil }198            acc = acc << 6 | UInt32(v)199            bits += 6200            if bits >= 8 {201                bits -= 8202                out.append(UInt8(truncatingIfNeeded: acc >> UInt32(bits)))203            }204        }205        // canonical form: the unused low bits of the last character are zero206        guard acc & (UInt32(1) << UInt32(bits) - 1) == 0 else { return nil }207        return out208    }209}210
Files main
Menu

Theme