Skip to content

Commit

Permalink
Parse/dump float values as per de facto spec
Browse files Browse the repository at this point in the history
  • Loading branch information
mattyoho committed Jun 22, 2011
1 parent 50e6e6c commit 0147246
Show file tree
Hide file tree
Showing 2 changed files with 49 additions and 4 deletions.
5 changes: 5 additions & 0 deletions lib/tnetstring.rb
Expand Up @@ -22,6 +22,8 @@ def self.parse(tnetstring)
value = case payload_type value = case payload_type
when '#' when '#'
payload.to_i payload.to_i
when '^'
payload.to_f
when ',' when ','
payload payload
when ']' when ']'
Expand Down Expand Up @@ -145,6 +147,9 @@ def self.dump(obj)
if obj.kind_of?(Integer) if obj.kind_of?(Integer)
int_str = obj.to_s int_str = obj.to_s
"#{int_str.length}:#{int_str}#" "#{int_str.length}:#{int_str}#"
elsif obj.kind_of?(Float)
float_str = obj.to_s
"#{float_str.length}:#{float_str}^"
elsif obj.kind_of?(String) || obj.kind_of?(Symbol) elsif obj.kind_of?(String) || obj.kind_of?(Symbol)
"#{obj.length}:#{obj}," "#{obj.length}:#{obj},"
elsif obj.is_a?(TrueClass) elsif obj.is_a?(TrueClass)
Expand Down
48 changes: 44 additions & 4 deletions spec/tnetstring_spec.rb
Expand Up @@ -2,8 +2,28 @@


describe TNetstring do describe TNetstring do
context "parsing" do context "parsing" do
it "parses an integer" do context "integers" do
TNetstring.parse('5:12345#')[0].should == 12345 it "parses a positive integer" do
TNetstring.parse('5:12345#')[0].should == 12345
end

it "parses a negative integer" do
TNetstring.parse('6:-12345#')[0].should == -12345
end
end

context "floats" do
it "parses a positve float" do
TNetstring.parse('3:3.5^')[0].should == 3.5
end

it "parses a negative float" do
TNetstring.parse('5:-3.14^')[0].should == -3.14
end

it "parses a float with leading zeros" do
TNetstring.parse('7:-000.14^')[0].should == -0.14
end
end end


it "parses an empty string" do it "parses an empty string" do
Expand Down Expand Up @@ -78,8 +98,28 @@
end end


context "dumping" do context "dumping" do
it "dumps an integer" do context "integers" do
TNetstring.dump(42).should == "2:42#" it "dumps a positive integer" do
TNetstring.dump(42).should == "2:42#"
end

it "dumps a negative integer" do
TNetstring.dump(-42).should == "3:-42#"
end
end

context "floats" do
it "dumps a positive float" do
TNetstring.dump(12.3).should == "4:12.3^"
end

it "dumps a negative float" do
TNetstring.dump(-2.3).should == "4:-2.3^"
end

it "dumps a float with integral value" do
TNetstring.dump(-42.0).should == "5:-42.0^"
end
end end


it "dumps a string" do it "dumps a string" do
Expand Down

0 comments on commit 0147246

Please sign in to comment.