Skip to content

Commit

Permalink
Merge pull request #39 from Shopify/encode_bool
Browse files Browse the repository at this point in the history
Add logic and test for encode_bool
  • Loading branch information
maximecb authored Apr 3, 2024
2 parents b6a1f68 + 39fdaf8 commit f871549
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
17 changes: 17 additions & 0 deletions lib/protoboeuf/codegen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,23 @@ def encode
"\n buff\nend\n"
end

def encode_bool(field)
tag = (field.number << 3) | field.wire_type
# False/zero is the default value, so the false case encodes nothing
<<-eocode
## encode the tag
val = @#{field.name}
if val == true
buff << #{sprintf("%#04x", tag)}
buff << 1
elsif val == false
# Default value, encode nothing
else
raise "bool values should be true or false"
end
eocode
end

def encode_uint64(field)
tag = (field.number << 3) | field.wire_type
<<-eocode
Expand Down
22 changes: 22 additions & 0 deletions test/message_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,28 @@ def test_translate_known_type_timestamp
assert_equal 3337, instance.t.nanos
end

def test_encode_bool
code = ProtoBoeuf.parse_string <<-eoboeuf
syntax = "proto3";
message BoolValue {
bool value = 1;
}
eoboeuf

m = Module.new { class_eval code.to_ruby }

# False
actual = m::BoolValue.encode m::BoolValue.new(value: false)
expected = ::Google::Protobuf::BoolValue.encode(::Google::Protobuf::BoolValue.new(value: false))
assert_equal expected, actual

# True
actual = m::BoolValue.encode m::BoolValue.new(value: true)
expected = ::Google::Protobuf::BoolValue.encode(::Google::Protobuf::BoolValue.new(value: true))
assert_equal expected, actual
end

def test_encode_uint64
code = ProtoBoeuf.parse_string <<-eoboeuf
syntax = "proto3";
Expand Down

0 comments on commit f871549

Please sign in to comment.