|
| 1 | +import Foundation |
| 2 | + |
| 3 | +extension FixedWidthInteger { |
| 4 | + public func scaled<T: FixedWidthInteger>() -> T { |
| 5 | + let sizeDelta = MemoryLayout<Self>.size * 8 - MemoryLayout<T>.size * 8 |
| 6 | + if sizeDelta > 0 { |
| 7 | + return T(self >> sizeDelta) |
| 8 | + } |
| 9 | + if sizeDelta < 0 { |
| 10 | + return T(self) >> sizeDelta |
| 11 | + } |
| 12 | + return T(self) |
| 13 | + } |
| 14 | + |
| 15 | + public func scaled<T: BinaryFloatingPoint>() -> T { |
| 16 | + T(self) / T(Self.max) |
| 17 | + } |
| 18 | +} |
| 19 | + |
| 20 | +extension FixedWidthInteger where Self: UnsignedInteger { |
| 21 | + public func scalingDown(factor: Self) -> Self { |
| 22 | + let portion: Float = Float(factor) / Float(Self.max) |
| 23 | + let newValue = Float(self) * portion |
| 24 | + return Self.init(Swift.max(0, Swift.min(newValue, Float(Self.max)))) |
| 25 | + } |
| 26 | + |
| 27 | + public func scalingUp(factor: Self) -> Self { |
| 28 | + guard factor > 0 else { return self } |
| 29 | + let portion: Float = Float(Self.max) / Float(factor) |
| 30 | + let newValue = Float(self) * portion |
| 31 | + return Self.init(Swift.max(0, Swift.min(newValue, Float(Self.max)))) |
| 32 | + } |
| 33 | +} |
| 34 | + |
| 35 | +extension FixedWidthInteger { |
| 36 | + public func normalized(in range: ClosedRange<Self> = .maxRange) -> Float { |
| 37 | + guard range.upperBound - range.lowerBound > 0 else { return 0 } |
| 38 | + let value = Swift.min(Swift.max(self, range.lowerBound), range.upperBound) |
| 39 | + return Float(value - range.lowerBound) / Float(range.upperBound - range.lowerBound) |
| 40 | + } |
| 41 | +} |
| 42 | + |
| 43 | +extension Range where Bound: FixedWidthInteger { |
| 44 | + public static var maxRange: Self { |
| 45 | + Bound.min..<Bound.max |
| 46 | + } |
| 47 | +} |
| 48 | + |
| 49 | +extension ClosedRange where Bound: FixedWidthInteger { |
| 50 | + public static var maxRange: Self { |
| 51 | + Bound.min...Bound.max |
| 52 | + } |
| 53 | +} |
0 commit comments