Created
April 4, 2011 18:56
-
-
Save mloughran/902183 to your computer and use it in GitHub Desktop.
Making WebSocket unmasking fast in ruby
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
module EventMachine | |
module WebSocket | |
class MaskedString < String | |
def read_mask | |
raise "Too short" if bytesize < 4 # TODO - change | |
@masking_key = String.new(self[0..3]) | |
end | |
def slice_mask | |
slice!(0, 4) | |
end | |
def getbyte(index) | |
masked_char = super(index + 4) | |
masked_char ? masked_char ^ @masking_key.getbyte(index % 4) : nil | |
end | |
def getbytes(start_index, count) | |
data = '' | |
count.times do |i| | |
data << getbyte(start_index + i) | |
end | |
data | |
end | |
end | |
end | |
end | |
require 'benchmark' | |
n = 1000 | |
# Use a 4 byte mask and a 1K string | |
string = rand.to_s[0..3] + 'a' * 1024 | |
Benchmark.bm do |x| | |
x.report("MaskedString:") { | |
n.times { | |
string = EventMachine::WebSocket::MaskedString.new(string) | |
string.read_mask | |
string.getbytes(0, 1024) | |
} | |
} | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Or even better: http://blog.50projects.com/2010/12/ruby-string-xor-optimizations.html