Skip to content

Commit

Permalink
Start encoding string fields
Browse files Browse the repository at this point in the history
  • Loading branch information
paracycle committed Apr 4, 2024
1 parent e184ee4 commit ad452bb
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 0 deletions.
20 changes: 20 additions & 0 deletions lib/protoboeuf/codegen.rb
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,26 @@ def encode_bool(field)
eocode
end

def encode_string(field)
tag = (field.number << 3) | field.wire_type
# Empty string is default value, so encodes nothing
<<-eocode
val = @#{field.name}.encode(Encoding::UTF_8).force_encoding(Encoding::ASCII_8BIT)
if val.bytesize > 0
## encode the tag
buff << #{sprintf("%#04x", tag)}
len = val.bytesize
while len > 0
byte = len & 0x7F
len >>= 7
byte |= 0x80 if len > 0
buff << byte
end
buff.concat(val)
end
eocode
end

def encode_uint64(field)
tag = (field.number << 3) | field.wire_type
# Zero is the default value, so it encodes zero bytes
Expand Down
18 changes: 18 additions & 0 deletions test/message_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -595,6 +595,24 @@ def test_encode_bool
assert_equal expected, actual
end

def test_encode_string
code = ProtoBoeuf.parse_string <<-eoboeuf
syntax = "proto3";
message StringValue {
string value = 1;
}
eoboeuf

m = Module.new { class_eval code.to_ruby }

["", "hello world", "foobar", "nöel", "some emoji 🎉👍❤️ and some math ∮𝛅x"].each do |s|
actual = m::StringValue.encode m::StringValue.new(value: s)
expected = ::Google::Protobuf::StringValue.encode(::Google::Protobuf::StringValue.new(value: s))
assert_equal expected, actual, "Failed during encoding of #{s.inspect}"
end
end

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

0 comments on commit ad452bb

Please sign in to comment.