From af59a0a737febe66cfd61a592e5282e2194268c3 Mon Sep 17 00:00:00 2001 From: Gonzalo Rodriguez Date: Tue, 10 Sep 2019 18:44:33 -0300 Subject: [PATCH] Automatically detect byte strings --- lib/libcbor/helpers.rb | 22 +++++++++++++--------- spec/encoding_spec.rb | 15 ++++++++++++++- 2 files changed, 27 insertions(+), 10 deletions(-) diff --git a/lib/libcbor/helpers.rb b/lib/libcbor/helpers.rb index 143ef4d..18934d7 100644 --- a/lib/libcbor/helpers.rb +++ b/lib/libcbor/helpers.rb @@ -34,15 +34,19 @@ module StringHelper # # @return [String] The CBOR representation def __libcbor_to_cbor - @@item ||= LibCBOR.cbor_new_definite_string - string = FFI::MemoryPointer.from_string(self) - out_bfr = FFI::MemoryPointer.new :pointer - out_bfr_len = FFI::MemoryPointer.new :size_t - LibCBOR.cbor_string_set_handle(@@item, string, bytes.length) - res_len = LibCBOR.cbor_serialize_alloc(@@item, out_bfr, out_bfr_len) - out_bfr.read_pointer.get_bytes(0, res_len).tap do - LibC.free(out_bfr.read_pointer) - end + if encoding == Encoding::ASCII_8BIT + CBOR::ByteString.new(self).__libcbor_to_cbor + else + @@item ||= LibCBOR.cbor_new_definite_string + string = FFI::MemoryPointer.from_string(self) + out_bfr = FFI::MemoryPointer.new :pointer + out_bfr_len = FFI::MemoryPointer.new :size_t + LibCBOR.cbor_string_set_handle(@@item, string, bytes.length) + res_len = LibCBOR.cbor_serialize_alloc(@@item, out_bfr, out_bfr_len) + out_bfr.read_pointer.get_bytes(0, res_len).tap do + LibC.free(out_bfr.read_pointer) + end + end end end diff --git a/spec/encoding_spec.rb b/spec/encoding_spec.rb index 220842e..b3fd66f 100644 --- a/spec/encoding_spec.rb +++ b/spec/encoding_spec.rb @@ -14,8 +14,21 @@ module CBOR describe String do it 'returns correct bytes' do expect("Hello".to_cbor.bytes).to eq [101] + "Hello".bytes - end + + it "returns corrects bytes when binary encoding" do + word = "Hello".b + + expect(word.to_cbor.bytes).to eq [0b010_00000 + word.length] + word.bytes + end + end + + describe ByteString do + it "returns corrects bytes" do + word = CBOR::ByteString.new("Hello") + + expect(word.to_cbor.bytes).to eq [0b010_00000 + word.length] + word.bytes + end end describe Float do