-
-
Save imanel/903261 to your computer and use it in GitHub Desktop.
This file contains 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
# gem install fast_xor | |
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 full_mask(start, length) | |
first_mask = start % 4 | |
mask_multiplier = length / 4 + 1 | |
(@masking_key * mask_multiplier)[first_mask..-1] | |
end | |
def getbytes(start_index, count) | |
string_to_mask = self[start_index..start_index + count] | |
masking_string = full_mask(start_index, count) | |
string_to_mask.xor!(masking_string) | |
end | |
end | |
end | |
end | |
require 'benchmark' | |
require 'xor' | |
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