Index: src/0dev.org/encoding/fibonacci/fib.go ================================================================== --- src/0dev.org/encoding/fibonacci/fib.go +++ src/0dev.org/encoding/fibonacci/fib.go @@ -130,14 +130,22 @@ } // Clearing e.length is not necessary as it will be overwritten later // Stage the complete byte for writing - buffer := []byte{byte(e.remaining)} + buffer := make([]byte, 1, 2) + buffer[0] = byte(e.remaining) // Stage every full byte from the encoded value for writing - for enc > 128 { + // + // The bitlength of the largest encoded byte value, 255, is 13. + // Even with 7 bits already in the buffer this leaves [7+1], [8] + // and 4 bits remaining => a single if is enough instead of a for. + // + // 128 is [1000 0000] in binary. Any value equal or greater than it + // will be atleast 8 bits in length + if enc >= 128 { buffer = append(buffer, byte(enc)) enc >>= 8 len -= 8 } @@ -189,10 +197,11 @@ // Advance the internal and output buffers output = output[1:] d.buffer >>= len d.at -= len + // Account for the processed output byte total++ } // Termination condition if len(output) == 0 || err != nil { @@ -199,10 +208,12 @@ return total, err } // We need to limit the output's size else we could end up with a lot of small values // that fit neither in the output slice nor in the internal buffer + // + // (63 is [0011 1111] in binary, xor is a substraction and right shift a division) free := int((63 ^ d.at) >> 3) if free > len(output) { free = len(output) }