Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
22 changes: 13 additions & 9 deletions lib/libcbor/helpers.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
15 changes: 14 additions & 1 deletion spec/encoding_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down