Permalink
Browse files

Merge branch 'optimise_encoding_check'

  • Loading branch information...
2 parents 74325fe + ca3e167 commit b53fe93f7e20f92da02fcd6e9ab8bf1fa0ffff0c @mloughran mloughran committed Jul 11, 2012
Showing with 35 additions and 3 deletions.
  1. +17 −3 lib/em-websocket/connection.rb
  2. +18 −0 spec/integration/shared_examples.rb
@@ -129,16 +129,26 @@ def send_flash_cross_domain_file
close_connection_after_writing
end
+ # Cache encodings since it's moderately expensive to look them up each time
+ ENCODING_SUPPORTED = "string".respond_to?(:force_encoding)
+ UTF8 = Encoding.find("UTF-8") if ENCODING_SUPPORTED
+ BINARY = Encoding.find("BINARY") if ENCODING_SUPPORTED
+
+ # Send a WebSocket text frame.
+ #
+ # A WebSocketError may be raised if the connection is in an opening or a
+ # closing state, or if the passed in data is not valid UTF-8
+ #
def send(data)
# If we're using Ruby 1.9, be pedantic about encodings
- if data.respond_to?(:force_encoding)
+ if ENCODING_SUPPORTED
# Also accept ascii only data in other encodings for convenience
- unless (data.encoding == Encoding.find("UTF-8") && data.valid_encoding?) || data.ascii_only?
+ unless (data.encoding == UTF8 && data.valid_encoding?) || data.ascii_only?
raise WebSocketError, "Data sent to WebSocket must be valid UTF-8 but was #{data.encoding} (valid: #{data.valid_encoding?})"
end
# This labels the encoding as binary so that it can be combined with
# the BINARY framing
- data.force_encoding("BINARY")
+ data.force_encoding(BINARY)
else
# TODO: Check that data is valid UTF-8
end
@@ -148,6 +158,10 @@ def send(data)
else
raise WebSocketError, "Cannot send data before onopen callback"
end
+
+ # Revert data back to the original encoding (which we assume is UTF-8)
+ # Doing this to avoid duping the string - there may be a better way
+ data.force_encoding(UTF8)
end
# Send a ping to the client. The client must respond with a pong.
@@ -124,5 +124,23 @@
start_client { }
}
end
+
+ it "should not change the encoding of strings sent to send [antiregression]" do
+ em {
+ start_server { |server|
+ server.onopen {
+ s = "example string"
+ s.force_encoding("UTF-8")
+
+ server.send(s)
+
+ s.encoding.should == Encoding.find("UTF-8")
+ done
+ }
+ }
+
+ start_client { }
+ }
+ end
end
end

0 comments on commit b53fe93

Please sign in to comment.