mutating func consume<T: FixedWidthInteger>FixedWidthInteger & UnsignedInteger>() throws -> T {
let size = MemoryLayout<T>.size
guard idx + size <= bytes.count else {
throw Error.notEnoughBytes
}
defer { idx += size }
return bytes[idx..<idx + size].enumerated().reduce(0) {
$0 + T($1.element) << (8 * $1.offset)
}
}
which can be used for all signed and unsigned integer types (U)IntUInt
, (U)Int8UInt8
, ..., (U)Int64UInt64
, e.g.
let header: UInt8 = try buffer.consume()
and for the signed integer types via the bitPattern:
initializer, e.g.
let word = try! Int16(bitPattern: buffer.consume())