Skip to content
This repository has been archived by the owner on Aug 21, 2023. It is now read-only.

implement reading binary data from bson #20

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
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
7 changes: 7 additions & 0 deletions spec/bson_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -335,4 +335,11 @@ describe BSON do
fail "expected BSON" unless ary.is_a?(BSON)
ary["0"].should eq(1)
end

it "should be able to read binary data" do
bson = BSON.new
bson["bin"] = BSON::Binary.new(BSON::Binary::SubType::Binary, "binary".to_slice)
value = bson["bin"].as(BSON::Binary)
String.new(value.data).should eq("binary")
end
end
19 changes: 19 additions & 0 deletions src/bson/binary.cr
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,25 @@ class BSON
def initialize(@subtype : SubType, @data : Slice(UInt8))
end

def self.new(binary : LibBSON::Binary)
data = Slice(UInt8).new(binary.data, binary.len)

case binary.sub_type
when LibBSON::SubType::BSON_SUBTYPE_BINARY
new(SubType::Binary, data)
when LibBSON::SubType::BSON_SUBTYPE_FUNCTION
new(SubType::Function, data)
when LibBSON::SubType::BSON_SUBTYPE_UUID
new(SubType::UUID, data)
when LibBSON::SubType::BSON_SUBTYPE_MD5
new(SubType::MD5, data)
when LibBSON::SubType::BSON_SUBTYPE_USER
new(SubType::User, data)
else
raise "unable to handle subtype #{binary.sub_type}"
end
end

def to_raw_type
case @subtype
when SubType::Binary
Expand Down
2 changes: 2 additions & 0 deletions src/bson/value.cr
Original file line number Diff line number Diff line change
Expand Up @@ -68,6 +68,8 @@ class BSON
MaxKey.new
when LibBSON::Type::BSON_TYPE_MINKEY
MinKey.new
when LibBSON::Type::BSON_TYPE_BINARY
Binary.new(v.v_binary)
else
raise "Invalid BSON Value type #{@handle.v_type}"
end
Expand Down