SPB Git

spb/os-vault Public

Self-custody, multi-chain crypto wallet for macOS. One recovery phrase, six chain families, zero API keys — nothing leaves your Mac.

Swift 96% Shell 3.4% Makefile 0.6%
1.7 KB · 77 lines swift
Raw Blame History
1import Foundation23public enum BinaryReaderError: Error {4    case invalidBytesCount(Int)5    case dataMismatch6}78public struct BinaryReader {9    internal var cursor: Int10    internal let bytes: [UInt8]1112    public init(bytes: [UInt8]) {13        cursor = 014        self.bytes = bytes15    }1617    public var isEmpty: Bool {18        bytes.isEmpty19    }2021    public var count: Int {22        bytes.count23    }2425    public var remainBytes: Int {26        count - cursor27    }28}2930public extension BinaryReader {31    mutating func readAll() throws -> [UInt8] {32        try read(count: count - cursor)33    }3435    mutating func read() throws -> UInt8 {36        let newPosition = cursor + 137        guard bytes.count >= newPosition else {38            throw BinaryReaderError.dataMismatch39        }40        let result = bytes[cursor]41        cursor = newPosition42        return result43    }4445    mutating func read(count: Int) throws -> [UInt8] {46        guard count <= UInt32.max else {47            throw BinaryReaderError.invalidBytesCount(count)48        }4950        return try read(count: UInt32(count))51    }5253    mutating func read(count: UInt32) throws -> [UInt8] {54        let newPosition = cursor + Int(count)55        guard bytes.count >= newPosition else {56            throw BinaryReaderError.dataMismatch57        }58        let result = bytes[cursor ..< newPosition]59        cursor = newPosition60        return Array(result)61    }6263    mutating func decodeLength() throws -> Int {64        var len: UInt8 = 065        var size: UInt8 = 066        while true {67            let elem: UInt8 = try read()68            len |= (elem & 0x7F) << (size * 7)69            size += 170            if elem & 0x80 == 0 {71                break72            }73        }74        return Int(len)75    }76}77