Skip to content

Commit 144090a

Browse files
committed
Start encoding bytes fields
1 parent ad452bb commit 144090a

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

lib/protoboeuf/codegen.rb

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -128,6 +128,26 @@ def encode_bool(field)
128128
eocode
129129
end
130130

131+
def encode_bytes(field)
132+
tag = (field.number << 3) | field.wire_type
133+
# Empty bytes is default value, so encodes nothing
134+
<<-eocode
135+
val = @#{field.name}.b
136+
if val.bytesize > 0
137+
## encode the tag
138+
buff << #{sprintf("%#04x", tag)}
139+
len = val.bytesize
140+
while len > 0
141+
byte = len & 0x7F
142+
len >>= 7
143+
byte |= 0x80 if len > 0
144+
buff << byte
145+
end
146+
buff.concat(val)
147+
end
148+
eocode
149+
end
150+
131151
def encode_string(field)
132152
tag = (field.number << 3) | field.wire_type
133153
# Empty string is default value, so encodes nothing

test/message_test.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -595,6 +595,25 @@ def test_encode_bool
595595
assert_equal expected, actual
596596
end
597597

598+
def test_encode_bytes
599+
code = ProtoBoeuf.parse_string <<-eoboeuf
600+
syntax = "proto3";
601+
602+
message BytesValue {
603+
bytes value = 1;
604+
}
605+
eoboeuf
606+
607+
m = Module.new { class_eval code.to_ruby }
608+
609+
["", "hello world", "foobar", "nöel", "some emoji 🎉👍❤️ and some math ∮𝛅x", "\x01\x02\x00\x01\x02"].each do |s|
610+
s = s.b
611+
actual = m::BytesValue.encode m::BytesValue.new(value: s)
612+
expected = ::Google::Protobuf::BytesValue.encode(::Google::Protobuf::BytesValue.new(value: s))
613+
assert_equal expected, actual, "Failed during encoding of #{s.inspect}"
614+
end
615+
end
616+
598617
def test_encode_string
599618
code = ProtoBoeuf.parse_string <<-eoboeuf
600619
syntax = "proto3";

0 commit comments

Comments
 (0)