Files
James Coglan 9ce857b3d4 Revise uses of encoding APIs.
When originally implemented, we still supported Ruby 1.8, which
necessitated checking for encoding methods and using a regex to validate
UTF-8. These checks are now gone.

We tagged many strings as binary when not strictly necessary, either
because we were just going to iterate their bytes or because we were
going to hand them off to the caller which should just write them
directly to a socket. Strings used as buffers to accumulate streaming
input are still tagged as binary to avoid encoding
collision/conversion.

The places where we do need to tag as UTF-8 (i.e. just before emitting
to the application) remain, but copy the string if necessary. This
allows us to work with frozen strings.

Finally, strings passed in via the Driver#text method should be
*transcoded* to UTF-8 if necessary, not merely tagged. The Ruby
String#encode method produces a new string so this should also be safe
with frozen strings.
2016-05-19 21:08:22 +01:00

56 lines
1.1 KiB
Ruby

module WebSocket
class Driver
class StreamReader
# Try to minimise the number of reallocations done:
MINIMUM_AUTOMATIC_PRUNE_OFFSET = 128
def initialize
@buffer = String.new('').force_encoding(BINARY)
@offset = 0
end
def put(chunk)
return unless chunk and chunk.bytesize > 0
@buffer << chunk.force_encoding(BINARY)
end
# Read bytes from the data:
def read(length)
return nil if (@offset + length) > @buffer.bytesize
chunk = @buffer.byteslice(@offset, length)
@offset += chunk.bytesize
prune if @offset > MINIMUM_AUTOMATIC_PRUNE_OFFSET
return chunk
end
def each_byte
prune
@buffer.each_byte do |octet|
@offset += 1
yield octet
end
end
private
def prune
buffer_size = @buffer.bytesize
if @offset > buffer_size
@buffer = String.new('').force_encoding(BINARY)
else
@buffer = @buffer.byteslice(@offset, buffer_size - @offset)
end
@offset = 0
end
end
end
end