@@ -131,12 +131,20 @@ // 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 } @@ -190,8 +198,9 @@ output = output[1:] d.buffer >>= len d.at -= len + // Account for the processed output byte total++ } // Termination condition @@ -200,8 +209,10 @@ } // 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) }