diff --git a/stdlib/public/core/FloatingPointTypes.swift.gyb b/stdlib/public/core/FloatingPointTypes.swift.gyb index 6a2ad9acd5083..c02ba7ddd16bc 100644 --- a/stdlib/public/core/FloatingPointTypes.swift.gyb +++ b/stdlib/public/core/FloatingPointTypes.swift.gyb @@ -1403,8 +1403,8 @@ extension ${Self} { /// Creates a value that exactly represents the given integer. /// - /// If the given integer is outside the representable range of this type, the - /// result is `nil`. + /// If the given integer is outside the representable range of this type or + /// can't be represented exactly, the result is `nil`. /// /// - Parameter value: The integer to represent as a floating-point value. % if srcBits < SignificandBitCount: diff --git a/stdlib/public/core/Integers.swift.gyb b/stdlib/public/core/Integers.swift.gyb index a132b27d13d09..8243f8bdc0083 100644 --- a/stdlib/public/core/Integers.swift.gyb +++ b/stdlib/public/core/Integers.swift.gyb @@ -818,11 +818,11 @@ def overflowOperationComment(operator): /// /// - Parameter rhs: The value to add to this value. /// - Returns: A tuple containing the result of the addition along with a - /// flag indicating whether overflow occurred. If the `overflow` component - /// is `false`, the `partialValue` component contains the entire sum. If - /// the `overflow` component is `true`, an overflow occurred and the - /// `partialValue` component contains the truncated sum of this value and - /// `rhs`. + /// Boolean value indicating whether overflow occurred. If the `overflow` + /// component is `false`, the `partialValue` component contains the entire + /// sum. If the `overflow` component is `true`, an overflow occurred and + /// the `partialValue` component contains the truncated sum of this value + /// and `rhs`. """, '-': """\ /// Returns the difference of this value and the given value along with a @@ -842,7 +842,7 @@ def overflowOperationComment(operator): /// /// - Parameter rhs: The value to multiply by this value. /// - Returns: A tuple containing the result of the multiplication along with - /// a flag indicating whether overflow occurred. If the `overflow` + /// a Boolean value indicating whether overflow occurred. If the `overflow` /// component is `false`, the `partialValue` component contains the entire /// product. If the `overflow` component is `true`, an overflow /// occurred and the `partialValue` component contains the truncated @@ -857,25 +857,25 @@ def overflowOperationComment(operator): /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the result of the division along with a - /// flag indicating whether overflow occurred. If the `overflow` component - /// is `false`, the `partialValue` component contains the entire quotient. - /// If the `overflow` component is `true`, an overflow occurred and - /// the `partialValue` component contains the truncated quotient. + /// Boolean value indicating whether overflow occurred. If the `overflow` + /// component is `false`, the `partialValue` component contains the entire + /// quotient. If the `overflow` component is `true`, an overflow occurred + /// and the `partialValue` component contains the truncated quotient. """, '%': """\ // FIXME(integers): the comment is for division instead of remainder - /// Returns the remainder of dividing this value by the given value along with - /// a flag indicating whether overflow occurred in the operation. + /// Returns the remainder of dividing this value by the given value along + /// with a flag indicating whether overflow occurred in the operation. /// /// Dividing by zero is not an error when using this method. For a value `x`, /// the result of `x.dividedReportingOverflow(by: 0)` is `(x, true)`. /// /// - Parameter rhs: The value to divide this value by. /// - Returns: A tuple containing the result of the division along with a - /// flag indicating whether overflow occurred. If the `overflow` component - /// is `false`, the `partialValue` component contains the entire quotient. - /// If the `overflow` component is `true`, an overflow occurred and - /// the `partialValue` component contains the truncated quotient. + /// Boolean value indicating whether overflow occurred. If the `overflow` + /// component is `false`, the `partialValue` component contains the entire + /// quotient. If the `overflow` component is `true`, an overflow occurred + /// and the `partialValue` component contains the truncated quotient. """, } return comments[operator] @@ -990,7 +990,7 @@ public protocol Numeric : Equatable, ExpressibleByIntegerLiteral { /// let y = Int8(exactly: 1_000) /// // y == nil /// - /// - Parameter source: A value to convert to this type of integer. + /// - Parameter source: A value to convert to this type. init?(exactly source: T) // FIXME(ABI)#44 (Recursive Protocol Constraints): should be just @@ -1098,6 +1098,23 @@ public protocol SignedNumeric : Numeric { } extension SignedNumeric { + /// Returns the additive inverse of the specified value. + /// + /// The negation operator (prefix `-`) returns the additive inverse of its + /// argument. + /// + /// let x = 21 + /// let y = -x + /// // y == -21 + /// + /// The resulting value must be representable in the same type as the + /// argument. In particular, negating a signed, fixed-width integer type's + /// minimum results in a value that cannot be represented. + /// + /// let z = -Int8.min + /// // Overflow error + /// + /// - Returns: The additive inverse of the argument. @_transparent public static prefix func - (_ operand: Self) -> Self { var result = operand @@ -1105,6 +1122,14 @@ extension SignedNumeric { return result } + /// Replaces this value with its additive inverse. + /// + /// The following example uses the `negate()` method to negate the value of + /// an integer `x`: + /// + /// var x = 21 + /// x.negate() + /// // x == -21 @_transparent public mutating func negate() { self = 0 - self @@ -1140,6 +1165,17 @@ public func abs(_ x: T) -> T { } extension Numeric { + /// Returns the given number unchanged. + /// + /// You can use the unary plus operator (`+`) to provide symmetry in your + /// code for positive numbers when also using the unary minus operator. + /// + /// let x = -21 + /// let y = +21 + /// // x == -21 + /// // y == 21 + /// + /// - Returns: The given argument without any changes. @_transparent public static prefix func + (x: Self) -> Self { return x @@ -1433,11 +1469,13 @@ public protocol BinaryInteger : // FIXME: Should be `Words : Collection where Words.Element == UInt` // See for why it isn't. - /// A type that represents the words of a binary integer. - /// Must implement the `Collection` protocol with an `UInt` element type. + /// A type that represents the words of a binary integer. + /// + /// The `Words` type must conform to the `Collection` protocol with an + /// `Element` type of `UInt`. associatedtype Words : Sequence where Words.Element == UInt - /// Returns a collection containing the words of this value's binary + /// A collection containing the words of this value's binary /// representation, in order from the least significant to most significant. /// /// Negative values are returned in two's complement representation, @@ -1543,6 +1581,20 @@ extension BinaryInteger { self = 0 } + /// Creates an integer from the given floating-point value, if it can be + /// represented exactly. + /// + /// If the value passed as `source` is not representable exactly, the result + /// is `nil`. In the following example, the constant `x` is successfully + /// created from a value of `21.0`, while the attempt to initialize the + /// constant `y` from `21.5` fails: + /// + /// let x = Int(exactly: 21.0) + /// // x == Optional(21) + /// let y = Int(exactly: 21.5) + /// // y == nil + /// + /// - Parameter source: A floating-point value to convert to an integer. public init?(exactly source: T) { // FIXME(integers): implement fatalError() @@ -1885,10 +1937,10 @@ extension BinaryInteger { /// the right shift operator (`<<`), both of which are available to any type /// that conforms to the `FixedWidthInteger` protocol. /// -/// The next example declares the generic `squared` function, which accepts an +/// The next example declares a generic `squared` function, which accepts an /// instance `x` of any fixed-width integer type. The function uses the -/// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and check -/// whether the result is too large to represent in the same type. +/// `multipliedReportingOverflow(by:)` method to multiply `x` by itself and +/// check whether the result is too large to represent in the same type. /// /// func squared(_ x: T) -> T? { /// let (result, overflow) = x.multipliedReportingOverflow(by: x) @@ -1950,12 +2002,12 @@ ${overflowOperationComment(x.operator)} % end /// Returns a tuple containing the high and low parts of the result of - /// multiplying its arguments. + /// multiplying this value by the given value. /// /// Use this method to calculate the full result of a product that would /// otherwise overflow. Unlike traditional truncating multiplication, the - /// `multipliedFullWidth(by:)` method returns an instance of DoubleWith, - /// containing both the `high` and `low` parts of the product of `self` and + /// `multipliedFullWidth(by:)` method returns a tuple + /// containing both the `high` and `low` parts of the product of this value and /// `other`. The following example uses this method to multiply two `UInt8` /// values that normally overflow when multiplied: /// @@ -1974,27 +2026,24 @@ ${overflowOperationComment(x.operator)} /// let z = UInt16(result.high) << 8 | UInt16(result.low) /// // z == 2000 /// - /// - Parameters: - /// - other: A value to multiply `self` by. + /// - Parameter other: The value to multiply this value by. /// - Returns: A tuple containing the high and low parts of the result of - /// multiplying `self` and `other`. - // FIXME(integers): figure out how to return DoubleWidth or correct the - // doc comment + /// multiplying this value and `other`. + // FIXME(integers): figure out how to return DoubleWidth func multipliedFullWidth(by other: Self) -> (high: Self, low: Self.Magnitude) /// Returns a tuple containing the quotient and remainder of dividing the - /// first argument by `self`. + /// given value by this value. /// /// The resulting quotient must be representable within the bounds of the - /// type. If the quotient of dividing `dividend` by `self` is too large to - /// represent in the type, a runtime error may occur. + /// type. If the quotient of dividing `dividend` by this value is too large + /// to represent in the type, a runtime error may occur. /// - /// - Parameters: - /// - dividend: A DoubleWidth value containing the high and low parts - /// of a double-width integer. The `high` component of the value carries - /// the sign, if the type is signed. + /// - Parameter dividend: A tuple containing the high and low parts of a + /// double-width integer. The `high` component of the value carries the + /// sign, if the type is signed. /// - Returns: A tuple containing the quotient and remainder of `dividend` - /// divided by `self`. + /// divided by this value. func dividingFullWidth(_ dividend: (high: Self, low: Self.Magnitude)) -> (quotient: Self, remainder: Self) @@ -2003,7 +2052,7 @@ ${overflowOperationComment(x.operator)} /// The number of bits equal to 1 in this value's binary representation. /// /// For example, in a fixed-width integer type with a `bitWidth` value of 8, - /// the number 31 has five bits equal to 1. + /// the number *31* has five bits equal to *1*. /// /// let x: Int8 = 0b0001_1111 /// // x == 31 @@ -2013,7 +2062,7 @@ ${overflowOperationComment(x.operator)} /// The number of leading zeros in this value's binary representation. /// /// For example, in a fixed-width integer type with a `bitWidth` value of 8, - /// the number 31 has three leading zeros. + /// the number *31* has three leading zeros. /// /// let x: Int8 = 0b0001_1111 /// // x == 31 @@ -2082,6 +2131,7 @@ extension FixedWidthInteger { @available(swift, deprecated: 3.1, obsoleted: 4.0, message: "Use 0") public static var allZeros: Self { return 0 } + /// The number of bits in the binary representation of this value. @_inlineable public var bitWidth: Int { return Self.bitWidth } @@ -2154,6 +2204,23 @@ ${assignmentOperatorComment(x.operator, False)} //===----------------------------------------------------------------------===// extension FixedWidthInteger { + /// Returns the inverse of the bits set in the argument. + /// + /// The bitwise NOT operator (`~`) is a prefix operator that returns a value + /// in which all the bits of its argument are flipped: Bits that are `1` in + /// the argument are `0` in the result, and bits that are `0` in the argument + /// are `1` in the result. This is equivalent to the inverse of a set. For + /// example: + /// + /// let x: UInt8 = 5 // 0b00000101 + /// let notX = ~x // 0b11111010 + /// + /// Performing a bitwise NOT operation on 0 returns a value with every bit + /// set to `1`. + /// + /// let allOnes = ~UInt8.min // 0b11111111 + /// + /// - Complexity: O(1). @_transparent public static prefix func ~ (x: Self) -> Self { return 0 &- x &- 1 @@ -2215,6 +2282,26 @@ ${operatorComment(x.nonMaskingOperator, True)} } extension FixedWidthInteger { + /// Creates a new instance with the representable value that's closest to the + /// given integer. + /// + /// If the value passed as `source` is greater than the maximum representable + /// value in this type, the result is the type's `max` value. If `source` is + /// less than the smallest representable value in this type, the result is + /// the type's `min` value. + /// + /// In this example, `x` is initialized as an `Int8` instance by clamping + /// `500` to the range `-128...127`, and `y` is initialized as a `UInt` + /// instance by clamping `-500` to the range `0...UInt.max`. + /// + /// let x = Int8(clamping: 500) + /// // x == 127 + /// // x == Int8.max + /// + /// let y = UInt(clamping: -500) + /// // y == 0 + /// + /// - Parameter source: An integer to convert to this type. @_semantics("optimize.sil.specialize.generic.partial.never") public init(clamping source: Other) { if _slowPath(source < Self.min) { @@ -2261,6 +2348,42 @@ ${unsafeOperationComment(x.operator)} } % end + /// Creates a new instance from the bit pattern of the given instance by + /// sign-extending or truncating to fit this type. + /// + /// When the bit width of `T` (the type of `source`) is equal to or greater + /// than this type's bit width, the result is the truncated + /// least-significant bits of `source`. For example, when converting a + /// 16-bit value to an 8-bit type, only the lower 8 bits of `source` are + /// used. + /// + /// let p: Int16 = -500 + /// // 'p' has a binary representation of 11111110_00001100 + /// let q = Int8(extendingOrTruncating: p) + /// // q == 12 + /// // 'q' has a binary representation of 00001100 + /// + /// When the bit width of `T` is less than this type's bit width, the result + /// is *sign-extended* to fill the remaining bits. That is, if `source` is + /// negative, the result is padded with ones; otherwise, the result is + /// padded with zeros. + /// + /// let u: Int8 = 21 + /// // 'u' has a binary representation of 00010101 + /// let v = Int16(extendingOrTruncating: u) + /// // v == 21 + /// // 'v' has a binary representation of 00000000_00010101 + /// + /// let w: Int8 = -21 + /// // 'w' has a binary representation of 11101011 + /// let x = Int16(extendingOrTruncating: w) + /// // x == -21 + /// // 'x' has a binary representation of 11111111_11101011 + /// let y = UInt16(extendingOrTruncating: w) + /// // y == 65515 + /// // 'y' has a binary representation of 11111111_11101011 + /// + /// - Parameter source: An integer to convert to this type. @inline(__always) public init(truncatingIfNeeded source: T) { if Self.bitWidth <= ${word_bits} { @@ -2373,6 +2496,21 @@ extension UnsignedInteger where Self : FixedWidthInteger { self.init(truncatingIfNeeded: source) } + /// Creates a new instance from the given integer, if it can be represented + /// exactly. + /// + /// If the value passed as `source` is not representable exactly, the result + /// is `nil`. In the following example, the constant `x` is successfully + /// created from a value of `100`, while the attempt to initialize the + /// constant `y` from `1_000` fails because the `Int8` type can represent + /// `127` at maximum: + /// + /// let x = Int8(exactly: 100) + /// // x == Optional(100) + /// let y = Int8(exactly: 1_000) + /// // y == nil + /// + /// - Parameter source: A value to convert to this type of integer. @_semantics("optimize.sil.specialize.generic.partial.never") @inline(__always) public init?(exactly source: T) { @@ -2454,6 +2592,21 @@ extension SignedInteger where Self : FixedWidthInteger { self.init(truncatingIfNeeded: source) } + /// Creates a new instance from the given integer, if it can be represented + /// exactly. + /// + /// If the value passed as `source` is not representable exactly, the result + /// is `nil`. In the following example, the constant `x` is successfully + /// created from a value of `100`, while the attempt to initialize the + /// constant `y` from `1_000` fails because the `Int8` type can represent + /// `127` at maximum: + /// + /// let x = Int8(exactly: 100) + /// // x == Optional(100) + /// let y = Int8(exactly: 1_000) + /// // y == nil + /// + /// - Parameter source: A value to convert to this type of integer. @_semantics("optimize.sil.specialize.generic.partial.never") @inline(__always) public init?(exactly source: T) { @@ -2557,6 +2710,26 @@ public struct ${Self} #if !os(Windows) && (arch(i386) || arch(x86_64)) % end + /// Creates an integer from the given floating-point value, rounding toward + /// zero. + /// + /// Any fractional part of the value passed as `source` is removed, rounding + /// the value toward zero. + /// + /// let x = Int(21.5) + /// // x == 21 + /// let y = Int(-21.5) + /// // y == -21 + /// + /// If `source` is outside the bounds of this type after rounding toward + /// zero, a runtime error may occur. + /// + /// let z = UInt(-21.5) + /// // Error: ...the result would be less than UInt.min + /// + /// - Parameter source: A floating-point value to convert to an integer. + /// `source` must be representable in this type after rounding toward + /// zero. @_transparent public init(_ source: ${FloatType}) { _precondition(source.isFinite, @@ -2568,6 +2741,20 @@ public struct ${Self} self._value = Builtin.fpto${u}i_FPIEEE${FloatBits}_${BuiltinName}(source._value) } + /// Creates an integer from the given floating-point value, if it can be + /// represented exactly. + /// + /// If the value passed as `source` is not representable exactly, the result + /// is `nil`. In the following example, the constant `x` is successfully + /// created from a value of `21.0`, while the attempt to initialize the + /// constant `y` from `21.5` fails: + /// + /// let x = Int(exactly: 21.0) + /// // x == Optional(21) + /// let y = Int(exactly: 21.5) + /// // y == nil + /// + /// - 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) @@ -2597,6 +2784,7 @@ public struct ${Self} // unwrapped. // See corresponding definitions in the FixedWidthInteger extension. % for x in binaryArithmetic['Numeric'] + binaryArithmetic["BinaryInteger"][:1]: +${assignmentOperatorComment(x.operator, True)} @_transparent public static func ${x.operator}=(_ lhs: inout ${Self}, _ rhs: ${Self}) { % if x.kind == '/': @@ -2628,6 +2816,7 @@ public struct ${Self} % for x in chain(*binaryArithmetic.values()): +${overflowOperationComment(x.operator)} @_transparent public func ${x.name}ReportingOverflow( ${x.firstArg} other: ${Self} @@ -2660,6 +2849,7 @@ public struct ${Self} } % end +${assignmentOperatorComment('%', True)} @_transparent public static func %=(_ lhs: inout ${Self}, _ rhs: ${Self}) { // No LLVM primitives for checking overflow of division @@ -2694,6 +2884,7 @@ public struct ${Self} } % for x in binaryBitwise: +${assignmentOperatorComment(x.operator, True)} @_transparent public static func ${x.operator}=(_ lhs: inout ${Self}, _ rhs: ${Self}) { lhs = ${Self}(Builtin.${x.llvmName}_Int${bits}(lhs._value, rhs._value)) @@ -2712,9 +2903,26 @@ ${assignmentOperatorComment(x.operator, True)} % end + /// The number of bits used for the underlying binary representation of + /// values of this type. + /// +% if self_type.is_word: + /// The bit width of ${Article.lower()} `${Self}` instance is 32 on 32-bit + /// platforms and 64 on 64-bit platforms. +% else: + /// The bit width of ${Article.lower()} `${Self}` instance is ${bits}. +% end @_transparent public static var bitWidth : Int { return ${bits} } + /// The number of leading zeros in this value's binary representation. + /// + /// For example, in an integer type with a `bitWidth` value of 8, + /// the number *31* has three leading zeros. + /// + /// let x: Int8 = 0b0001_1111 + /// // x == 31 + /// // x.leadingZeroBitCount == 3 @_transparent public var leadingZeroBitCount: Int { return Int( @@ -2723,6 +2931,13 @@ ${assignmentOperatorComment(x.operator, True)} )._lowWord._value) } + /// The number of trailing zeros in this value's binary representation. + /// + /// For example, the number *-8* has three trailing zeros. + /// + /// let x = Int8(bitPattern: 0b1111_1000) + /// // x == -8 + /// // x.trailingZeroBitCount == 3 @_transparent public var trailingZeroBitCount: Int { return Int( @@ -2731,6 +2946,14 @@ ${assignmentOperatorComment(x.operator, True)} )._lowWord._value) } + /// The number of bits equal to 1 in this value's binary representation. + /// + /// For example, in a fixed-width integer type with a `bitWidth` value of 8, + /// the number *31* has five bits equal to *1*. + /// + /// let x: Int8 = 0b0001_1111 + /// // x == 31 + /// // x.nonzeroBitCount == 5 @_transparent public var nonzeroBitCount: Int { return Int( @@ -2777,6 +3000,13 @@ ${assignmentOperatorComment(x.operator, True)} } } + /// A collection containing the words of this value's binary + /// representation, in order from the least significant to most significant. +% if signed: + /// + /// Negative values are returned in two's complement representation, + /// regardless of the type's underlying implementation. +% end @_transparent public var words: Words { return Words(self) @@ -2802,6 +3032,21 @@ ${assignmentOperatorComment(x.operator, True)} public typealias Magnitude = ${U}${Self} % if signed: + /// The magnitude of this value. + /// + /// For any numeric value `x`, `x.magnitude` is the absolute value of `x`. + /// You can use the `magnitude` property in operations that are simpler to + /// implement in terms of unsigned values, such as printing the value of an + /// integer, which is just printing a '-' character in front of an absolute + /// value. + /// + /// let x = -200 + /// // x.magnitude == 200 + /// + /// The global `abs(_:)` function provides more familiar syntax when you need + /// to find an absolute value. In addition, because `abs(_:)` always returns + /// a value of the same type, even in a generic context, using the function + /// instead of the `magnitude` property is encouraged. @_transparent public var magnitude: U${Self} { let base = U${Self}(_value) @@ -2810,6 +3055,34 @@ ${assignmentOperatorComment(x.operator, True)} % end % dbits = bits*2 + /// Returns a tuple containing the high and low parts of the result of + /// multiplying this value by the given value. + /// + /// Use this method to calculate the full result of a product that would + /// otherwise overflow. Unlike traditional truncating multiplication, the + /// `multipliedFullWidth(by:)` method returns a tuple + /// containing both the `high` and `low` parts of the product of this value and + /// `other`. The following example uses this method to multiply two `UInt8` + /// values that normally overflow when multiplied: + /// + /// let x: UInt8 = 100 + /// let y: UInt8 = 20 + /// let result = x.multipliedFullWidth(by: y) + /// // result.high == 0b00000111 + /// // result.low == 0b11010000 + /// + /// The product of `x` and `y` is 2000, which is too large to represent in a + /// `UInt8` instance. The `high` and `low` properties of the `result` value + /// represent 2000 when concatenated to form a double-width integer; that + /// is, using `result.high` as the high byte and `result.low` as the low byte + /// of a `UInt16` instance. + /// + /// let z = UInt16(result.high) << 8 | UInt16(result.low) + /// // z == 2000 + /// + /// - Parameter other: The value to multiply this value by. + /// - Returns: A tuple containing the high and low parts of the result of + /// multiplying this value and `other`. // FIXME(integers): tests public func multipliedFullWidth(by other: ${Self}) -> (high: ${Self}, low: ${Self}.Magnitude) { @@ -2830,6 +3103,18 @@ ${assignmentOperatorComment(x.operator, True)} % end } + /// Returns a tuple containing the quotient and remainder of dividing the + /// given value by this value. + /// + /// The resulting quotient must be representable within the bounds of the + /// type. If the quotient of dividing `dividend` by this value is too large + /// to represent in the type, a runtime error may occur. + /// + /// - Parameter dividend: A tuple containing the high and low parts of a + /// double-width integer. The `high` component of the value carries the + /// sign, if the type is signed. + /// - Returns: A tuple containing the quotient and remainder of `dividend` + /// divided by this value. // FIXME(integers): tests public func dividingFullWidth( _ dividend: (high: ${Self}, low: ${Self}.Magnitude) @@ -2912,6 +3197,11 @@ ${assignmentOperatorComment(x.operator, True)} @available(swift, obsoleted: 4) public static var _sizeInBytes: ${Self} { return ${bits}/8 } + /// Returns `-1` if this value is negative and `1` if it's positive; + /// otherwise, `0`. + /// + /// - Returns: The sign of this number, expressed as an integer of the same + /// type. @inline(__always) public func signum() -> ${Self} { let isPositive = ${Self}(Builtin.zext_Int1_Int${bits}( @@ -2922,6 +3212,26 @@ ${assignmentOperatorComment(x.operator, True)} %# end of concrete type: ${Self} extension ${Self} { + /// Creates an integer from the given floating-point value, rounding toward + /// zero. + /// + /// Any fractional part of the value passed as `source` is removed, rounding + /// the value toward zero. + /// + /// let x = Int(21.5) + /// // x == 21 + /// let y = Int(-21.5) + /// // y == -21 + /// + /// If `source` is outside the bounds of this type after rounding toward + /// zero, a runtime error may occur. + /// + /// let z = UInt(-21.5) + /// // Error: ...the result would be less than UInt.min + /// + /// - Parameter source: A floating-point value to convert to an integer. + /// `source` must be representable in this type after rounding toward + /// zero. // FIXME(integers): implement me in a less terrible way public init(_ source: T) { % for (FloatType, FloatBits) in [ @@ -3016,6 +3326,7 @@ extension ${Self} { % for x in binaryBitwise + maskingShifts + list(chain(*binaryArithmetic.values())): +${operatorComment(x.operator, True)} @_transparent public static func ${x.operator}(_ lhs: ${Self}, _ rhs: ${Self}) -> ${Self} { var lhs = lhs @@ -3027,6 +3338,7 @@ extension ${Self} { % for op in maskingShifts: +${operatorComment(x.operator, True)} @available(swift, obsoleted: 4) @_transparent public static func ${op.nonMaskingOperator}( @@ -3037,6 +3349,7 @@ extension ${Self} { return lhs } +${assignmentOperatorComment(x.operator, True)} @available(swift, obsoleted: 4) @_transparent public static func ${op.nonMaskingOperator}=( diff --git a/stdlib/public/core/StringIndexConversions.swift b/stdlib/public/core/StringIndexConversions.swift index e23cb51fcdc26..1039184d6c2b3 100644 --- a/stdlib/public/core/StringIndexConversions.swift +++ b/stdlib/public/core/StringIndexConversions.swift @@ -16,9 +16,7 @@ extension String.Index { /// /// If the index passed as `sourcePosition` represents the start of an /// extended grapheme cluster---the element type of a string---then the - /// initializer succeeds. If the index instead represents the position of a - /// Unicode scalar within an extended grapheme cluster or the position of an - /// encoded Unicode scalar value, the result is `nil`. + /// initializer succeeds. /// /// The following example converts the position of the Unicode scalar `"e"` /// into its corresponding position in the string. The character at that @@ -43,7 +41,7 @@ extension String.Index { /// let nextScalarsIndex = cafe.unicodeScalars.index(after: scalarsIndex) /// let nextStringIndex = String.Index(nextScalarsIndex, within: cafe) /// - /// print(nextIndex) + /// print(nextStringIndex) /// // Prints "nil" /// /// - Parameters: diff --git a/stdlib/public/core/UnsafePointer.swift.gyb b/stdlib/public/core/UnsafePointer.swift.gyb index bfac62028c873..cb645943271d8 100644 --- a/stdlib/public/core/UnsafePointer.swift.gyb +++ b/stdlib/public/core/UnsafePointer.swift.gyb @@ -1180,9 +1180,9 @@ extension Int { /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_inlineable - public init(bitPattern: ${Self}?) { - if let bitPattern = bitPattern { - self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue)) + public init(bitPattern pointer: ${Self}?) { + if let pointer = pointer { + self = Int(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 } @@ -1198,9 +1198,9 @@ extension UInt { /// - Parameter pointer: The pointer to use as the source for the new /// integer. @_inlineable - public init(bitPattern: ${Self}?) { - if let bitPattern = bitPattern { - self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue)) + public init(bitPattern pointer: ${Self}?) { + if let pointer = pointer { + self = UInt(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 } diff --git a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb index 5d9f6122deb2e..e496ac27b8e64 100644 --- a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb @@ -507,8 +507,8 @@ public struct Unsafe${Mutable}RawBufferPointer /// Initializes the buffer's memory with the given elements, binding the /// initialized memory to the elements' type. /// - /// When calling the `initialize(as:from:)` method on a buffer `b`, the - /// memory referenced by `b` must be uninitialized or initialized to a + /// When calling the `initializeMemory(as:from:)` method on a buffer `b`, + /// the memory referenced by `b` must be uninitialized or initialized to a /// trivial type, and must be properly aligned for accessing `S.Element`. /// The buffer must contain sufficient memory to accommodate /// `source.underestimatedCount`. diff --git a/stdlib/public/core/UnsafeRawPointer.swift.gyb b/stdlib/public/core/UnsafeRawPointer.swift.gyb index e439b3b8d9fee..52320b5bc6536 100644 --- a/stdlib/public/core/UnsafeRawPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawPointer.swift.gyb @@ -981,10 +981,17 @@ extension OpaquePointer { } extension Int { + /// Creates a new value with the bit pattern of the given pointer. + /// + /// The new value represents the address of the pointer passed as `pointer`. + /// If `pointer` is `nil`, the result is `0`. + /// + /// - Parameter pointer: The pointer to use as the source for the new + /// integer. @_inlineable - public init(bitPattern: Unsafe${Mutable}RawPointer?) { - if let bitPattern = bitPattern { - self = Int(Builtin.ptrtoint_Word(bitPattern._rawValue)) + public init(bitPattern pointer: Unsafe${Mutable}RawPointer?) { + if let pointer = pointer { + self = Int(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 } @@ -992,10 +999,17 @@ extension Int { } extension UInt { + /// Creates a new value with the bit pattern of the given pointer. + /// + /// The new value represents the address of the pointer passed as `pointer`. + /// If `pointer` is `nil`, the result is `0`. + /// + /// - Parameter pointer: The pointer to use as the source for the new + /// integer. @_inlineable - public init(bitPattern: Unsafe${Mutable}RawPointer?) { - if let bitPattern = bitPattern { - self = UInt(Builtin.ptrtoint_Word(bitPattern._rawValue)) + public init(bitPattern pointer: Unsafe${Mutable}RawPointer?) { + if let pointer = pointer { + self = UInt(Builtin.ptrtoint_Word(pointer._rawValue)) } else { self = 0 }