diff --git a/stdlib/public/core/Builtin.swift b/stdlib/public/core/Builtin.swift index 022bfe57a0cf7..869349cc708c3 100644 --- a/stdlib/public/core/Builtin.swift +++ b/stdlib/public/core/Builtin.swift @@ -246,18 +246,26 @@ public func _unsafeReferenceCast(_ x: T, to: U.Type) -> U { return Builtin.castReference(x) } -/// - returns: `x as T`. +/// Returns the given instance cast unconditionally to the specified type. /// -/// - Precondition: `x is T`. In particular, in -O builds, no test is -/// performed to ensure that `x` actually has dynamic type `T`. +/// The instance passed as `x` must be an instance of type `T`. /// -/// - Warning: Trades safety for performance. Use `unsafeDowncast` -/// only when `x as! T` has proven to be a performance problem and you -/// are confident that, always, `x is T`. It is better than an -/// `unsafeBitCast` because it's more restrictive, and because -/// checking is still performed in debug builds. +/// Use this function instead of `unsafeBitcast(_:to:)` because this function +/// is more restrictive and still performs a check in debug builds. In -O +/// builds, no test is performed to ensure that `x` actually has the dynamic +/// type `T`. +/// +/// - Warning: This function trades safety for performance. Use +/// `unsafeDowncast(_:to:)` only when you are confident that `x is T` always +/// evaluates to `true`, and only after `x as! T` has proven to be a +/// performance problem. +/// +/// - Parameters: +/// - x: An instance to cast to type `T`. +/// - type: The type `T` to which `x` is cast. +/// - Returns: The instance `x`, cast to type `T`. @_transparent -public func unsafeDowncast(_ x: AnyObject, to: T.Type) -> T { +public func unsafeDowncast(_ x: AnyObject, to type: T.Type) -> T { _debugPrecondition(x is T, "invalid unsafeDowncast") return Builtin.castReference(x) } @@ -337,7 +345,6 @@ func swift_class_getInstanceExtents(_ theClass: AnyClass) func swift_objc_class_unknownGetInstanceExtents(_ theClass: AnyClass) -> (negative: UInt, positive: UInt) -/// - Returns: @inline(__always) internal func _class_getInstancePositiveExtentSize(_ theClass: AnyClass) -> Int { #if _runtime(_ObjC) diff --git a/stdlib/public/core/Codable.swift b/stdlib/public/core/Codable.swift index fcc1b9a7512f0..cc23d9f094f74 100644 --- a/stdlib/public/core/Codable.swift +++ b/stdlib/public/core/Codable.swift @@ -51,19 +51,21 @@ public protocol CodingKey: CustomStringConvertible, CustomDebugStringConvertible /// The string to use in a named collection (e.g. a string-keyed dictionary). var stringValue: String { get } - /// Initializes `self` from a string. + /// Creates a new instance from the given string. + /// + /// If the string passed as `stringValue` does not correspond to any instance of this type, the result is `nil`. /// /// - parameter stringValue: The string value of the desired key. - /// - returns: An instance of `Self` from the given string, or `nil` if the given string does not correspond to any instance of `Self`. init?(stringValue: String) - /// The int to use in an indexed collection (e.g. an int-keyed dictionary). + /// The value to use in an integer-indexed collection (e.g. an int-keyed dictionary). var intValue: Int? { get } - /// Initializes `self` from an integer. + /// Creates a new instance from the specified integer. + /// + /// If the value passed as `intValue` does not correspond to any instance of this type, the result is `nil`. /// /// - parameter intValue: The integer value of the desired key. - /// - returns: An instance of `Self` from the given integer, or `nil` if the given integer does not correspond to any instance of `Self`. init?(intValue: Int) } @@ -87,7 +89,6 @@ extension CodingKey { /// A type that can encode values into a native format for external representation. public protocol Encoder { /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Any contextual information set by the user for encoding. @@ -95,53 +96,51 @@ public protocol Encoder { /// Returns an encoding container appropriate for holding multiple values keyed by the given key type. /// + /// You must use only one kind of top-level encoding container. This method must not be called after a call to `unkeyedContainer()` or after encoding a value through a call to `singleValueContainer()` + /// /// - parameter type: The key type to use for the container. /// - returns: A new keyed encoding container. - /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func container(keyedBy type: Key.Type) -> KeyedEncodingContainer /// Returns an encoding container appropriate for holding multiple unkeyed values. /// + /// You must use only one kind of top-level encoding container. This method must not be called after a call to `container(keyedBy:)` or after encoding a value through a call to `singleValueContainer()` + /// /// - returns: A new empty unkeyed container. - /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func unkeyedContainer() -> UnkeyedEncodingContainer /// Returns an encoding container appropriate for holding a single primitive value. /// + /// You must use only one kind of top-level encoding container. This method must not be called after a call to `unkeyedContainer()` or `container(keyedBy:)`, or after encoding a value through a call to `singleValueContainer()` + /// /// - returns: A new empty single value container. - /// - precondition: May not be called after a prior `self.container(keyedBy:)` call. - /// - precondition: May not be called after a prior `self.unkeyedContainer()` call. - /// - precondition: May not be called after a value has been encoded through a previous `self.singleValueContainer()` call. func singleValueContainer() -> SingleValueEncodingContainer } /// A type that can decode values from a native format into in-memory representations. public protocol Decoder { /// The path of coding keys taken to get to this point in decoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Any contextual information set by the user for decoding. var userInfo: [CodingUserInfoKey : Any] { get } - /// Returns the data stored in `self` as represented in a container keyed by the given key type. + /// Returns the data stored in this decoder as represented in a container keyed by the given key type. /// /// - parameter type: The key type to use for the container. - /// - returns: A keyed decoding container view into `self`. + /// - returns: A keyed decoding container view into this decoder. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a keyed container. func container(keyedBy type: Key.Type) throws -> KeyedDecodingContainer - /// Returns the data stored in `self` as represented in a container appropriate for holding values with no keys. + /// Returns the data stored in this decoder as represented in a container appropriate for holding values with no keys. /// - /// - returns: An unkeyed container view into `self`. + /// - returns: An unkeyed container view into this decoder. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not an unkeyed container. func unkeyedContainer() throws -> UnkeyedDecodingContainer - /// Returns the data stored in `self` as represented in a container appropriate for holding a single primitive value. + /// Returns the data stored in this decoder as represented in a container appropriate for holding a single primitive value. /// - /// - returns: A single value container view into `self`. + /// - returns: A single value container view into this decoder. /// - throws: `DecodingError.typeMismatch` if the encountered stored value is not a single value container. func singleValueContainer() throws -> SingleValueDecodingContainer } @@ -159,7 +158,6 @@ public protocol KeyedEncodingContainerProtocol { associatedtype Key : CodingKey /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Encodes a null value for the given key. @@ -275,7 +273,7 @@ public protocol KeyedEncodingContainerProtocol { /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// - /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. + /// For encoders which don't support this feature, the default implementation encodes the given object unconditionally. /// /// - parameter object: The object to encode. /// - parameter key: The key to associate the object with. @@ -400,17 +398,17 @@ public protocol KeyedEncodingContainerProtocol { /// - returns: A new unkeyed encoding container. mutating func nestedUnkeyedContainer(forKey key: Key) -> UnkeyedEncodingContainer - /// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container. + /// Stores a new nested container for the default `super` key and returns A new encoder instance for encoding `super` into that container. /// /// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// - /// - returns: A new `Encoder` to pass to `super.encode(to:)`. + /// - returns: A new encoder to pass to `super.encode(to:)`. mutating func superEncoder() -> Encoder - /// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container. + /// Stores a new nested container for the given key and returns A new encoder instance for encoding `super` into that container. /// /// - parameter key: The key to encode `super` for. - /// - returns: A new `Encoder` to pass to `super.encode(to:)`. + /// - returns: A new encoder to pass to `super.encode(to:)`. mutating func superEncoder(forKey key: Key) -> Encoder } @@ -425,7 +423,7 @@ public struct KeyedEncodingContainer : KeyedEncodingContainerProt @_versioned internal var _box: _KeyedEncodingContainerBase - /// Initializes `self` with the given container. + /// Creates a new instance with the given container. /// /// - parameter container: The container to hold. public init(_ container: Container) where Container.Key == Key { @@ -433,7 +431,6 @@ public struct KeyedEncodingContainer : KeyedEncodingContainerProt } /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. public var codingPath: [CodingKey] { return _box.codingPath } @@ -583,7 +580,7 @@ public struct KeyedEncodingContainer : KeyedEncodingContainerProt /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// - /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. + /// For encoders which don't support this feature, the default implementation encodes the given object unconditionally. /// /// - parameter object: The object to encode. /// - parameter key: The key to associate the object with. @@ -744,19 +741,19 @@ public struct KeyedEncodingContainer : KeyedEncodingContainerProt return _box.nestedUnkeyedContainer(forKey: key) } - /// Stores a new nested container for the default `super` key and returns a new `Encoder` instance for encoding `super` into that container. + /// Stores a new nested container for the default `super` key and returns A new encoder instance for encoding `super` into that container. /// /// Equivalent to calling `superEncoder(forKey:)` with `Key(stringValue: "super", intValue: 0)`. /// - /// - returns: A new `Encoder` to pass to `super.encode(to:)`. + /// - returns: A new encoder to pass to `super.encode(to:)`. public mutating func superEncoder() -> Encoder { return _box.superEncoder() } - /// Stores a new nested container for the given key and returns a new `Encoder` instance for encoding `super` into that container. + /// Stores a new nested container for the given key and returns A new encoder instance for encoding `super` into that container. /// /// - parameter key: The key to encode `super` for. - /// - returns: A new `Encoder` to pass to `super.encode(to:)`. + /// - returns: A new encoder to pass to `super.encode(to:)`. public mutating func superEncoder(forKey key: Key) -> Encoder { return _box.superEncoder(forKey: key) } @@ -771,7 +768,6 @@ public protocol KeyedDecodingContainerProtocol { associatedtype Key : CodingKey /// The path of coding keys taken to get to this point in decoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// All the keys the `Decoder` has for this container. @@ -779,9 +775,9 @@ public protocol KeyedDecodingContainerProtocol { /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. var allKeys: [Key] { get } - /// Returns whether the `Decoder` contains a value associated with the given key. + /// Returns a Boolean value indicating whether the decoder contains a value associated with the given key. /// - /// The value associated with the given key may be a null value as appropriate for the data format. + /// The value associated with `key` may be a null value as appropriate for the data format. /// /// - parameter key: The key to search for. /// - returns: Whether the `Decoder` has an entry for the given key. @@ -1138,7 +1134,7 @@ public struct KeyedDecodingContainer : KeyedDecodingContainerProt @_versioned internal var _box: _KeyedDecodingContainerBase - /// Initializes `self` with the given container. + /// Creates a new instance with the given container. /// /// - parameter container: The container to hold. public init(_ container: Container) where Container.Key == Key { @@ -1146,19 +1142,18 @@ public struct KeyedDecodingContainer : KeyedDecodingContainerProt } /// The path of coding keys taken to get to this point in decoding. - /// A `nil` value indicates an unkeyed container. public var codingPath: [CodingKey] { return _box.codingPath } - /// All the keys the `Decoder` has for this container. + /// All the keys the decoder has for this container. /// - /// Different keyed containers from the same `Decoder` may return different keys here; it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. + /// Different keyed containers from the same decoder may return different keys here, because it is possible to encode with multiple key types which are not convertible to one another. This should report all keys present which are convertible to the requested type. public var allKeys: [Key] { return _box.allKeys } - /// Returns whether the `Decoder` contains a value associated with the given key. + /// Returns a Boolean value indicating whether the decoder contains a value associated with the given key. /// /// The value associated with the given key may be a null value as appropriate for the data format. /// @@ -1588,7 +1583,6 @@ public struct KeyedDecodingContainer : KeyedDecodingContainerProt /// their format. public protocol UnkeyedEncodingContainer { /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// The number of elements encoded into the container. @@ -1691,7 +1685,7 @@ public protocol UnkeyedEncodingContainer { /// Encodes a reference to the given object only if it is encoded unconditionally elsewhere in the payload (previously, or in the future). /// - /// For `Encoder`s which don't support this feature, the default implementation encodes the given object unconditionally. + /// For encoders which don't support this feature, the default implementation encodes the given object unconditionally. /// /// For formats which don't support this feature, the default implementation encodes the given object unconditionally. /// @@ -1802,7 +1796,7 @@ public protocol UnkeyedEncodingContainer { /// Encodes a nested container and returns an `Encoder` instance for encoding `super` into that container. /// - /// - returns: A new `Encoder` to pass to `super.encode(to:)`. + /// - returns: A new encoder to pass to `super.encode(to:)`. mutating func superEncoder() -> Encoder } @@ -1813,13 +1807,14 @@ public protocol UnkeyedEncodingContainer { /// their format. public protocol UnkeyedDecodingContainer { /// The path of coding keys taken to get to this point in decoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } - /// Returns the number of elements (if known) contained within this container. + /// The number of elements contained within this container. + /// + /// If the number of elements is unknown, the value is `nil`. var count: Int? { get } - /// Returns whether there are no more elements left to be decoded in the container. + /// A Boolean value indicating whether there are no more elements left to be decoded in the container. var isAtEnd: Bool { get } /// The current decoding index of the container (i.e. the index of the next element to be decoded.) @@ -2117,7 +2112,6 @@ public protocol UnkeyedDecodingContainer { /// non-keyed value. public protocol SingleValueEncodingContainer { /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Encodes a null value. @@ -2235,7 +2229,6 @@ public protocol SingleValueEncodingContainer { /// A `SingleValueDecodingContainer` is a container which can support the storage and direct decoding of a single non-keyed value. public protocol SingleValueDecodingContainer { /// The path of coding keys taken to get to this point in encoding. - /// A `nil` value indicates an unkeyed container. var codingPath: [CodingKey] { get } /// Decodes a null value. @@ -2375,14 +2368,14 @@ public struct CodingUserInfoKey : RawRepresentable, Equatable, Hashable { /// The key's string value. public let rawValue: String - /// Initializes `self` with the given raw value. + /// Creates a new instance with the given raw value. /// /// - parameter rawValue: The value of the key. public init?(rawValue: String) { self.rawValue = rawValue } - /// Returns whether the given keys are equal. + /// Returns a Boolean value indicating whether the given keys are equal. /// /// - parameter lhs: The key to compare against. /// - parameter rhs: The key to compare with. @@ -2404,7 +2397,7 @@ public struct CodingUserInfoKey : RawRepresentable, Equatable, Hashable { public enum EncodingError : Error { /// The context in which the error occurred. public struct Context { - /// The path of `CodingKey`s taken to get to the point of the failing encode call. + /// The path of coding keys taken to get to the point of the failing encode call. public let codingPath: [CodingKey] /// A description of what went wrong, for debugging purposes. @@ -2413,9 +2406,9 @@ public enum EncodingError : Error { /// The underlying error which caused this error, if any. public let underlyingError: Error? - /// Initializes `self` with the given path of `CodingKey`s and a description of what went wrong. + /// Creates a new context with the given path of coding keys and a description of what went wrong. /// - /// - parameter codingPath: The path of `CodingKey`s taken to get to the point of the failing encode call. + /// - parameter codingPath: The path of coding keys taken to get to the point of the failing encode call. /// - parameter debugDescription: A description of what went wrong, for debugging purposes. /// - parameter underlyingError: The underlying error which caused this error, if any. public init(codingPath: [CodingKey], debugDescription: String, underlyingError: Error? = nil) { @@ -2425,9 +2418,9 @@ public enum EncodingError : Error { } } - /// `.invalidValue` indicates that an `Encoder` or its containers could not encode the given value. + /// An indication that an encoder or its containers could not encode the given value. /// - /// Contains the attempted value, along with context for debugging. + /// As associated values, this case contains the attempted value and context for debugging. case invalidValue(Any, Context) // MARK: - NSError Bridging @@ -2473,7 +2466,7 @@ public enum EncodingError : Error { public enum DecodingError : Error { /// The context in which the error occurred. public struct Context { - /// The path of `CodingKey`s taken to get to the point of the failing decode call. + /// The path of coding keys taken to get to the point of the failing decode call. public let codingPath: [CodingKey] /// A description of what went wrong, for debugging purposes. @@ -2482,9 +2475,9 @@ public enum DecodingError : Error { /// The underlying error which caused this error, if any. public let underlyingError: Error? - /// Initializes `self` with the given path of `CodingKey`s and a description of what went wrong. + /// Creates a new context with the given path of coding keys and a description of what went wrong. /// - /// - parameter codingPath: The path of `CodingKey`s taken to get to the point of the failing decode call. + /// - parameter codingPath: The path of coding keys taken to get to the point of the failing decode call. /// - parameter debugDescription: A description of what went wrong, for debugging purposes. /// - parameter underlyingError: The underlying error which caused this error, if any. public init(codingPath: [CodingKey], debugDescription: String, underlyingError: Error? = nil) { @@ -2494,24 +2487,24 @@ public enum DecodingError : Error { } } - /// `.typeMismatch` indicates that a value of the given type could not be decoded because it did not match the type of what was found in the encoded payload. + /// An indication that a value of the given type could not be decoded because it did not match the type of what was found in the encoded payload. /// - /// Contains the attempted type, along with context for debugging. + /// As associated values, this case contains the attempted type and context for debugging. case typeMismatch(Any.Type, Context) - /// `.valueNotFound` indicates that a non-optional value of the given type was expected, but a null value was found. + /// An indication that a non-optional value of the given type was expected, but a null value was found. /// - /// Contains the attempted type, along with context for debugging. + /// As associated values, this case contains the attempted type and context for debugging. case valueNotFound(Any.Type, Context) - /// `.keyNotFound` indicates that a `KeyedDecodingContainer` was asked for an entry for the given key, but did not contain one. + /// An indication that a keyed decoding container was asked for an entry for the given key, but did not contain one. /// - /// Contains the attempted key, along with context for debugging. + /// As associated values, this case contains the attempted key and context for debugging. case keyNotFound(CodingKey, Context) - /// `.dataCorrupted` indicates that the data is corrupted or otherwise invalid. + /// An indication that the data is corrupted or otherwise invalid. /// - /// Contains context for debugging. + /// As an associated value, this case contains the context for debugging. case dataCorrupted(Context) // MARK: - NSError Bridging @@ -2576,37 +2569,40 @@ internal struct _GenericIndexKey : CodingKey { } public extension DecodingError { - /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. + /// Returns a new `.dataCorrupted` error using a constructed coding path and the given debug description. /// - /// Constructs a coding path by appending the given key to the given container's coding path. + /// The coding path for the returned error is constructed by appending the given key to the given container's coding path. /// /// - param key: The key which caused the failure. /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. + /// - Returns: A new `.dataCorrupted` error with the given information. static func dataCorruptedError(forKey key: C.Key, in container: C, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [key], debugDescription: debugDescription) return .dataCorrupted(context) } - /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. + /// Returns a new `.dataCorrupted` error using a constructed coding path and the given debug description. /// - /// Constructs a coding path by appending a nil key to the given container's coding path. + /// The coding path for the returned error is constructed by appending the given container's current index to its coding path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. + /// - Returns: A new `.dataCorrupted` error with the given information. static func dataCorruptedError(in container: UnkeyedDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath + [_GenericIndexKey(intValue: container.currentIndex)!], debugDescription: debugDescription) return .dataCorrupted(context) } - /// A convenience method which creates a new .dataCorrupted error using a constructed coding path and the given debug description. + /// Returns a new `.dataCorrupted` error using a constructed coding path and the given debug description. /// - /// Uses the given container's coding path as the constructed path. + /// The coding path for the returned error is the given container's coding path. /// /// - param container: The container in which the corrupted data was accessed. /// - param debugDescription: A description of the error to aid in debugging. + /// - Returns: A new `.dataCorrupted` error with the given information. static func dataCorruptedError(in container: SingleValueDecodingContainer, debugDescription: String) -> DecodingError { let context = DecodingError.Context(codingPath: container.codingPath, debugDescription: debugDescription) diff --git a/stdlib/public/core/Collection.swift b/stdlib/public/core/Collection.swift index 876a1ed9752df..312a36d86187e 100644 --- a/stdlib/public/core/Collection.swift +++ b/stdlib/public/core/Collection.swift @@ -445,18 +445,6 @@ public struct IndexingIterator< /// corresponding element. In the example above, `firstSpace` is used to /// extract the prefix that contains elements up to that index. /// -/// You can pass only valid indices to collection operations. You can find a -/// complete set of a collection's valid indices by starting with the -/// collection's `startIndex` property and finding every successor up to, and -/// including, the `endIndex` property. All other values of the `Index` type, -/// such as the `startIndex` property of a different collection, are invalid -/// indices for this collection. -/// -/// Saved indices may become invalid as a result of mutating operations. For -/// more information about index invalidation in mutable collections, see the -/// reference for the `MutableCollection` and `RangeReplaceableCollection` -/// protocols, as well as for the specific type you're using. -/// /// Accessing Individual Elements /// ============================= /// @@ -481,6 +469,18 @@ public struct IndexingIterator< /// print(text.first) /// // Prints "Optional("B")" /// +/// You can pass only valid indices to collection operations. You can find a +/// complete set of a collection's valid indices by starting with the +/// collection's `startIndex` property and finding every successor up to, and +/// including, the `endIndex` property. All other values of the `Index` type, +/// such as the `startIndex` property of a different collection, are invalid +/// indices for this collection. +/// +/// Saved indices may become invalid as a result of mutating operations. For +/// more information about index invalidation in mutable collections, see the +/// reference for the `MutableCollection` and `RangeReplaceableCollection` +/// protocols, as well as for the specific type you're using. +/// /// Accessing Slices of a Collection /// ================================ /// diff --git a/stdlib/public/core/CompilerProtocols.swift b/stdlib/public/core/CompilerProtocols.swift index 2eb12b3bc1223..2d76a661dc6a1 100644 --- a/stdlib/public/core/CompilerProtocols.swift +++ b/stdlib/public/core/CompilerProtocols.swift @@ -673,30 +673,8 @@ public protocol ExpressibleByDictionaryLiteral { /// Conforming to the ExpressibleByStringInterpolation Protocol /// =========================================================== /// -/// To use string interpolation to initialize instances of your custom type, -/// implement the required initializers for `ExpressibleByStringInterpolation` -/// conformance. String interpolation is a multiple-step initialization -/// process. When you use string interpolation, the following steps occur: -/// -/// 1. The string literal is broken into pieces. Each segment of the string -/// literal before, between, and after any included expressions, along with -/// the individual expressions themselves, are passed to the -/// `init(stringInterpolationSegment:)` initializer. -/// 2. The results of those calls are passed to the -/// `init(stringInterpolation:)` initializer in the order in which they -/// appear in the string literal. -/// -/// In other words, initializing the `message` constant in the example above -/// using string interpolation is equivalent to the following code: -/// -/// let message = String(stringInterpolation: -/// String(stringInterpolationSegment: "One cookie: $"), -/// String(stringInterpolationSegment: price), -/// String(stringInterpolationSegment: ", "), -/// String(stringInterpolationSegment: number), -/// String(stringInterpolationSegment: " cookies: $"), -/// String(stringInterpolationSegment: price * number), -/// String(stringInterpolationSegment: ".")) +/// The `ExpressibleByStringInterpolation` protocol is deprecated. Do not add +/// new conformances to the protocol. @available(*, deprecated, message: "it will be replaced or redesigned in Swift 4.0. Instead of conforming to 'ExpressibleByStringInterpolation', consider adding an 'init(_:String)'") public typealias ExpressibleByStringInterpolation = _ExpressibleByStringInterpolation public protocol _ExpressibleByStringInterpolation { diff --git a/stdlib/public/core/FloatingPoint.swift.gyb b/stdlib/public/core/FloatingPoint.swift.gyb index 620c89727c65e..fe9970431ea5e 100644 --- a/stdlib/public/core/FloatingPoint.swift.gyb +++ b/stdlib/public/core/FloatingPoint.swift.gyb @@ -1005,7 +1005,7 @@ public protocol FloatingPoint: SignedNumeric, Strideable, Hashable { /// The greatest representable value that compares less than this value. /// - /// For any finite value `x`, `x.nextDown` is greater than `x`. For `nan` or + /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or /// `-infinity`, `x.nextDown` is `x` itself. The following special cases /// also apply: /// @@ -1038,7 +1038,8 @@ public protocol FloatingPoint: SignedNumeric, Strideable, Hashable { /// /// - Parameter other: The value to compare with this value. /// - Returns: `true` if `other` has the same value as this instance; - /// otherwise, `false`. + /// otherwise, `false`. If either this value or `other` is NaN, the result + /// of this method is `false`. func isEqual(to other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than the @@ -1068,7 +1069,9 @@ public protocol FloatingPoint: SignedNumeric, Strideable, Hashable { /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. - /// - Returns: `true` if `other` is less than this value; otherwise, `false`. + /// - Returns: `true` if this value is less than `other`; otherwise, `false`. + /// If either this value or `other` is NaN, the result of this method is + /// `false`. func isLess(than other: Self) -> Bool /// Returns a Boolean value indicating whether this instance is less than or @@ -1096,24 +1099,24 @@ public protocol FloatingPoint: SignedNumeric, Strideable, Hashable { /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: The value to compare with this value. - /// - Returns: `true` if `other` is less than this value; otherwise, `false`. + /// - Returns: `true` if `other` is greater than this value; otherwise, + /// `false`. If either this value or `other` is NaN, the result of this + /// method is `false`. func isLessThanOrEqualTo(_ other: Self) -> Bool - /// Returns a Boolean value indicating whether this instance should precede the - /// given value in an ascending sort. + /// Returns a Boolean value indicating whether this instance should precede + /// or tie positions with the given value in an ascending sort. /// /// This relation is a refinement of the less-than-or-equal-to operator /// (`<=`) that provides a total order on all values of the type, including - /// noncanonical encodings, signed zeros, and NaNs. Because it is used much - /// less frequently than the usual comparisons, there is no operator form of - /// this relation. + /// signed zeros and NaNs. /// - /// The following example uses `isTotallyOrdered(below:)` to sort an array of - /// floating-point values, including some that are NaN: + /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an + /// array of floating-point values, including some that are NaN: /// /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] - /// numbers.sort { $0.isTotallyOrdered(below: $1) } - /// // numbers == [-9.5, 2.5, 3.0, 21.25, nan] + /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } + /// // numbers == [-9.5, 2.5, 3.0, 21.25, NaN] /// /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order /// relation as defined by the [IEEE 754 specification][spec]. @@ -1121,8 +1124,8 @@ public protocol FloatingPoint: SignedNumeric, Strideable, Hashable { /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 /// /// - Parameter other: A floating-point value to compare to this value. - /// - Returns: `true` if this value is ordered below `other` in a total - /// ordering of the floating-point type; otherwise, `false`. + /// - Returns: `true` if this value is ordered below or the same as `other` + /// in a total ordering of the floating-point type; otherwise, `false`. func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool /// A Boolean value indicating whether this instance is normal. @@ -1596,10 +1599,48 @@ public protocol BinaryFloatingPoint: FloatingPoint, ExpressibleByFloatLiteral { extension FloatingPoint { + /// The unit in the last place of 1.0. + /// + /// The positive difference between 1.0 and the next greater representable + /// number. The `ulpOfOne` constant corresponds to the C macros + /// `FLT_EPSILON`, `DBL_EPSILON`, and others with a similar purpose. public static var ulpOfOne: Self { return Self(1).ulp } + /// Returns this value rounded to an integral value using the specified + /// rounding rule. + /// + /// The following example rounds a value using four different rounding rules: + /// + /// let x = 6.5 + /// + /// // Equivalent to the C 'round' function: + /// print(x.rounded(.toNearestOrAwayFromZero)) + /// // Prints "7.0" + /// + /// // Equivalent to the C 'trunc' function: + /// print(x.rounded(.towardZero)) + /// // Prints "6.0" + /// + /// // Equivalent to the C 'ceil' function: + /// print(x.rounded(.up)) + /// // Prints "7.0" + /// + /// // Equivalent to the C 'floor' function: + /// print(x.rounded(.down)) + /// // Prints "6.0" + /// + /// For more information about the available rounding rules, see the + /// `FloatingPointRoundingRule` enumeration. To round a value using the + /// default "schoolbook rounding", you can use the shorter `rounded()` + /// method instead. + /// + /// print(x.rounded()) + /// // Prints "7.0" + /// + /// - Parameter rule: The rounding rule to use. + /// - Returns: The integral value found by rounding using `rule`. @_transparent public func rounded(_ rule: FloatingPointRoundingRule) -> Self { var lhs = self @@ -1658,11 +1699,52 @@ extension FloatingPoint { round(.toNearestOrAwayFromZero) } + /// The greatest representable value that compares less than this value. + /// + /// For any finite value `x`, `x.nextDown` is less than `x`. For `nan` or + /// `-infinity`, `x.nextDown` is `x` itself. The following special cases + /// also apply: + /// + /// - If `x` is `infinity`, then `x.nextDown` is `greatestFiniteMagnitude`. + /// - If `x` is `leastNonzeroMagnitude`, then `x.nextDown` is `0.0`. + /// - If `x` is zero, then `x.nextDown` is `-leastNonzeroMagnitude`. + /// - If `x` is `-greatestFiniteMagnitude`, then `x.nextDown` is `-infinity`. @_transparent public var nextDown: Self { return -(-self).nextUp } + /// Returns the remainder of this value divided by the given value using + /// truncating division. + /// + /// Performing truncating division with floating-point values results in a + /// truncated integer quotient and a remainder. For values `x` and `y` and + /// their truncated integer quotient `q`, the remainder `r` satisfies + /// `x == y * q + r`. + /// + /// The following example calculates the truncating remainder of dividing + /// 8.625 by 0.75: + /// + /// let x = 8.625 + /// print(x / 0.75) + /// // Prints "11.5" + /// + /// let q = (x / 0.75).rounded(.towardZero) + /// // q == 11.0 + /// let r = x.truncatingRemainder(dividingBy: 0.75) + /// // r == 0.375 + /// + /// let x1 = 0.75 * q + r + /// // x1 == 8.625 + /// + /// If this value and `other` are both finite numbers, the truncating + /// remainder has the same sign as this value and is strictly smaller in + /// magnitude than `other`. The `truncatingRemainder(dividingBy:)` method + /// is always exact. + /// + /// - Parameter other: The value to use when dividing this value. + /// - Returns: The remainder of this value divided by `other` using + /// truncating division. @_transparent public func truncatingRemainder(dividingBy other: Self) -> Self { var lhs = self @@ -1670,6 +1752,38 @@ extension FloatingPoint { return lhs } + /// Returns the remainder of this value divided by the given value. + /// + /// For two finite values `x` and `y`, the remainder `r` of dividing `x` by + /// `y` satisfies `x == y * q + r`, where `q` is the integer nearest to + /// `x / y`. If `x / y` is exactly halfway between two integers, `q` is + /// chosen to be even. Note that `q` is *not* `x / y` computed in + /// floating-point arithmetic, and that `q` may not be representable in any + /// available integer type. + /// + /// The following example calculates the remainder of dividing 8.625 by 0.75: + /// + /// let x = 8.625 + /// print(x / 0.75) + /// // Prints "11.5" + /// + /// let q = (x / 0.75).rounded(.toNearestOrEven) + /// // q == 12.0 + /// let r = x.remainder(dividingBy: 0.75) + /// // r == -0.375 + /// + /// let x1 = 0.75 * q + r + /// // x1 == 8.625 + /// + /// If this value and `other` are finite numbers, the remainder is in the + /// closed range `-abs(other / 2)...abs(other / 2)`. The + /// `remainder(dividingBy:)` method is always exact. This method implements + /// the remainder operation defined by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameter other: The value to use when dividing this value. + /// - Returns: The remainder of this value divided by `other`. @_transparent public func remainder(dividingBy other: Self) -> Self { var lhs = self @@ -1677,6 +1791,20 @@ extension FloatingPoint { return lhs } + /// Returns the square root of the value, rounded to a representable value. + /// + /// The following example declares a function that calculates the length of + /// the hypotenuse of a right triangle given its two perpendicular sides. + /// + /// func hypotenuse(_ a: Double, _ b: Double) -> Double { + /// return (a * a + b * b).squareRoot() + /// } + /// + /// let (dx, dy) = (3.0, 4.0) + /// let distance = hypotenuse(dx, dy) + /// // distance == 5.0 + /// + /// - Returns: The square root of the value. @_transparent public func squareRoot( ) -> Self { var lhs = self @@ -1684,6 +1812,19 @@ extension FloatingPoint { return lhs } + /// Returns the result of adding the product of the two given values to this + /// value, computed without intermediate rounding. + /// + /// This method is equivalent to the C `fma` function and implements the + /// `fusedMultiplyAdd` operation defined by the [IEEE 754 + /// specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - lhs: One of the values to multiply before adding to this value. + /// - rhs: The other value to multiply. + /// - Returns: The product of `lhs` and `rhs`, added to this value. @_transparent public func addingProduct(_ lhs: Self, _ rhs: Self) -> Self { var addend = self @@ -1691,6 +1832,33 @@ extension FloatingPoint { return addend } + /// Returns the lesser of the two given values. + /// + /// This method returns the minimum of two values, preserving order and + /// eliminating NaN when possible. For two values `x` and `y`, the result of + /// `minimum(x, y)` is `x` if `x <= y`, `y` if `y < x`, or whichever of `x` + /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are + /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. + /// + /// Double.minimum(10.0, -25.0) + /// // -25.0 + /// Double.minimum(10.0, .nan) + /// // 10.0 + /// Double.minimum(.nan, -25.0) + /// // -25.0 + /// Double.minimum(.nan, .nan) + /// // nan + /// + /// The `minimum` method implements the `minNum` operation defined by the + /// [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - x: A floating-point value. + /// - y: Another floating-point value. + /// - Returns: The minimum of `x` and `y`, or whichever is a number if the + /// other is NaN. public static func minimum(_ x: Self, _ y: Self) -> Self { if x.isSignalingNaN || y.isSignalingNaN { // Produce a quiet NaN matching platform arithmetic behavior. @@ -1700,6 +1868,33 @@ extension FloatingPoint { return y } + /// Returns the greater of the two given values. + /// + /// This method returns the maximum of two values, preserving order and + /// eliminating NaN when possible. For two values `x` and `y`, the result of + /// `maximum(x, y)` is `x` if `x > y`, `y` if `x <= y`, or whichever of `x` + /// or `y` is a number if the other is a quiet NaN. If both `x` and `y` are + /// NaN, or either `x` or `y` is a signaling NaN, the result is NaN. + /// + /// Double.maximum(10.0, -25.0) + /// // 10.0 + /// Double.maximum(10.0, .nan) + /// // 10.0 + /// Double.maximum(.nan, -25.0) + /// // -25.0 + /// Double.maximum(.nan, .nan) + /// // nan + /// + /// The `maximum` method implements the `maxNum` operation defined by the + /// [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - x: A floating-point value. + /// - y: Another floating-point value. + /// - Returns: The greater of `x` and `y`, or whichever is a number if the + /// other is NaN. public static func maximum(_ x: Self, _ y: Self) -> Self { if x.isSignalingNaN || y.isSignalingNaN { // Produce a quiet NaN matching platform arithmetic behavior. @@ -1709,6 +1904,35 @@ extension FloatingPoint { return y } + /// Returns the value with lesser magnitude. + /// + /// This method returns the value with lesser magnitude of the two given + /// values, preserving order and eliminating NaN when possible. For two + /// values `x` and `y`, the result of `minimumMagnitude(x, y)` is `x` if + /// `x.magnitude <= y.magnitude`, `y` if `y.magnitude < x.magnitude`, or + /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both + /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result + /// is NaN. + /// + /// Double.minimumMagnitude(10.0, -25.0) + /// // 10.0 + /// Double.minimumMagnitude(10.0, .nan) + /// // 10.0 + /// Double.minimumMagnitude(.nan, -25.0) + /// // -25.0 + /// Double.minimumMagnitude(.nan, .nan) + /// // nan + /// + /// The `minimumMagnitude` method implements the `minNumMag` operation + /// defined by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - x: A floating-point value. + /// - y: Another floating-point value. + /// - Returns: Whichever of `x` or `y` has lesser magnitude, or whichever is + /// a number if the other is NaN. public static func minimumMagnitude(_ x: Self, _ y: Self) -> Self { if x.isSignalingNaN || y.isSignalingNaN { // Produce a quiet NaN matching platform arithmetic behavior. @@ -1718,6 +1942,35 @@ extension FloatingPoint { return y } + /// Returns the value with greater magnitude. + /// + /// This method returns the value with greater magnitude of the two given + /// values, preserving order and eliminating NaN when possible. For two + /// values `x` and `y`, the result of `maximumMagnitude(x, y)` is `x` if + /// `x.magnitude > y.magnitude`, `y` if `x.magnitude <= y.magnitude`, or + /// whichever of `x` or `y` is a number if the other is a quiet NaN. If both + /// `x` and `y` are NaN, or either `x` or `y` is a signaling NaN, the result + /// is NaN. + /// + /// Double.maximumMagnitude(10.0, -25.0) + /// // -25.0 + /// Double.maximumMagnitude(10.0, .nan) + /// // 10.0 + /// Double.maximumMagnitude(.nan, -25.0) + /// // -25.0 + /// Double.maximumMagnitude(.nan, .nan) + /// // nan + /// + /// The `maximumMagnitude` method implements the `maxNumMag` operation + /// defined by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - x: A floating-point value. + /// - y: Another floating-point value. + /// - Returns: Whichever of `x` or `y` has greater magnitude, or whichever is + /// a number if the other is NaN. public static func maximumMagnitude(_ x: Self, _ y: Self) -> Self { if x.isSignalingNaN || y.isSignalingNaN { // Produce a quiet NaN matching platform arithmetic behavior. @@ -1727,6 +1980,12 @@ extension FloatingPoint { return y } + /// The classification of this value. + /// + /// A value's `floatingPointClass` property describes its "class" as + /// described by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public var floatingPointClass: FloatingPointClassification { if isSignalingNaN { return .signalingNaN } if isNaN { return .quietNaN } @@ -1748,12 +2007,53 @@ extension BinaryFloatingPoint { /// let magnitude = x.significand * F.radix ** x.exponent public static var radix: Int { return 2 } + /// Creates a new floating-point value using the sign of one value and the + /// magnitude of another. + /// + /// The following example uses this initializer to create a new `Double` + /// instance with the sign of `a` and the magnitude of `b`: + /// + /// let a = -21.5 + /// let b = 305.15 + /// let c = Double(signOf: a, magnitudeOf: b) + /// print(c) + /// // Prints "-305.15" + /// + /// This initializer implements the IEEE 754 `copysign` operation. + /// + /// - Parameters: + /// - signOf: A value from which to use the sign. The result of the + /// initializer has the same sign as `signOf`. + /// - magnitudeOf: A value from which to use the magnitude. The result of + /// the initializer has the same magnitude as `magnitudeOf`. public init(signOf: Self, magnitudeOf: Self) { self.init(sign: signOf.sign, exponentBitPattern: magnitudeOf.exponentBitPattern, significandBitPattern: magnitudeOf.significandBitPattern) } + /// Returns a Boolean value indicating whether this instance should precede + /// or tie positions with the given value in an ascending sort. + /// + /// This relation is a refinement of the less-than-or-equal-to operator + /// (`<=`) that provides a total order on all values of the type, including + /// signed zeros and NaNs. + /// + /// The following example uses `isTotallyOrdered(belowOrEqualTo:)` to sort an + /// array of floating-point values, including some that are NaN: + /// + /// var numbers = [2.5, 21.25, 3.0, .nan, -9.5] + /// numbers.sort { !$1.isTotallyOrdered(belowOrEqualTo: $0) } + /// // numbers == [-9.5, 2.5, 3.0, 21.25, NaN] + /// + /// The `isTotallyOrdered(belowOrEqualTo:)` method implements the total order + /// relation as defined by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameter other: A floating-point value to compare to this value. + /// - Returns: `true` if this value is ordered below or the same as `other` + /// in a total ordering of the floating-point type; otherwise, `false`. public func isTotallyOrdered(belowOrEqualTo other: Self) -> Bool { // Quick return when possible. if self < other { return true } diff --git a/stdlib/public/core/FloatingPointTypes.swift.gyb b/stdlib/public/core/FloatingPointTypes.swift.gyb index 3a17f479d2987..6a2ad9acd5083 100644 --- a/stdlib/public/core/FloatingPointTypes.swift.gyb +++ b/stdlib/public/core/FloatingPointTypes.swift.gyb @@ -107,12 +107,43 @@ extension ${Self}: BinaryFloatingPoint { public typealias Exponent = Int public typealias RawSignificand = ${RawSignificand} + /// The number of bits used to represent the type's exponent. + /// + /// A binary floating-point type's `exponentBitCount` imposes a limit on the + /// range of the exponent for normal, finite values. The *exponent bias* of + /// a type `F` can be calculated as the following, where `**` is + /// exponentiation: + /// + /// let bias = 2 ** (F.exponentBitCount - 1) - 1 + /// + /// The least normal exponent for values of the type `F` is `1 - bias`, and + /// the largest finite exponent is `bias`. An all-zeros exponent is reserved + /// for subnormals and zeros, and an all-ones exponent is reserved for + /// infinity and NaN. + /// + /// For example, the `Float` type has an `exponentBitCount` of 8, which gives + /// an exponent bias of `127` by the calculation above. + /// + /// let bias = 2 ** (Float.exponentBitCount - 1) - 1 + /// // bias == 127 + /// print(Float.greatestFiniteMagnitude.exponent) + /// // Prints "127" + /// print(Float.leastNormalMagnitude.exponent) + /// // Prints "-126" public static var exponentBitCount: Int { return ${ExponentBitCount} } -%if bits == 80: /// The available number of fractional significand bits. + /// + /// For fixed-width floating-point types, this is the actual number of + /// fractional significand bits. + /// + /// For extensible floating-point types, `significandBitCount` should be the + /// maximum allowed significand width (without counting any leading integral + /// bit of the significand). If there is no upper limit, then + /// `significandBitCount` should be `Int.max`. +%if bits == 80: /// /// `Float80.significandBitCount` is 63, even though 64 bits are used to /// store the significand in the memory representation of a `Float80` @@ -176,6 +207,19 @@ extension ${Self}: BinaryFloatingPoint { self.init(_bits: Builtin.bitcast_Int${bits}_FPIEEE${bits}(bitPattern._value)) } + /// The sign of the floating-point value. + /// + /// The `sign` property is `.minus` if the value's signbit is set, and + /// `.plus` otherwise. For example: + /// + /// let x = -33.375 + /// // x.sign == .minus + /// + /// Do not use this property to check whether a floating point value is + /// negative. For a value `x`, the comparison `x.sign == .minus` is not + /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if + /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` + /// could be either `.plus` or `.minus`. public var sign: FloatingPointSign { let shift = ${Self}.significandBitCount + ${Self}.exponentBitCount return FloatingPointSign(rawValue: Int(bitPattern &>> ${RawSignificand}(shift)))! @@ -184,15 +228,37 @@ extension ${Self}: BinaryFloatingPoint { @available(*, unavailable, renamed: "sign") public var isSignMinus: Bool { Builtin.unreachable() } + /// The raw encoding of the value's exponent field. + /// + /// This value is unadjusted by the type's exponent bias. public var exponentBitPattern: UInt { return UInt(bitPattern &>> UInt${bits}(${Self}.significandBitCount)) & ${Self}._infinityExponent } + /// The raw encoding of the value's significand field. + /// + /// The `significandBitPattern` property does not include the leading + /// integral bit of the significand, even for types like `Float80` that + /// store it explicitly. public var significandBitPattern: ${RawSignificand} { return ${RawSignificand}(bitPattern) & ${Self}._significandMask } + /// Creates a new instance from the specified sign and bit patterns. + /// + /// The values passed as `exponentBitPattern` and `significandBitPattern` are + /// interpreted in the binary interchange format defined by the [IEEE 754 + /// specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - sign: The sign of the new value. + /// - exponentBitPattern: The bit pattern to use for the exponent field of + /// the new value. + /// - significandBitPattern: The bit pattern to use for the significand + /// field of the new value. public init(sign: FloatingPointSign, exponentBitPattern: UInt, significandBitPattern: ${RawSignificand}) { @@ -208,6 +274,16 @@ extension ${Self}: BinaryFloatingPoint { significand) } + /// A Boolean value indicating whether the instance's representation is in + /// the canonical form. + /// + /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, + /// encoding of a floating-point value's representation. Every `Float` or + /// `Double` value is canonical, but noncanonical values of the `Float80` + /// type exist, and noncanonical values may exist for other types that + /// conform to the `FloatingPoint` protocol. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public var isCanonical: Bool { return true } @@ -231,6 +307,19 @@ extension ${Self}: BinaryFloatingPoint { return unsafeBitCast(self, to: _Float80Representation.self) } + /// The sign of the floating-point value. + /// + /// The `sign` property is `.minus` if the value's signbit is set, and + /// `.plus` otherwise. For example: + /// + /// let x = -33.375 + /// // x.sign == .minus + /// + /// Do not use this property to check whether a floating point value is + /// negative. For a value `x`, the comparison `x.sign == .minus` is not + /// necessarily the same as `x < 0`. In particular, `x.sign == .minus` if + /// `x` is -0, and while `x < 0` is always `false` if `x` is NaN, `x.sign` + /// could be either `.plus` or `.minus`. public var sign: FloatingPointSign { return _representation.sign } @@ -239,6 +328,9 @@ extension ${Self}: BinaryFloatingPoint { @inline(__always) get { return 1 &<< 63 } } + /// The raw encoding of the value's exponent field. + /// + /// This value is unadjusted by the type's exponent bias. public var exponentBitPattern: UInt { let provisional = _representation.exponentBitPattern if provisional == 0 { @@ -262,6 +354,11 @@ extension ${Self}: BinaryFloatingPoint { return provisional } + /// The raw encoding of the value's significand field. + /// + /// The `significandBitPattern` property does not include the leading + /// integral bit of the significand, even for types like `Float80` that + /// store it explicitly. public var significandBitPattern: UInt64 { if _representation.exponentBitPattern > 0 && _representation.explicitSignificand < Float80._explicitBitMask { @@ -275,6 +372,20 @@ extension ${Self}: BinaryFloatingPoint { return _representation.explicitSignificand & Float80._significandMask } + /// Creates a new instance from the specified sign and bit patterns. + /// + /// The values passed as `exponentBitPattern` and `significandBitPattern` are + /// interpreted in the binary interchange format defined by the [IEEE 754 + /// specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - sign: The sign of the new value. + /// - exponentBitPattern: The bit pattern to use for the exponent field of + /// the new value. + /// - significandBitPattern: The bit pattern to use for the significand + /// field of the new value. public init(sign: FloatingPointSign, exponentBitPattern: UInt, significandBitPattern: UInt64) { @@ -287,6 +398,16 @@ extension ${Self}: BinaryFloatingPoint { self = unsafeBitCast(rep, to: Float80.self) } + /// A Boolean value indicating whether the instance's representation is in + /// the canonical form. + /// + /// The [IEEE 754 specification][spec] defines a *canonical*, or preferred, + /// encoding of a floating-point value's representation. Every `Float` or + /// `Double` value is canonical, but noncanonical values of the `Float80` + /// type exist, and noncanonical values may exist for other types that + /// conform to the `FloatingPoint` protocol. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public var isCanonical: Bool { if exponentBitPattern == 0 { // If exponent field is zero, canonical numbers have the explicit @@ -299,16 +420,60 @@ extension ${Self}: BinaryFloatingPoint { } %end + /// Positive infinity. + /// + /// Infinity compares greater than all finite numbers and equal to other + /// infinite values. + /// + /// let x = Double.greatestFiniteMagnitude + /// let y = x * 2 + /// // y == Double.infinity + /// // y > x public static var infinity: ${Self} { return ${Self}(sign: .plus, exponentBitPattern: _infinityExponent, significandBitPattern: 0) } + /// A quiet NaN ("not a number"). + /// + /// A NaN compares not equal, not greater than, and not less than every + /// value, including itself. Passing a NaN to an operation generally results + /// in NaN. + /// + /// let x = 1.21 + /// // x > Double.nan == false + /// // x < Double.nan == false + /// // x == Double.nan == false + /// + /// Because a NaN always compares not equal to itself, to test whether a + /// floating-point value is NaN, use its `isNaN` property instead of the + /// equal-to operator (`==`). In the following example, `y` is NaN. + /// + /// let y = x + Double.nan + /// print(y == Double.nan) + /// // Prints "false" + /// print(y.isNaN) + /// // Prints "true" public static var nan: ${Self} { return ${Self}(nan: 0, signaling: false) } + /// A signaling NaN ("not a number"). + /// + /// The default IEEE 754 behavior of operations involving a signaling NaN is + /// to raise the Invalid flag in the floating-point environment and return a + /// quiet NaN. + /// + /// Operations on types conforming to the `FloatingPoint` protocol should + /// support this behavior, but they might also support other options. For + /// example, it would be reasonable to implement alternative operations in + /// which operating on a signaling NaN triggers a runtime error or results + /// in a diagnostic for debugging purposes. Types that implement alternative + /// behaviors for a signaling NaN must document the departure. + /// + /// Other than these signaling operations, a signaling NaN behaves in the + /// same manner as a quiet NaN. public static var signalingNaN: ${Self} { return ${Self}(nan: 0, signaling: true) } @@ -316,12 +481,29 @@ extension ${Self}: BinaryFloatingPoint { @available(*, unavailable, renamed: "nan") public static var quietNaN: ${Self} { Builtin.unreachable()} + /// The greatest finite number representable by this type. + /// + /// This value compares greater than or equal to all finite numbers, but less + /// than `infinity`. + /// + /// This value corresponds to type-specific C macros such as `FLT_MAX` and + /// `DBL_MAX`. The naming of those macros is slightly misleading, because + /// `infinity` is greater than this value. public static var greatestFiniteMagnitude: ${Self} { return ${Self}(sign: .plus, exponentBitPattern: _infinityExponent - 1, significandBitPattern: _significandMask) } + /// The mathematical constant pi. + /// + /// This value should be rounded toward zero to keep user computations with + /// angles from inadvertently ending up in the wrong quadrant. A type that + /// conforms to the `FloatingPoint` protocol provides the value for `pi` at + /// its best possible precision. + /// + /// print(Double.pi) + /// // Prints "3.14159265358979" public static var pi: ${Self} { %if bits == 32: // Note: this is not the correctly rounded (to nearest) value of pi, @@ -337,6 +519,25 @@ extension ${Self}: BinaryFloatingPoint { %end } + /// The unit in the last place of this value. + /// + /// This is the unit of the least significant digit in this value's + /// significand. For most numbers `x`, this is the difference between `x` + /// and the next greater (in magnitude) representable number. There are some + /// edge cases to be aware of: + /// + /// - If `x` is not a finite number, then `x.ulp` is NaN. + /// - If `x` is very small in magnitude, then `x.ulp` may be a subnormal + /// number. If a type does not support subnormals, `x.ulp` may be rounded + /// to zero. + /// - `greatestFiniteMagnitude.ulp` is a finite number, even though the next + /// greater representable value is `infinity`. + /// + /// This quantity, or a related quantity, is sometimes called *epsilon* or + /// *machine epsilon.* Avoid that name because it has different meanings in + /// different languages, which can lead to confusion, and because it + /// suggests that it is a good tolerance to use for comparisons, which it + /// almost never is. public var ulp: ${Self} { if !isFinite { return ${Self}.nan } if exponentBitPattern > UInt(${Self}.significandBitCount) { @@ -360,12 +561,27 @@ extension ${Self}: BinaryFloatingPoint { significandBitPattern: 1) } + /// The least positive normal number. + /// + /// This value compares less than or equal to all positive normal numbers. + /// There may be smaller positive numbers, but they are *subnormal*, meaning + /// that they are represented with less precision than normal numbers. + /// + /// This value corresponds to type-specific C macros such as `FLT_MIN` and + /// `DBL_MIN`. The naming of those macros is slightly misleading, because + /// subnormals, zeros, and negative numbers are smaller than this value. public static var leastNormalMagnitude: ${Self} { return ${Self}(sign: .plus, exponentBitPattern: 1, significandBitPattern: 0) } + /// The least positive number. + /// + /// This value compares less than or equal to all positive numbers, but + /// greater than zero. If the type supports subnormal values, + /// `leastNonzeroMagnitude` is smaller than `leastNormalMagnitude`; + /// otherwise they are equal. public static var leastNonzeroMagnitude: ${Self} { #if arch(arm) return leastNormalMagnitude @@ -376,6 +592,32 @@ extension ${Self}: BinaryFloatingPoint { #endif } + /// The exponent of the floating-point value. + /// + /// The *exponent* of a floating-point value is the integer part of the + /// logarithm of the value's magnitude. For a value `x` of a floating-point + /// type `F`, the magnitude can be calculated as the following, where `**` + /// is exponentiation: + /// + /// let magnitude = x.significand * F.radix ** x.exponent + /// + /// In the next example, `y` has a value of `21.5`, which is encoded as + /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. + /// + /// let y: Double = 21.5 + /// // y.significand == 1.34375 + /// // y.exponent == 4 + /// // Double.radix == 2 + /// + /// The `exponent` property has the following edge cases: + /// + /// - If `x` is zero, then `x.exponent` is `Int.min`. + /// - If `x` is +/-infinity or NaN, then `x.exponent` is `Int.max` + /// + /// This property implements the `logB` operation defined by the [IEEE 754 + /// specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public var exponent: Int { if !isFinite { return .max } if isZero { return .min } @@ -385,6 +627,34 @@ extension ${Self}: BinaryFloatingPoint { return provisional + 1 - Int(shift) } + /// The significand of the floating-point value. + /// + /// The magnitude of a floating-point value `x` of type `F` can be calculated + /// by using the following formula, where `**` is exponentiation: + /// + /// let magnitude = x.significand * F.radix ** x.exponent + /// + /// In the next example, `y` has a value of `21.5`, which is encoded as + /// `1.34375 * 2 ** 4`. The significand of `y` is therefore 1.34375. + /// + /// let y: Double = 21.5 + /// // y.significand == 1.34375 + /// // y.exponent == 4 + /// // Double.radix == 2 + /// + /// If a type's radix is 2, then for finite nonzero numbers, the significand + /// is in the range `1.0 ..< 2.0`. For other values of `x`, `x.significand` + /// is defined as follows: + /// + /// - If `x` is zero, then `x.significand` is 0.0. + /// - If `x` is infinity, then `x.significand` is 1.0. + /// - If `x` is NaN, then `x.significand` is NaN. + /// - Note: The significand is frequently also called the *mantissa*, but + /// significand is the preferred terminology in the [IEEE 754 + /// specification][spec], to allay confusion with the use of mantissa for + /// the fractional part of a logarithm. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 public var significand: ${Self} { if isNaN { return self } if isNormal { @@ -404,6 +674,49 @@ extension ${Self}: BinaryFloatingPoint { significandBitPattern: 0) } + /// Creates a new value from the given sign, exponent, and significand. + /// + /// The following example uses this initializer to create a new `Double` + /// instance. `Double` is a binary floating-point type that has a radix of + /// `2`. + /// + /// let x = Double(sign: .plus, exponent: -2, significand: 1.5) + /// // x == 0.375 + /// + /// This initializer is equivalent to the following calculation, where `**` + /// is exponentiation, computed as if by a single, correctly rounded, + /// floating-point operation: + /// + /// let sign: FloatingPointSign = .plus + /// let exponent = -2 + /// let significand = 1.5 + /// let y = (sign == .minus ? -1 : 1) * significand * Double.radix ** exponent + /// // y == 0.375 + /// + /// As with any basic operation, if this value is outside the representable + /// range of the type, overflow or underflow occurs, and zero, a subnormal + /// value, or infinity may result. In addition, there are two other edge + /// cases: + /// + /// - If the value you pass to `significand` is zero or infinite, the result + /// is zero or infinite, regardless of the value of `exponent`. + /// - If the value you pass to `significand` is NaN, the result is NaN. + /// + /// For any floating-point value `x` of type `F`, the result of the following + /// is equal to `x`, with the distinction that the result is canonicalized + /// if `x` is in a noncanonical encoding: + /// + /// let x0 = F(sign: x.sign, exponent: x.exponent, significand: x.significand) + /// + /// This initializer implements the `scaleB` operation defined by the [IEEE + /// 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameters: + /// - sign: The sign to use for the new value. + /// - exponent: The new value's exponent. + /// - significand: The new value's significand. public init(sign: FloatingPointSign, exponent: Int, significand: ${Self}) { var result = significand if sign == .minus { result = -result } @@ -464,6 +777,16 @@ extension ${Self}: BinaryFloatingPoint { significandBitPattern: significand) } + /// The least representable value that compares greater than this value. + /// + /// For any finite value `x`, `x.nextUp` is greater than `x`. For `nan` or + /// `infinity`, `x.nextUp` is `x` itself. The following special cases also + /// apply: + /// + /// - If `x` is `-infinity`, then `x.nextUp` is `-greatestFiniteMagnitude`. + /// - If `x` is `-leastNonzeroMagnitude`, then `x.nextUp` is `-0.0`. + /// - If `x` is zero, then `x.nextUp` is `leastNonzeroMagnitude`. + /// - If `x` is `greatestFiniteMagnitude`, then `x.nextUp` is `infinity`. public var nextUp: ${Self} { if isNaN { return self } if sign == .minus { @@ -505,6 +828,40 @@ extension ${Self}: BinaryFloatingPoint { significandBitPattern: significandBitPattern + 1) } + /// Rounds the value to an integral value using the specified rounding rule. + /// + /// The following example rounds a value using four different rounding rules: + /// + /// // Equivalent to the C 'round' function: + /// var w = 6.5 + /// w.round(.toNearestOrAwayFromZero) + /// // w == 7.0 + /// + /// // Equivalent to the C 'trunc' function: + /// var x = 6.5 + /// x.round(.towardZero) + /// // x == 6.0 + /// + /// // Equivalent to the C 'ceil' function: + /// var y = 6.5 + /// y.round(.up) + /// // y == 7.0 + /// + /// // Equivalent to the C 'floor' function: + /// var z = 6.5 + /// z.round(.down) + /// // z == 6.0 + /// + /// For more information about the available rounding rules, see the + /// `FloatingPointRoundingRule` enumeration. To round a value using the + /// default "schoolbook rounding", you can use the shorter `round()` method + /// instead. + /// + /// var w1 = 6.5 + /// w1.round() + /// // w1 == 7.0 + /// + /// - Parameter rule: The rounding rule to use. @_transparent public mutating func round(_ rule: FloatingPointRoundingRule) { switch rule { @@ -528,6 +885,14 @@ extension ${Self}: BinaryFloatingPoint { } } + /// Replaces this value with its additive inverse. + /// + /// The result is always exact. This example uses the `negate()` method to + /// negate the value of the variable `x`: + /// + /// var x = 21.5 + /// x.negate() + /// // x == -21.5 @_transparent public mutating func negate() { _value = Builtin.fneg_FPIEEE${bits}(self._value) @@ -563,11 +928,42 @@ extension ${Self}: BinaryFloatingPoint { %end } + /// Replaces this value with the remainder of itself divided by the given + /// value using truncating division. + /// + /// Performing truncating division with floating-point values results in a + /// truncated integer quotient and a remainder. For values `x` and `y` and + /// their truncated integer quotient `q`, the remainder `r` satisfies + /// `x == y * q + r`. + /// + /// The following example calculates the truncating remainder of dividing + /// 8.625 by 0.75: + /// + /// var x = 8.625 + /// print(x / 0.75) + /// // Prints "11.5" + /// + /// let q = (x / 0.75).rounded(.towardZero) + /// // q == 11.0 + /// x.formTruncatingRemainder(dividingBy: 0.75) + /// // x == 0.375 + /// + /// let x1 = 0.75 * q + x + /// // x1 == 8.625 + /// + /// If this value and `other` are both finite numbers, the truncating + /// remainder has the same sign as this value and is strictly smaller in + /// magnitude than `other`. The `formTruncatingRemainder(dividingBy:)` + /// method is always exact. + /// + /// - Parameter other: The value to use when dividing this value. @_transparent public mutating func formTruncatingRemainder(dividingBy other: ${Self}) { _value = Builtin.frem_FPIEEE${bits}(self._value, other._value) } + /// Replaces this value with its square root, rounded to a representable + /// value. @_transparent public mutating func formSquareRoot( ) { %if bits == 80: @@ -577,61 +973,222 @@ extension ${Self}: BinaryFloatingPoint { %end } + /// Adds the product of the two given values to this value in place, computed + /// without intermediate rounding. + /// + /// - Parameters: + /// - lhs: One of the values to multiply before adding to this value. + /// - rhs: The other value to multiply. @_transparent public mutating func addProduct(_ lhs: ${Self}, _ rhs: ${Self}) { _value = Builtin.int_fma_FPIEEE${bits}(lhs._value, rhs._value, _value) } + /// Returns a Boolean value indicating whether this instance is equal to the + /// given value. + /// + /// This method serves as the basis for the equal-to operator (`==`) for + /// floating-point values. When comparing two values with this method, `-0` + /// is equal to `+0`. NaN is not equal to any value, including itself. For + /// example: + /// + /// let x = 15.0 + /// x.isEqual(to: 15.0) + /// // true + /// x.isEqual(to: .nan) + /// // false + /// Double.nan.isEqual(to: .nan) + /// // false + /// + /// The `isEqual(to:)` method implements the equality predicate defined by + /// the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameter other: The value to compare with this value. + /// - Returns: `true` if `other` has the same value as this instance; + /// otherwise, `false`. @_transparent public func isEqual(to other: ${Self}) -> Bool { return Bool(Builtin.fcmp_oeq_FPIEEE${bits}(self._value, other._value)) } + /// Returns a Boolean value indicating whether this instance is less than the + /// given value. + /// + /// This method serves as the basis for the less-than operator (`<`) for + /// floating-point values. Some special cases apply: + /// + /// - Because NaN compares not less than nor greater than any value, this + /// method returns `false` when called on NaN or when NaN is passed as + /// `other`. + /// - `-infinity` compares less than all values except for itself and NaN. + /// - Every value except for NaN and `+infinity` compares less than + /// `+infinity`. + /// + /// let x = 15.0 + /// x.isLess(than: 20.0) + /// // true + /// x.isLess(than: .nan) + /// // false + /// Double.nan.isLess(than: x) + /// // false + /// + /// The `isLess(than:)` method implements the less-than predicate defined by + /// the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameter other: The value to compare with this value. + /// - Returns: `true` if `other` is less than this value; otherwise, `false`. @_transparent public func isLess(than other: ${Self}) -> Bool { return Bool(Builtin.fcmp_olt_FPIEEE${bits}(self._value, other._value)) } + /// Returns a Boolean value indicating whether this instance is less than or + /// equal to the given value. + /// + /// This method serves as the basis for the less-than-or-equal-to operator + /// (`<=`) for floating-point values. Some special cases apply: + /// + /// - Because NaN is incomparable with any value, this method returns `false` + /// when called on NaN or when NaN is passed as `other`. + /// - `-infinity` compares less than or equal to all values except NaN. + /// - Every value except NaN compares less than or equal to `+infinity`. + /// + /// let x = 15.0 + /// x.isLessThanOrEqualTo(20.0) + /// // true + /// x.isLessThanOrEqualTo(.nan) + /// // false + /// Double.nan.isLessThanOrEqualTo(x) + /// // false + /// + /// The `isLessThanOrEqualTo(_:)` method implements the less-than-or-equal + /// predicate defined by the [IEEE 754 specification][spec]. + /// + /// [spec]: http://ieeexplore.ieee.org/servlet/opac?punumber=4610933 + /// + /// - Parameter other: The value to compare with this value. + /// - Returns: `true` if `other` is less than this value; otherwise, `false`. @_transparent public func isLessThanOrEqualTo(_ other: ${Self}) -> Bool { return Bool(Builtin.fcmp_ole_FPIEEE${bits}(self._value, other._value)) } + /// A Boolean value indicating whether this instance is normal. + /// + /// A *normal* value is a finite number that uses the full precision + /// available to values of a type. Zero is neither a normal nor a subnormal + /// number. @_transparent public var isNormal: Bool { return exponentBitPattern > 0 && isFinite } + /// A Boolean value indicating whether this instance is finite. + /// + /// All values other than NaN and infinity are considered finite, whether + /// normal or subnormal. @_transparent public var isFinite: Bool { return exponentBitPattern < ${Self}._infinityExponent } + /// A Boolean value indicating whether the instance is equal to zero. + /// + /// The `isZero` property of a value `x` is `true` when `x` represents either + /// `-0.0` or `+0.0`. `x.isZero` is equivalent to the following comparison: + /// `x == 0.0`. + /// + /// let x = -0.0 + /// x.isZero // true + /// x == 0.0 // true @_transparent public var isZero: Bool { return exponentBitPattern == 0 && significandBitPattern == 0 } + /// A Boolean value indicating whether the instance is subnormal. + /// + /// A *subnormal* value is a nonzero number that has a lesser magnitude than + /// the smallest normal number. Subnormal values do not use the full + /// precision available to values of a type. + /// + /// Zero is neither a normal nor a subnormal number. Subnormal numbers are + /// often called *denormal* or *denormalized*---these are different names + /// for the same concept. @_transparent public var isSubnormal: Bool { return exponentBitPattern == 0 && significandBitPattern != 0 } + /// A Boolean value indicating whether the instance is infinite. + /// + /// Note that `isFinite` and `isInfinite` do not form a dichotomy, because + /// they are not total: If `x` is `NaN`, then both properties are `false`. @_transparent public var isInfinite: Bool { return !isFinite && significandBitPattern == 0 } + /// A Boolean value indicating whether the instance is NaN ("not a number"). + /// + /// Because NaN is not equal to any value, including NaN, use this property + /// instead of the equal-to operator (`==`) or not-equal-to operator (`!=`) + /// to test whether a value is or is not NaN. For example: + /// + /// let x = 0.0 + /// let y = x * .infinity + /// // y is a NaN + /// + /// // Comparing with the equal-to operator never returns 'true' + /// print(x == Double.nan) + /// // Prints "false" + /// print(y == Double.nan) + /// // Prints "false" + /// + /// // Test with the 'isNaN' property instead + /// print(x.isNaN) + /// // Prints "false" + /// print(y.isNaN) + /// // Prints "true" + /// + /// This property is `true` for both quiet and signaling NaNs. @_transparent public var isNaN: Bool { return !isFinite && significandBitPattern != 0 } + /// A Boolean value indicating whether the instance is a signaling NaN. + /// + /// Signaling NaNs typically raise the Invalid flag when used in general + /// computing operations. @_transparent public var isSignalingNaN: Bool { return isNaN && (significandBitPattern & ${Self}._quietNaNMask) == 0 } + /// The floating-point value with the same sign and exponent as this value, + /// but with a significand of 1.0. + /// + /// A *binade* is a set of binary floating-point values that all have the + /// same sign and exponent. The `binade` property is a member of the same + /// binade as this value, but with a unit significand. + /// + /// In this example, `x` has a value of `21.5`, which is stored as + /// `1.34375 * 2**4`, where `**` is exponentiation. Therefore, `x.binade` is + /// equal to `1.0 * 2**4`, or `16.0`. + /// + /// let x = 21.5 + /// // x.significand == 1.34375 + /// // x.exponent == 4 + /// + /// let y = x.binade + /// // y == 16.0 + /// // y.significand == 1.0 + /// // y.exponent == 4 public var binade: ${Self} { if !isFinite { return .nan } if exponentBitPattern != 0 { @@ -645,6 +1202,20 @@ extension ${Self}: BinaryFloatingPoint { significandBitPattern: 1 &<< RawSignificand(index)) } + /// The number of bits required to represent the value's significand. + /// + /// If this value is a finite nonzero number, `significandWidth` is the + /// number of fractional bits required to represent the value of + /// `significand`; otherwise, `significandWidth` is -1. The value of + /// `significandWidth` is always -1 or between zero and + /// `significandBitCount`. For example: + /// + /// - For any representable power of two, `significandWidth` is zero, because + /// `significand` is `1.0`. + /// - If `x` is 10, `x.significand` is `1.01` in binary, so + /// `x.significandWidth` is 2. + /// - If `x` is Float.pi, `x.significand` is `1.10010010000111111011011` in + /// binary, and `x.significandWidth` is 23. public var significandWidth: Int { let trailingZeroBits = significandBitPattern.trailingZeroBitCount if isNormal { @@ -794,6 +1365,9 @@ extension ${Self} { return ${Self}(_bits: Builtin.int_fabs_FPIEEE${bits}(_value)) } + /// Creates the closest representable value to the given integer. + /// + /// - Parameter value: The integer to represent as a floating-point value. // FIXME(integers): implement properly public init?(exactly source: T) { fatalError() @@ -819,11 +1393,20 @@ extension ${Self} { % ThatBuiltinName = self_ty.builtin_name % srcBits = self_ty.bits % sign = 's' if self_ty.is_signed else 'u' + /// Creates the closest representable value to the given integer. + /// + /// - Parameter value: The integer to represent as a floating-point value. @_transparent public init(_ v: ${That}) { _value = Builtin.${sign}itofp_${ThatBuiltinName}_FPIEEE${bits}(v._value) } + /// 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`. + /// + /// - Parameter value: The integer to represent as a floating-point value. % if srcBits < SignificandBitCount: @available(*, message: "Converting ${That} to ${Self} will always succeed.") % end diff --git a/stdlib/public/core/HashedCollections.swift.gyb b/stdlib/public/core/HashedCollections.swift.gyb index 564d4f6cc5ce3..46c8432e124aa 100644 --- a/stdlib/public/core/HashedCollections.swift.gyb +++ b/stdlib/public/core/HashedCollections.swift.gyb @@ -1120,9 +1120,8 @@ public struct Set : /// In the following example, the elements of the `employees` set that are /// also members of `neighbors` are removed from `employees`, while the /// elements of `neighbors` that are not members of `employees` are added to - /// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and - /// `"Diana"` are removed from `employees` while the name `"Forlani"` is - /// added. + /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are + /// removed from `employees` while the name `"Forlani"` is added. /// /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] /// let neighbors = ["Bethany", "Eric", "Forlani"] diff --git a/stdlib/public/core/ImplicitlyUnwrappedOptional.swift b/stdlib/public/core/ImplicitlyUnwrappedOptional.swift index b3aaef56e6fbc..4be6e5f057134 100644 --- a/stdlib/public/core/ImplicitlyUnwrappedOptional.swift +++ b/stdlib/public/core/ImplicitlyUnwrappedOptional.swift @@ -12,7 +12,15 @@ /// An optional type that allows implicit member access. /// -/// *Deprecated.* +/// The `ImplicitlyUnwrappedOptional` type is deprecated. To create an optional +/// value that is implicitly unwrapped, place an exclamation mark (`!`) after +/// the type that you want to denote as optional. +/// +/// // An implicitly unwrapped optional integer +/// let guaranteedNumber: Int! = 6 +/// +/// // An optional integer +/// let possibleNumber: Int? = 5 @_fixed_layout public enum ImplicitlyUnwrappedOptional : ExpressibleByNilLiteral { // The compiler has special knowledge of the existence of diff --git a/stdlib/public/core/Integers.swift.gyb b/stdlib/public/core/Integers.swift.gyb index 6110a50af6e0d..a132b27d13d09 100644 --- a/stdlib/public/core/Integers.swift.gyb +++ b/stdlib/public/core/Integers.swift.gyb @@ -1335,6 +1335,9 @@ public protocol BinaryInteger : /// 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) @@ -1347,7 +1350,8 @@ public protocol BinaryInteger : /// // 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. + /// `source` must be representable in this type after rounding toward + /// zero. init(_ source: T) /// Creates a new instance from the given integer. @@ -2502,7 +2506,7 @@ extension SignedInteger where Self : FixedWidthInteger { % z = 's' if signed else 'z' % Article = 'An' if bits == 8 else 'A' -% if bits == word_bits: +% if self_type.is_word: /// ${'A ' if signed else 'An un'}signed integer value type. /// /// On 32-bit platforms, `${Self}` is the same size as `${Self}32`, and diff --git a/stdlib/public/core/KeyPath.swift b/stdlib/public/core/KeyPath.swift index 5caf8ee224112..dd96e7252ac2f 100644 --- a/stdlib/public/core/KeyPath.swift +++ b/stdlib/public/core/KeyPath.swift @@ -1347,21 +1347,101 @@ func _projectKeyPathReferenceWritable( // constrained by being overrides, and so that we can use exact-type constraints // on `Self` to prevent dynamically-typed methods from being inherited by // statically-typed key paths. + +/// This protocol is an implementation detail of key path expressions; do not +/// use it directly. @_show_in_interface public protocol _AppendKeyPath {} extension _AppendKeyPath where Self == AnyKeyPath { + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Appending the key path passed as `path` is successful only if the + /// root type for `path` matches this key path's value type. This example + /// creates key paths from `Array` to `String` and from `String` to + /// `Int`, and then tries appending each to the other: + /// + /// let arrayDescription: AnyKeyPath = \Array.description + /// let stringLength: AnyKeyPath = \String.count + /// + /// // Creates a key path from `Array` to `Int` + /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) + /// + /// let invalidKeyPath = stringLength.appending(path: arrayDescription) + /// // invalidKeyPath == nil + /// + /// The second call to `appending(path:)` returns `nil` + /// because the root type of `arrayDescription`, `Array`, does not + /// match the value type of `stringLength`, `Int`. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path and the value type + /// of `path`, if `path` can be appended. If `path` can't be appended, + /// returns `nil`. public func appending(path: AnyKeyPath) -> AnyKeyPath? { return _tryToAppendKeyPaths(root: self, leaf: path) } } extension _AppendKeyPath /* where Self == PartialKeyPath */ { + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Appending the key path passed as `path` is successful only if the + /// root type for `path` matches this key path's value type. This example + /// creates key paths from `Array` to `String` and from `String` to + /// `Int`, and then tries appending each to the other: + /// + /// let arrayDescription: PartialKeyPath> = \.description + /// let stringLength: PartialKeyPath = \.count + /// + /// // Creates a key path from `Array` to `Int` + /// let arrayDescriptionLength = arrayDescription.appending(path: stringLength) + /// + /// let invalidKeyPath = stringLength.appending(path: arrayDescription) + /// // invalidKeyPath == nil + /// + /// The second call to `appending(path:)` returns `nil` + /// because the root type of `arrayDescription`, `Array`, does not + /// match the value type of `stringLength`, `Int`. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path and the value type + /// of `path`, if `path` can be appended. If `path` can't be appended, + /// returns `nil`. public func appending(path: AnyKeyPath) -> PartialKeyPath? where Self == PartialKeyPath { return _tryToAppendKeyPaths(root: self, leaf: path) } + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Appending the key path passed as `path` is successful only if the + /// root type for `path` matches this key path's value type. This example + /// creates a key path from `Array` to `String`, and then tries + /// appending compatible and incompatible key paths: + /// + /// let arrayDescription: PartialKeyPath> = \.description + /// + /// // Creates a key path from `Array` to `Int` + /// let arrayDescriptionLength = arrayDescription.appending(path: \String.count) + /// + /// let invalidKeyPath = arrayDescription.appending(path: \Double.isZero) + /// // invalidKeyPath == nil + /// + /// The second call to `appending(path:)` returns `nil` because the root type + /// of the `path` parameter, `Double`, does not match the value type of + /// `arrayDescription`, `String`. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the the value type + /// of `path`, if `path` can be appended. If `path` can't be appended, + /// returns `nil`. public func appending( path: KeyPath ) -> KeyPath? @@ -1369,6 +1449,17 @@ extension _AppendKeyPath /* where Self == PartialKeyPath */ { return _tryToAppendKeyPaths(root: self, leaf: path) } + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Appending the key path passed as `path` is successful only if the + /// root type for `path` matches this key path's value type. + /// + /// - Parameter path: The reference writeable key path to append. + /// - Returns: A key path from the root of this key path to the the value type + /// of `path`, if `path` can be appended. If `path` can't be appended, + /// returns `nil`. public func appending( path: ReferenceWritableKeyPath ) -> ReferenceWritableKeyPath? @@ -1378,6 +1469,22 @@ extension _AppendKeyPath /* where Self == PartialKeyPath */ { } extension _AppendKeyPath /* where Self == KeyPath */ { + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Calling `appending(path:)` results in the same key path as if the + /// given key path had been specified using dot notation. In the following + /// example, `keyPath1` and `keyPath2` are equivalent: + /// + /// let arrayDescription = \Array.description + /// let keyPath1 = arrayDescription.appending(path: \String.count) + /// + /// let keyPath2 = \Array.description.count + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the value type of + /// `path`. public func appending( path: KeyPath ) -> KeyPath @@ -1396,6 +1503,16 @@ extension _AppendKeyPath /* where Self == KeyPath */ { } */ + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Calling `appending(path:)` results in the same key path as if the + /// given key path had been specified using dot notation. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the value type of + /// `path`. public func appending( path: ReferenceWritableKeyPath ) -> ReferenceWritableKeyPath @@ -1405,6 +1522,16 @@ extension _AppendKeyPath /* where Self == KeyPath */ { } extension _AppendKeyPath /* where Self == WritableKeyPath */ { + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Calling `appending(path:)` results in the same key path as if the + /// given key path had been specified using dot notation. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the value type of + /// `path`. public func appending( path: WritableKeyPath ) -> WritableKeyPath @@ -1412,6 +1539,16 @@ extension _AppendKeyPath /* where Self == WritableKeyPath */ { return _appendingKeyPaths(root: self, leaf: path) } + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Calling `appending(path:)` results in the same key path as if the + /// given key path had been specified using dot notation. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the value type of + /// `path`. public func appending( path: ReferenceWritableKeyPath ) -> ReferenceWritableKeyPath @@ -1421,6 +1558,16 @@ extension _AppendKeyPath /* where Self == WritableKeyPath */ { } extension _AppendKeyPath /* where Self == ReferenceWritableKeyPath */ { + /// Returns a new key path created by appending the given key path to this + /// one. + /// + /// Use this method to extend this key path to the value type of another key + /// path. Calling `appending(path:)` results in the same key path as if the + /// given key path had been specified using dot notation. + /// + /// - Parameter path: The key path to append. + /// - Returns: A key path from the root of this key path to the value type of + /// `path`. public func appending( path: WritableKeyPath ) -> ReferenceWritableKeyPath diff --git a/stdlib/public/core/Optional.swift b/stdlib/public/core/Optional.swift index d4709b47212de..f0ee79799e690 100644 --- a/stdlib/public/core/Optional.swift +++ b/stdlib/public/core/Optional.swift @@ -178,8 +178,8 @@ public enum Optional : ExpressibleByNilLiteral { /// /// let possibleNumber: Int? = Int("42") /// let nonOverflowingSquare = possibleNumber.flatMap { x -> Int? in - /// let (result, overflowed) = Int.multiplyWithOverflow(x, x) - /// return overflowed ? nil : result + /// let (result, overflowed) = x.multipliedReportingOverflow(by: x) + /// return overflowed == .overflow ? nil : result /// } /// print(nonOverflowingSquare) /// // Prints "Optional(1764)" diff --git a/stdlib/public/core/Range.swift.gyb b/stdlib/public/core/Range.swift.gyb index 39f930af2feb5..4665cc6711573 100644 --- a/stdlib/public/core/Range.swift.gyb +++ b/stdlib/public/core/Range.swift.gyb @@ -18,6 +18,39 @@ public protocol RangeExpression { /// Returns the range of indices within the given collection described by /// this range expression. /// + /// You can use the `relative(to:)` method to convert a range expression, + /// which could be missing one or both of its endpoints, into a concrete + /// range that is bounded on both sides. The following example uses this + /// method to convert a partial range up to `4` into a half-open range, + /// using an array instance to add the range's lower bound. + /// + /// let numbers = [10, 20, 30, 40, 50, 60, 70] + /// let upToFour = ..<4 + /// + /// let r1 = upToFour.relative(to: numbers) + /// // r1 == 0..<4 + /// + /// The `r1` range is bounded on the lower end by `0` because that is the + /// starting index of the `numbers` array. When the collection passed to + /// `relative(to:)` starts with a different index, that index is used as the + /// lower bound instead. The next example creates a slice of `numbers` + /// starting at index `2`, and then uses the slice with `relative(to:)` to + /// convert `upToFour` to a concrete range. + /// + /// let numbersSuffix = numbers[2...] + /// // numbersSuffix == [30, 40, 50, 60, 70] + /// + /// let r2 = upToFour.relative(to: numbersSuffix) + /// // r2 == 2..<4 + /// + /// Use this method only if you need the concrete range it produces. To + /// access a slice of a collection using a range expression, use the + /// collection's generic subscript that uses a range expression as its + /// parameter. + /// + /// let numbersPrefix = numbers[upToFour] + /// // numbersPrefix == [10, 20, 30, 40] + /// /// - Parameter collection: The collection to evaluate this range expression /// in relation to. /// - Returns: A range suitable for slicing `collection`. The returned range diff --git a/stdlib/public/core/SequenceAlgorithms.swift.gyb b/stdlib/public/core/SequenceAlgorithms.swift.gyb index 924e93d31bbfd..48f08d49e9df4 100644 --- a/stdlib/public/core/SequenceAlgorithms.swift.gyb +++ b/stdlib/public/core/SequenceAlgorithms.swift.gyb @@ -301,8 +301,8 @@ extension Sequence ${"" if preds else "where Element : Equatable"} { % if preds: /// Returns a Boolean value indicating whether this sequence and another - /// sequence contain equivalent elements, using the given predicate as the - /// equivalence test. + /// sequence contain equivalent elements in the same order, using the given + /// predicate as the equivalence test. /// /// At least one of the sequences must be finite. /// diff --git a/stdlib/public/core/SetAlgebra.swift b/stdlib/public/core/SetAlgebra.swift index 014be7fde2ae2..6e22a3b449620 100644 --- a/stdlib/public/core/SetAlgebra.swift +++ b/stdlib/public/core/SetAlgebra.swift @@ -276,15 +276,14 @@ public protocol SetAlgebra : Equatable, ExpressibleByArrayLiteral { /// In the following example, the elements of the `employees` set that are /// also members of `neighbors` are removed from `employees`, while the /// elements of `neighbors` that are not members of `employees` are added to - /// `employees`. In particular, the names `"Alicia"`, `"Chris"`, and - /// `"Diana"` are removed from `employees` while the names `"Forlani"` and - /// `"Greta"` are added. + /// `employees`. In particular, the names `"Bethany"` and `"Eric"` are + /// removed from `employees` while the name `"Forlani"` is added. /// - /// var employees: Set = ["Alicia", "Bethany", "Chris", "Diana", "Eric"] - /// let neighbors: Set = ["Bethany", "Eric", "Forlani", "Greta"] + /// var employees: Set = ["Alicia", "Bethany", "Diana", "Eric"] + /// let neighbors: Set = ["Bethany", "Eric", "Forlani"] /// employees.formSymmetricDifference(neighbors) /// print(employees) - /// // Prints "["Diana", "Chris", "Forlani", "Alicia", "Greta"]" + /// // Prints "["Diana", "Forlani", "Alicia"]" /// /// - Parameter other: A set of the same type. mutating func formSymmetricDifference(_ other: Self) diff --git a/stdlib/public/core/String.swift b/stdlib/public/core/String.swift index ef5c27b768a01..86a455b9209f6 100644 --- a/stdlib/public/core/String.swift +++ b/stdlib/public/core/String.swift @@ -13,6 +13,9 @@ import SwiftShims /// A type that can represent a string as a collection of characters. +/// +/// Do not declare new conformances to `StringProtocol`. Only the `String` and +/// `Substring` types in the standard library are valid conforming types. public protocol StringProtocol : BidirectionalCollection, TextOutputStream, TextOutputStreamable, @@ -536,10 +539,10 @@ extension String { /// // Prints "1" /// /// On the other hand, an emoji flag character is constructed from a pair of -/// Unicode scalar values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of -/// these scalar values, in turn, is too large to fit into a single UTF-16 or -/// UTF-8 code unit. As a result, each view of the string `"🇵🇷"` reports a -/// different length. +/// Unicode scalar values, like `"\u{1F1F5}"` and `"\u{1F1F7}"`. Each of these +/// scalar values, in turn, is too large to fit into a single UTF-16 or UTF-8 +/// code unit. As a result, each view of the string `"🇵🇷"` reports a different +/// length. /// /// let flag = "🇵🇷" /// print(flag.count) @@ -561,8 +564,8 @@ extension String { /// /// To find individual elements of a string, use the appropriate view for your /// task. For example, to retrieve the first word of a longer string, you can -/// search the `characters` view for a space and then create a new string from -/// a prefix of the `characters` view up to that point. +/// search the string for a space and then create a new string from a prefix +/// of the string up to that point. /// /// let name = "Marie Curie" /// let firstSpace = name.index(of: " ") ?? name.endIndex @@ -570,13 +573,45 @@ extension String { /// print(firstName) /// // Prints "Marie" /// -/// You can convert an index into one of a string's views to an index into -/// another view. +/// Strings and their views share indices, so you can access the UTF-8 view of +/// the `name` string using the same `firstSpace` index. /// -/// let firstSpaceUTF8 = firstSpace.samePosition(in: name.utf8) -/// print(Array(name.utf8[.. String.UTF8View.Index? { @@ -82,18 +93,23 @@ extension String.Index { /// /// The index must be a valid index of `String(utf16)`. /// - /// This example first finds the position of the character `"é"` and then uses - /// this method find the same position in the string's `utf16` view. + /// This example first finds the position of the character `"é"` and then + /// uses this method find the same position in the string's `utf16` view. /// /// let cafe = "Café" /// if let i = cafe.index(of: "é") { - /// let j = i.samePosition(in: cafe.utf16) + /// let j = i.samePosition(in: cafe.utf16)! /// print(cafe.utf16[j]) /// } /// // Prints "233" /// - /// - Parameter utf16: The view to use for the index conversion. - /// - Returns: The position in `utf16` that corresponds exactly to this index. + /// - Parameter utf16: The view to use for the index conversion. This index + /// must be a valid index of at least one view of the string shared by + /// `utf16`. + /// - Returns: The position in `utf16` that corresponds exactly to this + /// index. If this index does not have an exact corresponding position in + /// `utf16`, this method returns `nil`. For example, an attempt to convert + /// the position of a UTF-8 continuation byte returns `nil`. public func samePosition( in utf16: String.UTF16View ) -> String.UTF16View.Index? { diff --git a/stdlib/public/core/StringUTF16.swift b/stdlib/public/core/StringUTF16.swift index b4ae309b91e85..91ef64d804fb1 100644 --- a/stdlib/public/core/StringUTF16.swift +++ b/stdlib/public/core/StringUTF16.swift @@ -340,19 +340,27 @@ extension String.UTF16View.Index { /// Creates an index in the given UTF-16 view that corresponds exactly to the /// specified string position. /// + /// If the index passed as `sourcePosition` represents either the start of a + /// Unicode scalar value or the position of a UTF-16 trailing surrogate, + /// then the initializer succeeds. If `sourcePosition` does not have an + /// exact corresponding position in `target`, then the result is `nil`. For + /// example, an attempt to convert the position of a UTF-8 continuation byte + /// results in `nil`. + /// /// The following example finds the position of a space in a string and then /// converts that position to an index in the string's `utf16` view. /// /// let cafe = "Café 🍵" /// /// let stringIndex = cafe.index(of: "é")! - /// let utf16Index = String.UTF16View.Index(stringIndex, within: cafe.utf16) + /// let utf16Index = String.Index(stringIndex, within: cafe.utf16)! /// /// print(cafe.utf16[...utf16Index]) /// // Prints "Café" /// /// - Parameters: - /// - sourcePosition: A position in a string or one of its views + /// - sourcePosition: A position in at least one of the views of the string + /// shared by `target`. /// - target: The `UTF16View` in which to find the new position. public init?( _ sourcePosition: String.Index, within target: String.UTF16View @@ -377,6 +385,8 @@ extension String.UTF16View.Index { /// // Prints "Café" /// /// - Parameter unicodeScalars: The view to use for the index conversion. + /// This index must be a valid index of at least one view of the string + /// shared by `unicodeScalars`. /// - Returns: The position in `unicodeScalars` that corresponds exactly to /// this index. If this index does not have an exact corresponding /// position in `unicodeScalars`, this method returns `nil`. For example, diff --git a/stdlib/public/core/StringUnicodeScalarView.swift b/stdlib/public/core/StringUnicodeScalarView.swift index 3ca38ef4a23d8..f452e5682d37b 100644 --- a/stdlib/public/core/StringUnicodeScalarView.swift +++ b/stdlib/public/core/StringUnicodeScalarView.swift @@ -378,34 +378,32 @@ extension String.UnicodeScalarIndex { /// let cafe = "Café 🍵" /// /// let utf16Index = cafe.utf16.index(of: 32)! - /// let scalarIndex = String.UnicodeScalarView.Index(utf16Index, within: cafe.unicodeScalars)! + /// let scalarIndex = String.Index(utf16Index, within: cafe.unicodeScalars)! /// /// print(String(cafe.unicodeScalars[.. % if not Mutable: /// Creates a buffer over the same memory as the given buffer slice. /// - /// The new buffer will represent the same region of memory as the slice, - /// but it's indices will be rebased to zero. Given: + /// The new buffer represents the same region of memory as `slice`, but is + /// indexed starting at zero instead of sharing indices with the original + /// buffer. For example: /// - /// let slice = buffer[n..>) { self.init(start: slice.base.baseAddress! + slice.startIndex, @@ -324,15 +332,23 @@ public struct Unsafe${Mutable}BufferPointer /// Creates a buffer over the same memory as the given buffer slice. /// - /// The new buffer will represent the same region of memory as the slice, - /// but it's indices will be rebased to zero. Given: + /// The new buffer represents the same region of memory as `slice`, but is + /// indexed starting at zero instead of sharing indices with the original + /// buffer. For example: + /// + /// let buffer = returnsABuffer() + /// let n = 5 + /// let slice = buffer[n...] + /// let rebased = Unsafe${Mutable}BufferPointer(rebasing: slice) /// - /// let slice = buffer[n..(from source: S) -> (S.Iterator, Index) where S.Element == Element { diff --git a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb index d9cfdabf6bfe0..5d9f6122deb2e 100644 --- a/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb +++ b/stdlib/public/core/UnsafeRawBufferPointer.swift.gyb @@ -233,22 +233,19 @@ public struct Unsafe${Mutable}RawBufferPointer baseAddress!.storeBytes(of: value, toByteOffset: offset, as: T.self) } - /// Copies the specified number of bytes from the given raw pointer's memory - /// into this buffer's memory. + /// Copies the bytes from the given buffer to this buffer's memory. /// - /// If the `count` bytes of memory referenced by this pointer are bound to a - /// type `T`, then `T` must be a trivial type, this pointer and `source` - /// must be properly aligned for accessing `T`, and `count` must be a + /// If the `source.count` bytes of memory referenced by this buffer are bound + /// to a type `T`, then `T` must be a trivial type, the underlying pointer + /// must be properly aligned for accessing `T`, and `source.count` must be a /// multiple of `MemoryLayout.stride`. /// - /// After calling `copyBytes(from:count:)`, the `count` bytes of memory - /// referenced by this pointer are initialized to raw bytes. If the memory - /// is bound to type `T`, then it contains values of type `T`. + /// After calling `copyBytes(from:)`, the first `source.count` bytes of + /// memory referenced by this buffer are initialized to raw bytes. If the + /// memory is bound to type `T`, then it contains values of type `T`. /// - /// - Parameters: - /// - source: A pointer to the memory to copy bytes from. The memory at - /// `source..<(source + count)` must be initialized to a trivial type. - /// - count: The number of bytes to copy. `count` must not be negative. + /// - Parameter source: A buffer of raw bytes from which to copy. + /// `source.count` must be less than or equal to this buffer's `count`. @_inlineable public func copyBytes(from source: UnsafeRawBufferPointer) { _debugPrecondition(source.count <= self.count, @@ -258,14 +255,14 @@ public struct Unsafe${Mutable}RawBufferPointer /// Copies from a collection of `UInt8` into this buffer's memory. /// - /// If the `source.count` bytes of memory referenced by this pointer are - /// bound to a type `T`, then `T` must be a trivial type, the underlying - /// pointer must be properly aligned for accessing `T`, and `source.count` - /// must be a multiple of `MemoryLayout.stride`. + /// If the `source.count` bytes of memory referenced by this buffer are bound + /// to a type `T`, then `T` must be a trivial type, the underlying pointer + /// must be properly aligned for accessing `T`, and `source.count` must be a + /// multiple of `MemoryLayout.stride`. /// /// After calling `copyBytes(from:)`, the `source.count` bytes of memory - /// referenced by this pointer are initialized to raw bytes. If the memory - /// is bound to type `T`, then it contains values of type `T`. + /// referenced by this buffer are initialized to raw bytes. If the memory is + /// bound to type `T`, then it contains values of type `T`. /// /// - Parameter source: A collection of `UInt8` elements. `source.count` must /// be less than or equal to this buffer's `count`. @@ -288,9 +285,9 @@ public struct Unsafe${Mutable}RawBufferPointer /// at the given pointer. /// /// - Parameters: - /// - start: The address of the memory that starts the buffer. If `starts` is - /// `nil`, `count` must be zero. However, `count` may be zero even for a - /// non-`nil` `start`. + /// - start: The address of the memory that starts the buffer. If `starts` + /// is `nil`, `count` must be zero. However, `count` may be zero even + /// for a non-`nil` `start`. /// - count: The number of bytes to include in the buffer. `count` must not /// be negative. @_inlineable @@ -352,17 +349,26 @@ public struct Unsafe${Mutable}RawBufferPointer % end # !mutable % if not mutable: - /// Creates a raw buffer over the same memory as the given raw buffer slice. + /// Creates a raw buffer over the same memory as the given raw buffer slice, + /// with the indices rebased to zero. + /// + /// The new buffer represents the same region of memory as the slice, but its + /// indices start at zero instead of at the beginning of the slice in the + /// original buffer. The following code creates `slice`, a slice covering + /// part of an existing buffer instance, then rebases it into a new `rebased` + /// buffer. /// - /// The new raw buffer will represent the same region of memory as the slice, - /// but it's indices will be rebased to zero. Given: + /// let slice = buffer[n...] + /// let rebased = UnsafeRawBufferPointer(rebasing: slice) /// - /// let slice = buffer[n..) { self.init(start: slice.base.baseAddress! + slice.startIndex, @@ -370,17 +376,26 @@ public struct Unsafe${Mutable}RawBufferPointer } % end # !mutable - /// Creates a raw buffer over the same memory as the given raw buffer slice. + /// Creates a raw buffer over the same memory as the given raw buffer slice, + /// with the indices rebased to zero. /// - /// The new raw buffer will represent the same region of memory as the slice, - /// but it's indices will be rebased to zero. Given: + /// The new buffer represents the same region of memory as the slice, but its + /// indices start at zero instead of at the beginning of the slice in the + /// original buffer. The following code creates `slice`, a slice covering + /// part of an existing buffer instance, then rebases it into a new `rebased` + /// buffer. /// - /// let slice = buffer[n.. @@ -389,8 +404,7 @@ public struct Unsafe${Mutable}RawBufferPointer count: slice.count) } - /// Always zero, which is the index of the first byte in a - /// nonempty buffer. + /// Always zero, which is the index of the first byte in a nonempty buffer. @_inlineable public var startIndex: Int { return 0 @@ -490,31 +504,33 @@ public struct Unsafe${Mutable}RawBufferPointer } % if mutable: - /// Initializes memory in the buffer with the elements of - /// `source` and binds the initialized memory to type `T`. - /// - /// Returns an iterator to any elements of `source` that didn't fit in the - /// buffer, and a typed buffer of the written elements. - /// - /// - Precondition: The memory in `startIndex..<(source.count * - /// MemoryLayout.stride)` is uninitialized or initialized to a - /// trivial type. - /// - /// - Precondition: The buffer must contain sufficient memory to - /// accommodate at least `source.underestimateCount` elements. - /// - /// - Postcondition: The memory at `self[startIndex...stride] - /// is bound to type `T`. - /// - /// - Postcondition: The `T` values at `self[startIndex...stride]` - /// are initialized. + /// 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 + /// trivial type, and must be properly aligned for accessing `S.Element`. + /// The buffer must contain sufficient memory to accommodate + /// `source.underestimatedCount`. + /// + /// This method initializes the buffer with elements from `source` until + /// `source` is exhausted or, if `source` is a sequence but not a + /// collection, the buffer has no more room for its elements. After calling + /// `initializeMemory(as:from:)`, the memory referenced by the returned + /// `UnsafeMutableBufferPointer` instance is bound and initialized to type + /// `S.Element`. /// + /// - Parameters: + /// - type: The type of the elements to bind the buffer's memory to. + /// - source: A sequence of elements with which to initialize the buffer. + /// - Returns: An iterator to any elements of `source` that didn't fit in the + /// buffer, and a typed buffer of the written elements. The returned + /// buffer references memory starting at the same base address as this + /// buffer. // TODO: Optimize where `C` is a `ContiguousArrayBuffer`. @_inlineable public func initializeMemory( - as: S.Element.Type, from source: S + as type: S.Element.Type, from source: S ) -> (unwritten: S.Iterator, initialized: UnsafeMutableBufferPointer) { var it = source.makeIterator() diff --git a/stdlib/public/core/VarArgs.swift b/stdlib/public/core/VarArgs.swift index 26162cd88795a..4cf24980c650d 100644 --- a/stdlib/public/core/VarArgs.swift +++ b/stdlib/public/core/VarArgs.swift @@ -126,7 +126,7 @@ internal func _withVaList( /// uses, such as in a `class` initializer, you may find that the language /// rules do not allow you to use `withVaList(_:_:)` as intended. /// -/// - Parameters args: An array of arguments to convert to a C `va_list` +/// - Parameter args: An array of arguments to convert to a C `va_list` /// pointer. /// - Returns: A pointer that can be used with C functions that take a /// `va_list` argument.