Skip to content

Commit 4865207

Browse files
authored
Merge pull request #33826 from xwu/float-like-a-butterfly
[stdlib] Add another fast path for generic floating-point conversion
2 parents 3fe7abe + 643834e commit 4865207

File tree

1 file changed

+36
-9
lines changed

1 file changed

+36
-9
lines changed

stdlib/public/core/FloatingPoint.swift

Lines changed: 36 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1890,21 +1890,48 @@ extension BinaryFloatingPoint {
18901890
/// - Parameter value: A floating-point value to be converted.
18911891
@inlinable
18921892
public init<Source: BinaryFloatingPoint>(_ value: Source) {
1893+
// If two IEEE 754 binary interchange formats share the same exponent bit
1894+
// count and significand bit count, then they must share the same encoding
1895+
// for finite and infinite values.
1896+
switch (Source.exponentBitCount, Source.significandBitCount) {
18931897
#if !os(macOS) && !(os(iOS) && targetEnvironment(macCatalyst))
1894-
if #available(iOS 14.0, watchOS 7.0, tvOS 14.0, *) {
1895-
if case let value_ as Float16 = value {
1896-
self = Self(Float(value_))
1897-
return
1898+
case (5, 10):
1899+
guard #available(iOS 14.0, watchOS 7.0, tvOS 14.0, *) else {
1900+
self = Self._convert(from: value).value
1901+
break
18981902
}
1899-
}
1903+
let value_ = value as? Float16 ?? Float16(
1904+
sign: value.sign,
1905+
exponentBitPattern:
1906+
UInt(truncatingIfNeeded: value.exponentBitPattern),
1907+
significandBitPattern:
1908+
UInt16(truncatingIfNeeded: value.significandBitPattern))
1909+
self = Self(Float(value_))
19001910
#endif
1901-
switch value {
1902-
case let value_ as Float:
1911+
case (8, 23):
1912+
let value_ = value as? Float ?? Float(
1913+
sign: value.sign,
1914+
exponentBitPattern:
1915+
UInt(truncatingIfNeeded: value.exponentBitPattern),
1916+
significandBitPattern:
1917+
UInt32(truncatingIfNeeded: value.significandBitPattern))
19031918
self = Self(value_)
1904-
case let value_ as Double:
1919+
case (11, 52):
1920+
let value_ = value as? Double ?? Double(
1921+
sign: value.sign,
1922+
exponentBitPattern:
1923+
UInt(truncatingIfNeeded: value.exponentBitPattern),
1924+
significandBitPattern:
1925+
UInt64(truncatingIfNeeded: value.significandBitPattern))
19051926
self = Self(value_)
19061927
#if !(os(Windows) || os(Android)) && (arch(i386) || arch(x86_64))
1907-
case let value_ as Float80:
1928+
case (15, 63):
1929+
let value_ = value as? Float80 ?? Float80(
1930+
sign: value.sign,
1931+
exponentBitPattern:
1932+
UInt(truncatingIfNeeded: value.exponentBitPattern),
1933+
significandBitPattern:
1934+
UInt64(truncatingIfNeeded: value.significandBitPattern))
19081935
self = Self(value_)
19091936
#endif
19101937
default:

0 commit comments

Comments
 (0)