Skip to content

Synchronize Measurement.swift from the overlay #1353

New issue

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

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

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 5, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
231 changes: 117 additions & 114 deletions Foundation/Measurement.swift
Original file line number Diff line number Diff line change
Expand Up @@ -2,48 +2,66 @@
//
// This source file is part of the Swift.org open source project
//
// Copyright (c) 2014 - 2016 Apple Inc. and the Swift project authors
// Copyright (c) 2014 - 2017 Apple Inc. and the Swift project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See http://swift.org/LICENSE.txt for license information
// See http://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
// See https://swift.org/LICENSE.txt for license information
// See https://swift.org/CONTRIBUTORS.txt for the list of Swift project authors
//
//===----------------------------------------------------------------------===//

#if DEPLOYMENT_RUNTIME_SWIFT
import CoreFoundation
#else
@_exported import Foundation // Clang module
import _SwiftCoreFoundationOverlayShims
#endif

/// A `Measurement` is a model type that holds a `Double` value associated with a `Unit`.
///
/// Measurements support a large set of operators, including `+`, `-`, `*`, `/`, and a full set of comparison operators.
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable, CustomStringConvertible {
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct Measurement<UnitType : Unit> : ReferenceConvertible, Comparable, Equatable {
public typealias ReferenceType = NSMeasurement

/// The unit component of the `Measurement`.
public let unit: UnitType

/// The value component of the `Measurement`.
public var value: Double

/// Create a `Measurement` given a specified value and unit.
public init(value: Double, unit: UnitType) {
self.value = value
self.unit = unit
}

public var hashValue: Int {
return Int(bitPattern: _CFHashDouble(value))
return Int(bitPattern: __CFHashDouble(value))
}

}

@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : CustomStringConvertible, CustomDebugStringConvertible, CustomReflectable {
public var description: String {
return "\(value) \(unit.symbol)"
}

public var debugDescription: String {
return "\(value) \(unit.symbol)"
}

public var customMirror: Mirror {
var c: [(label: String?, value: Any)] = []
c.append((label: "value", value: value))
c.append((label: "unit", value: unit.symbol))
return Mirror(self, children: c, displayStyle: Mirror.DisplayStyle.struct)
}
}


/// When a `Measurement` contains a `Dimension` unit, it gains the ability to convert between the kinds of units in that dimension.
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement where UnitType : Dimension {
/// Returns a new measurement created by converting to the specified unit.
///
Expand All @@ -62,7 +80,7 @@ extension Measurement where UnitType : Dimension {
}
}
}

/// Converts the measurement to the specified unit.
///
/// - parameter otherUnit: A unit of the same `Dimension`.
Expand Down Expand Up @@ -97,73 +115,9 @@ extension Measurement where UnitType : Dimension {
return Measurement(value: lhsValueInTermsOfBase - rhsValueInTermsOfBase, unit: type(of: lhs.unit).baseUnit())
}
}

/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value == rhsInLhs.value
}
}

/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is less than `rhs`.
public static func <(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value < rhsInLhs.value
}
}

/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value > rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is greater than `rhs`.
public static func >(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value > rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value > rhsInLhs.value
}
}

/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value < rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is less than or equal to `rhs`.
public static func <=(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value <= rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value <= rhsInLhs.value
}
}

/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value >= rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if `lhs` is greater or equal to `rhs`.
public static func >=(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value >= rhs.value
} else {
let rhsInLhs = rhs.converted(to: lhs.unit)
return lhs.value >= rhsInLhs.value
}
}
}

@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement {
/// Add two measurements of the same Unit.
/// - precondition: The `unit` of `lhs` and `rhs` must be `isEqual`.
Expand All @@ -187,6 +141,8 @@ extension Measurement {
}
}

/// Multiply a measurement by a scalar value.
/// - returns: A measurement of value `lhs.value * rhs` with the same unit as `lhs`.
public static func *(lhs: Measurement<UnitType>, rhs: Double) -> Measurement<UnitType> {
return Measurement(value: lhs.value * rhs, unit: lhs.unit)
}
Expand All @@ -209,57 +165,64 @@ extension Measurement {
return Measurement(value: lhs / rhs.value, unit: rhs.unit)
}

/// Compare two measurements of the same `Unit`.
/// - returns: `true` if `lhs.value == rhs.value && lhs.unit == rhs.unit`.
public static func ==(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value == rhs.value && lhs.unit == rhs.unit
}

/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value < rhs.value`
public static func <(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value < rhs.value
}

/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value > rhs.value`
public static func >(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value > rhs.value
}

