Skip to content

Commit

Permalink
[Ruby] Fix for truncating behavior when converting Float to Duration.
Browse files Browse the repository at this point in the history
  • Loading branch information
haberman committed Feb 19, 2021
1 parent 256f132 commit 3b3aac9
Show file tree
Hide file tree
Showing 2 changed files with 7 additions and 1 deletion.
2 changes: 1 addition & 1 deletion ruby/ext/google/protobuf_c/message.c
Original file line number Diff line number Diff line change
Expand Up @@ -1287,7 +1287,7 @@ const upb_msg* Message_GetUpbMessage(VALUE value, const upb_msgdef* m,
if (!rb_obj_is_kind_of(value, rb_cNumeric)) goto badtype;

sec.int64_val = NUM2LL(value);
nsec.int32_val = (NUM2DBL(value) - NUM2LL(value)) * 1000000000;
nsec.int32_val = round((NUM2DBL(value) - NUM2LL(value)) * 1000000000);
upb_msg_set(msg, sec_f, sec, arena);
upb_msg_set(msg, nsec_f, nsec, arena);
return msg;
Expand Down
6 changes: 6 additions & 0 deletions ruby/tests/common_tests.rb
Original file line number Diff line number Diff line change
Expand Up @@ -1701,6 +1701,12 @@ def test_converts_duration
m = proto_module::TimeMessage.new(duration: 1.1)
assert_equal Google::Protobuf::Duration.new(seconds: 1, nanos: 100_000_000), m.duration

m = proto_module::TimeMessage.new(duration: 123.321)
assert_equal Google::Protobuf::Duration.new(seconds: 123, nanos: 321_000_000), m.duration

m = proto_module::TimeMessage.new(duration: -123.321)
assert_equal Google::Protobuf::Duration.new(seconds: -123, nanos: -321_000_000), m.duration

assert_raise(Google::Protobuf::TypeError) { m.duration = '2' }
assert_raise(Google::Protobuf::TypeError) { m.duration = proto_module::TimeMessage.new }
end
Expand Down

0 comments on commit 3b3aac9

Please sign in to comment.