     }
 
     public func setNextBits(_ bitsToWrite: UInt8, from bits: UInt64) {
-        if( bitsToWrite > 64 ) {
-            return
-        }
-
+        guard
+            mode == .writeOnly,
+            bitsToWrite <= 64
+            else { return }
         var shiftedBits = bits << (64 - bitsToWrite.toU64)
         var bitsLeftToWrite = bitsToWrite
         while bitsLeftToWrite > 0 {

public class Bitstream: NSObject {

    private var data: Data

    private var bitsLeftInReadBuffer: Int = 0
    private var readByteIndex: Int = 0
    private var readBuffer: UInt8 = 0

    private var writeBuffer: UInt8 = 0
    private var bitsLeftInWriteBuffer: Int = 8

    public init(data: Data ) {
        self.data = data
    }

    public func getNextBit() -> UInt8! {
        if bitsLeftInReadBuffer == 0 && readByteIndex < data.count {
            readBuffer = data[readByteIndex]
            bitsLeftInReadBuffer = 8
            readByteIndex += 1
        }
        if bitsLeftInReadBuffer > 0 {
            let bit = readBuffer.b7
            readBuffer = readBuffer << 1
            bitsLeftInReadBuffer -= 1
            return bit
        }
        return nil
    }

    public func getNextBits(_ bitsToRead: UInt8 ) -> UInt64! {
        if bitsToRead > 64 {
            return nil
        }

        var bitsLeft = bitsToRead
        var combinedValue: UInt64 = 0
        while bitsLeft > 0 {
            let bit = getNextBit()
            if bit == nil {
                return nil
            }
            combinedValue = combinedValue << 1
            combinedValue = combinedValue | bit!.toU64
            bitsLeft -= 1
        }
        return combinedValue
    }

    public func setNextBit(_ bit: UInt8 ) {
        if( bitsLeftInWriteBuffer == 0 ) {
            data.append(writeBuffer)
            writeBuffer = 0
            bitsLeftInWriteBuffer = 8

    }

    public func dump() {
        var bits = ""
        while let bit = getNextBit() {
            bits += "\(bit)"
        }
        print(bits)
    }
