From b4690130ce9d20f88c9590a1d75485b9bc8b259b Mon Sep 17 00:00:00 2001 From: Carsten Bormann Date: Sun, 24 Feb 2013 22:57:27 +0100 Subject: [PATCH] Write a FLOAT as a float (as opposed to a double) when that yields the same value --- ext/msgpack/packer.h | 12 ++++++++++++ spec/format_spec.rb | 6 +++--- 2 files changed, 15 insertions(+), 3 deletions(-) diff --git a/ext/msgpack/packer.h b/ext/msgpack/packer.h index 6bee4c0b..bf0510ef 100644 --- a/ext/msgpack/packer.h +++ b/ext/msgpack/packer.h @@ -255,6 +255,17 @@ static inline void msgpack_packer_write_u64(msgpack_packer_t* pk, uint64_t v) static inline void msgpack_packer_write_double(msgpack_packer_t* pk, double v) { + float fv = v; + if (fv == v) { + msgpack_buffer_ensure_writable(PACKER_BUFFER_(pk), 5); + union { + float f; + uint32_t u32; + char mem[4]; + } castbuf = { fv }; + castbuf.u32 = _msgpack_be_float(castbuf.u32); + msgpack_buffer_write_byte_and_data(PACKER_BUFFER_(pk), 0xca, castbuf.mem, 4); + } else { msgpack_buffer_ensure_writable(PACKER_BUFFER_(pk), 9); union { double d; @@ -263,6 +274,7 @@ static inline void msgpack_packer_write_double(msgpack_packer_t* pk, double v) } castbuf = { v }; castbuf.u64 = _msgpack_be_double(castbuf.u64); msgpack_buffer_write_byte_and_data(PACKER_BUFFER_(pk), 0xcb, castbuf.mem, 8); + } } static inline void msgpack_packer_write_raw_header(msgpack_packer_t* pk, unsigned int n) diff --git a/spec/format_spec.rb b/spec/format_spec.rb index fd7c2052..2e16a805 100644 --- a/spec/format_spec.rb +++ b/spec/format_spec.rb @@ -72,10 +72,10 @@ end it "double" do - check 9, 1.0 + check 5, 1.0 # fits in a float check 9, 0.1 check 9, -0.1 - check 9, -1.0 + check 5, -1.0 # fits in a float end it "fixraw" do @@ -154,7 +154,7 @@ end it "1.0" do - match 1.0, "\xcb\x3f\xf0\x00\x00\x00\x00\x00\x00" + match 1.0, "\xca\x3f\x80\x00\x00" end it "[]" do