/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value <= rhs.value`
public static func <=(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value <= rhs.value
/// Compare two measurements of the same `Dimension`.
///
/// If `lhs.unit == rhs.unit`, returns `lhs.value == rhs.value`. Otherwise, converts `rhs` to the same unit as `lhs` and then compares the resulting values.
/// - returns: `true` if the measurements are equal.
public static func ==<LeftHandSideType, RightHandSideType>(_ lhs: Measurement<LeftHandSideType>, _ rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value == rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase == rhsValueInTermsOfBase
}
}
return false
}
}

/// Compare two measurements of the same `Unit`.
/// - note: This function does not check `==` for the `unit` property of `lhs` and `rhs`.
/// - returns: `lhs.value >= rhs.value`
public static func >=(lhs: Measurement<UnitType>, rhs: Measurement<UnitType>) -> Bool {
return lhs.value >= rhs.value
/// - returns: `true` if the measurements can be compared and the `lhs` is less than the `rhs` converted value.
public static func <<LeftHandSideType, RightHandSideType>(lhs: Measurement<LeftHandSideType>, rhs: Measurement<RightHandSideType>) -> Bool {
if lhs.unit == rhs.unit {
return lhs.value < rhs.value
} else {
if let lhsDimensionalUnit = lhs.unit as? Dimension,
let rhsDimensionalUnit = rhs.unit as? Dimension {
if type(of: lhsDimensionalUnit).baseUnit() == type(of: rhsDimensionalUnit).baseUnit() {
let lhsValueInTermsOfBase = lhsDimensionalUnit.converter.baseUnitValue(fromValue: lhs.value)
let rhsValueInTermsOfBase = rhsDimensionalUnit.converter.baseUnitValue(fromValue: rhs.value)
return lhsValueInTermsOfBase < rhsValueInTermsOfBase
}
}
fatalError("Attempt to compare measurements with non-equal dimensions")
}
}
}

// Implementation note: similar to NSArray, NSDictionary, etc., NSMeasurement's import as an ObjC generic type is suppressed by the importer. Eventually we will need a more general purpose mechanism to correctly import generic types.

extension Measurement : _ObjectTypeBridgeable {
public static func _isBridgedToObjectiveC() -> Bool {
return true
}

#if DEPLOYMENT_RUNTIME_SWIFT
internal typealias MeasurementBridgeType = _ObjectTypeBridgeable
#else
internal typealias MeasurementBridgeType = _ObjectiveCBridgeable
#endif

@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : MeasurementBridgeType {
@_semantics("convertToObjectiveC")
public func _bridgeToObjectiveC() -> NSMeasurement {
return NSMeasurement(doubleValue: value, unit: unit)
}

public static func _forceBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) {
result = Measurement(value: source.doubleValue, unit: source.unit as! UnitType)
}

public static func _conditionallyBridgeFromObjectiveC(_ source: NSMeasurement, result: inout Measurement?) -> Bool {
if let u = source.unit as? UnitType {
result = Measurement(value: source.doubleValue, unit: u)
Expand All @@ -268,13 +231,53 @@ extension Measurement : _ObjectTypeBridgeable {
return false
}
}

public static func _unconditionallyBridgeFromObjectiveC(_ source: NSMeasurement?) -> Measurement {
let u = source!.unit as! UnitType
return Measurement(value: source!.doubleValue, unit: u)
}
}

@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension NSMeasurement : _HasCustomAnyHashableRepresentation {
// Must be @nonobjc to avoid infinite recursion during bridging.
@nonobjc
public func _toCustomAnyHashable() -> AnyHashable? {
#if DEPLOYMENT_RUNTIME_SWIFT
return AnyHashable(Measurement._unconditionallyBridgeFromObjectiveC(self))
#else
return AnyHashable(self as Measurement)
#endif
}
}

// This workaround is required for the time being, because Swift doesn't support covariance for Measurement (26607639)
@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String {
if let result = string(for: measurement) {
return result
} else {
return ""
}
}
}

// @available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
// extension Unit : Codable {
// public convenience init(from decoder: Decoder) throws {
// let container = try decoder.singleValueContainer()
// let symbol = try container.decode(String.self)
// self.init(symbol: symbol)
// }

// public func encode(to encoder: Encoder) throws {
// var container = encoder.singleValueContainer()
// try container.encode(self.symbol)
// }
// }

@available(OSX 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
extension Measurement : Codable {
private enum CodingKeys : Int, CodingKey {
case value
Expand Down
4 changes: 0 additions & 4 deletions Foundation/MeasurementFormatter.swift
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,3 @@ open class MeasurementFormatter : Formatter, NSSecureCoding {
open override func encode(with aCoder: NSCoder) { NSUnimplemented() }
public static var supportsSecureCoding: Bool { return true }
}

extension MeasurementFormatter {
public func string<UnitType>(from measurement: Measurement<UnitType>) -> String { NSUnimplemented() }
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why did this function go away?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Totally missed that. Thanks, this looks great.