@@ -31,46 +31,43 @@ bufferLength int = len(ctx.input) ) // Force a flush if we are called with no data to write if len(data) == 0 { + // Nothing to flush if the buffer is empty though if len(ctx.input) == 0 { return nil } // We can't have more than 7 bytes in the buffer so this is safe data, blockSize, bufferLength = ctx.input, len(ctx.input), 0 } // Check if there are pending bytes in the buffer if len(data) < blockSize || bufferLength > 0 { - // Check whether we have enough bytes for a complete block - if len(data) > 8-bufferLength { - // Fill the buffer ... - ctx.input = append(ctx.input, data[:8-bufferLength]...) - // ... and recurse, calling ourselves with the full buffer - err = write(ctx.input) - if err != nil { - return err - } - - // Clear the buffer - ctx.input = ctx.input[:0] - - // Handle remaining bytes, if any - var remaining []byte = data[8-bufferLength:] - if len(remaining) > 0 { - // Recurse, calling ourselves with the rest of the bytes - err = write(data[8-bufferLength:]) - if err != nil { - return err - } - } - } else { - // Add the insufficient data to the buffer and return - ctx.input = append(ctx.input, data...) + + // If the current buffer + new data can fit into a block + if (len(data) + bufferLength) <= blockSize { + ctx.input = append(ctx.input, data...) + + // Flush the block if the buffer fills it + if len(ctx.input) == blockSize { + return write(nil) + } + // ... otherwise just return return nil } + + // The current buffer + new data overflow the block size + // Complete the block, flush it ... + ctx.input = append(ctx.input, data[:blockSize-bufferLength]...) + err = write(nil) + if err != nil { + return err + } + // ... and stage the rest of the data in the buffer + ctx.input = append(ctx.input, data[blockSize-bufferLength:]...) + return nil } var buf []byte = make([]byte, 1, blockSize+1) for block := 0; block < len(data)/blockSize; block++ { for i := 0; i < blockSize; i++ {