Permalink
Browse files

Parse/dump float values as per de facto spec

  • Loading branch information...
1 parent 50e6e6c commit 01472462a5986d08b73b2499a2c60d980971f445 @mattyoho committed Jun 22, 2011
Showing with 49 additions and 4 deletions.
  1. +5 −0 lib/tnetstring.rb
  2. +44 −4 spec/tnetstring_spec.rb
View
@@ -22,6 +22,8 @@ def self.parse(tnetstring)
value = case payload_type
when '#'
payload.to_i
+ when '^'
+ payload.to_f
when ','
payload
when ']'
@@ -145,6 +147,9 @@ def self.dump(obj)
if obj.kind_of?(Integer)
int_str = obj.to_s
"#{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)
"#{obj.length}:#{obj},"
elsif obj.is_a?(TrueClass)
View
@@ -2,8 +2,28 @@
describe TNetstring do
context "parsing" do
- it "parses an integer" do
- TNetstring.parse('5:12345#')[0].should == 12345
+ context "integers" do
+ 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
it "parses an empty string" do
@@ -78,8 +98,28 @@
end
context "dumping" do
- it "dumps an integer" do
- TNetstring.dump(42).should == "2:42#"
+ context "integers" do
+ 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
it "dumps a string" do

0 comments on commit 0147246

Please sign in to comment.