// Buffered bits (LSB-first). var nBits: UInt32 = 0 // Number of valid bits currently in `bits`. var reader: ByteReader init(data: Data) { self.reader = ByteReader(data) } mutating func read(_ n: UInt32) throws -> UInt32 { precondition((1...32).contains(n), "n must be in 1…32") // Refill until we have enough bits. while nBits < n { guard let byte = try reader.read() else { throw BitStreamError.unexpectedEOF } // Append the byte at the current high position. bits |= UInt32(byte) << nBits nBits += 8 } // Mask out the requested bits. let result = bits & ((1 << n) &- 1) // (&- avoids overflow trap when n == 32) // Shift away the bits we've consumed. bits >>= n nBits -= n return result } }
out = pixel var i = 0 while p < out.count { let g = out[i + 1] // green out[i + 0] &+= g // red += green out[i + 2] &+= g // blue += green I += 4 } return out }