Skip to content

[stdlib] Fix exact floating point to integer cast overflow detection #16960

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 16, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 25 additions & 7 deletions stdlib/public/core/FloatingPointTypes.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -1583,8 +1583,18 @@ extension ${Self} {
% for self_ty in all_integer_types(word_bits):
% That = self_ty.stdlib_name
% ThatBuiltinName = self_ty.builtin_name
% srcBits = self_ty.bits
% sign = 's' if self_ty.is_signed else 'u'
% srcBits = self_ty.bits
% maxExponent = (1 << (ExponentBitCount - 1)) - 1
% maxBitLength = SignificandBitCount + 1 # implicit leading one
% if self_ty.is_signed:
% # The magnitude of the minimum value of a signed integer type is always
% # representable in floating point (assuming a large enough exponent)
% # because only one bit is set. All other possible magnitudes can be
% # represented using one bit less than the original source type.
% maxBitLength += 1
% end

/// Creates the closest representable value to the given integer.
///
/// - Parameter value: The integer to represent as a floating-point value.
Expand All @@ -1599,20 +1609,28 @@ extension ${Self} {
/// can't be represented exactly, the result is `nil`.
///
/// - Parameter value: The integer to represent as a floating-point value.
% if srcBits < SignificandBitCount:
% if srcBits <= maxBitLength and srcBits - 1 <= maxExponent:
@available(*, message: "Converting ${That} to ${Self} will always succeed.")
% end
@inlinable // FIXME(sil-serialize-all)
@inline(__always)
public init?(exactly value: ${That}) {
_value = Builtin.${sign}itofp_${ThatBuiltinName}_FPIEEE${bits}(value._value)

% if srcBits >= SignificandBitCount:
guard let roundTrip = ${That}(exactly: self),
roundTrip == value else {
% if srcBits - 1 > maxExponent:
// Check that the exponent will be in range.
guard value.magnitude >> ${maxExponent} <= 1 else {
return nil
}
% end
% if srcBits > maxBitLength:
// The magnitude of the integer must be representable by the significand.
// Omit trailing zeros that can be encoded by the exponent.
let mask: ${That}.Magnitude = ~((1 << (${SignificandBitCount} + 1)) - 1)
let absolute = value.magnitude
guard (absolute >> absolute.trailingZeroBitCount) & mask == 0 else {
return nil
}
% end
_value = Builtin.${sign}itofp_${ThatBuiltinName}_FPIEEE${bits}(value._value)
}
% end # all_integer_types
}
Expand Down
9 changes: 7 additions & 2 deletions stdlib/public/core/Integers.swift.gyb
Original file line number Diff line number Diff line change
Expand Up @@ -3296,10 +3296,15 @@ public struct ${Self}
/// - Parameter source: A floating-point value to convert to an integer.
@_transparent
public init?(exactly source: ${FloatType}) {
self._value = Builtin.fpto${u}i_FPIEEE${FloatBits}_${BuiltinName}(source._value)
if ${FloatType}(self) != source {
guard source > ${str(lower)}.0 && source < ${str(upper)}.0 else {
// The source is out of bounds (including infinities).
return nil
}
guard source == source.rounded(.towardZero) else {
// The source is a fraction or NaN.
return nil
}
self._value = Builtin.fpto${u}i_FPIEEE${FloatBits}_${BuiltinName}(source._value)
}

% if FloatType == 'Float80':
Expand Down