Skip to content

Instantly share code, notes, and snippets.

@imanel
Forked from mloughran/unmasking_benchmark.rb
Created April 5, 2011 08:45
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save imanel/903261 to your computer and use it in GitHub Desktop.
Save imanel/903261 to your computer and use it in GitHub Desktop.
# 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