Skip to content

Commit

Permalink
Update pure python float checking.
Browse files Browse the repository at this point in the history
Our C++ strtod was updated to handle text-format rounding about a month after it was ported to python.

PiperOrigin-RevId: 705344939
  • Loading branch information
mkruskal-google authored and copybara-github committed Dec 12, 2024
1 parent 0765dd4 commit a4825fb
Show file tree
Hide file tree
Showing 2 changed files with 5 additions and 7 deletions.
7 changes: 0 additions & 7 deletions conformance/text_format_failure_list_python.txt
Original file line number Diff line number Diff line change
Expand Up @@ -45,10 +45,3 @@ Required.*.TextFormatInput.StringLiteralBasicEscapesBytes.ProtobufOutput
Required.*.TextFormatInput.StringLiteralBasicEscapesBytes.TextFormatOutput # Output was not equivalent to reference message: modified: optional_bytes: "\007\010\014\n\r\t\013?\\\'\"" -> "\007\010\014\n\r\t
Required.*.TextFormatInput.StringLiteralBasicEscapesString.ProtobufOutput # Output was not equivalent to reference message: modified: optional_string: "\007\010\014\n\r\t\013?\\\'\"" -> "\007\010\014\n\r\
Required.*.TextFormatInput.StringLiteralBasicEscapesString.TextFormatOutput # Output was not equivalent to reference message: modified: optional_string: "\007\010\014\n\r\t\013?\\\'\"" -> "\007\010\014\n\r\

# Optional float interpreted as `inf`
Required.*.TextFormatInput.FloatFieldMaxValue.ProtobufOutput # Output was not equivalent to reference message
Required.*.TextFormatInput.FloatFieldMaxValue.TextFormatOutput # Output was not equivalent to reference message
Required.*.TextFormatInput.FloatFieldMaxValue_f.ProtobufOutput # Output was not equivalent to reference message
Required.*.TextFormatInput.FloatFieldMaxValue_f.TextFormatOutput # Output was not equivalent to reference message

5 changes: 5 additions & 0 deletions python/google/protobuf/internal/type_checkers.py
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@ class Uint64ValueChecker(IntValueChecker):
# The max 4 bytes float is about 3.4028234663852886e+38
_FLOAT_MAX = float.fromhex('0x1.fffffep+127')
_FLOAT_MIN = -_FLOAT_MAX
_MAX_FLOAT_AS_DOUBLE_ROUNDED = 3.4028235677973366e38
_INF = float('inf')
_NEG_INF = float('-inf')

Expand Down Expand Up @@ -269,8 +270,12 @@ def CheckValue(self, proposed_value):
converted_value = super().CheckValue(proposed_value)
# This inf rounding matches the C++ proto SafeDoubleToFloat logic.
if converted_value > _FLOAT_MAX:
if converted_value <= _MAX_FLOAT_AS_DOUBLE_ROUNDED:
return _FLOAT_MAX
return _INF
if converted_value < _FLOAT_MIN:
if converted_value >= -_MAX_FLOAT_AS_DOUBLE_ROUNDED:
return _FLOAT_MIN
return _NEG_INF

return TruncateToFourByteFloat(converted_value)
Expand Down

0 comments on commit a4825fb

Please sign in to comment.