Permalink
Browse files

Merge pull request #3 from josh/encoding

Handle encoding
  • Loading branch information...
2 parents d56b068 + daf0299 commit 05c680c61319b1ee84dbc2240859a1c09582e8dd @rkh committed May 18, 2011
Showing with 21 additions and 4 deletions.
  1. +8 −4 lib/otnetstring.rb
  2. +13 −0 spec/otnetstring_spec.rb
View
@@ -3,7 +3,7 @@
module OTNetstring
class Error < StandardError; end
- def self.parse(io)
+ def self.parse(io, encoding = 'internal')
io = StringIO.new(io) if io.respond_to? :to_str
length, byte = "", nil
@@ -21,8 +21,12 @@ def self.parse(io)
case byte
when '#' then Integer io.read(length)
- when ',' then io.read(length)
- when '~' then raise Error, "nil has length of 0, #{length} given" unless length == 0
+ when ',' then
+ str = io.read(length)
+ str.force_encoding(encoding) if str.respond_to?(:force_encoding)
+ str
+ when '~' then
+ raise Error, "nil has length of 0, #{length} given" unless length == 0
when '!' then io.read(length) == 'true'
when '[', '{'
array = []
@@ -37,7 +41,7 @@ def self.parse(io)
def self.encode(obj, string_sep = ',')
case obj
- when String then "#{obj.length}#{string_sep}#{obj}"
+ when String then "#{obj.bytesize}#{string_sep}#{obj}"
when Integer then encode(obj.inspect, '#')
when NilClass then "0~"
when Array then encode(obj.map { |e| encode(e) }.join, '[')
@@ -1,3 +1,4 @@
+# -*- coding: utf-8 -*-
# Based on tnetstring-rb's spec/tnetstring_spec.rb
#
# Copyright (c) 2011 Matt Yoho
@@ -24,6 +25,10 @@
describe OTNetstring do
context "parsing" do
+ before do
+ Encoding.default_internal = 'utf-8' if defined? Encoding
+ end
+
it "parses an integer" do
OTNetstring.parse('5#12345').should == 12345
end
@@ -36,6 +41,10 @@
OTNetstring.parse('12,this is cool').should == "this is cool"
end
+ it "parses a multibyte string" do
+ OTNetstring.parse("3,☃").should == ""
+ end
+
it "parses to an empty array" do
OTNetstring.parse('0[').should == []
end
@@ -100,6 +109,10 @@
OTNetstring.encode("hello world").should == "11,hello world"
end
+ it "encodes a multibyte string" do
+ OTNetstring.encode("").should == "3,☃"
+ end
+
context "boolean" do
it "encodes true as 'true'" do
OTNetstring.encode(true).should == "4!true"

0 comments on commit 05c680c

Please sign in to comment.