BinaryParser.swift (896B)
1 // 2 // BinaryParser.swift 3 // damus 4 // 5 // Created by William Casarin on 2023-04-25. 6 // 7 8 import Foundation 9 10 class BinaryParser { 11 var pos: Int 12 var buf: [UInt8] 13 14 init(buf: [UInt8], pos: Int = 0) { 15 self.pos = pos 16 self.buf = buf 17 } 18 19 func read_byte() -> UInt8? { 20 guard pos < buf.count else { 21 return nil 22 } 23 24 let v = buf[pos] 25 pos += 1 26 return v 27 } 28 29 func read_bytes(_ n: Int) -> [UInt8]? { 30 guard pos + n < buf.count else { 31 return nil 32 } 33 34 let v = [UInt8](self.buf[pos...pos+n]) 35 return v 36 } 37 38 func read_u16() -> UInt16? { 39 let start = self.pos 40 41 guard let b1 = read_byte(), let b2 = read_byte() else { 42 self.pos = start 43 return nil 44 } 45 46 return (UInt16(b1) << 8) | UInt16(b2) 47 } 48 }