-
Notifications
You must be signed in to change notification settings - Fork 1
/
SizeProtocol.swift
110 lines (88 loc) · 2.7 KB
/
SizeProtocol.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
public protocol SizeProtocol: Hashable, CustomStringConvertible, Codable {
associatedtype Element
associatedtype PointType: PointProtocol where
PointType.Element == Self.Element
associatedtype RectType: RectProtocol where
RectType.Element == Self.Element
var width: Element { get set }
var height: Element { get set }
init(_ width: Element, _ height: Element)
}
extension SizeProtocol {
public func hash(into hasher: inout Hasher) {
hasher.combine(width)
hasher.combine(height)
}
public init(from decoder: Decoder) throws {
let c = try decoder.singleValueContainer()
let array = try c.decode([Element].self)
guard array.count >= 2 else {
throw DecodingError.dataCorruptedError(
in: c,
debugDescription: "array.count < 2")
}
self.init(array[0], array[1])
}
public func encode(to encoder: Encoder) throws {
var c = encoder.singleValueContainer()
let array = [width, height]
try c.encode(array)
}
public var description: String {
"\(width)x\(height)"
}
public var area: Element { width * height }
public static var zero: Self {
Self(.zero, .zero)
}
public func toPoint() -> PointType {
PointType(width, height)
}
public static func +(a: Self, b: Self) -> Self {
Self(a.width + b.width, a.height + b.height)
}
public static func +=(a: inout Self, b: Self) {
a = a + b
}
public static func -(a: Self, b: Self) -> Self {
Self(a.width - b.width, a.height - b.height)
}
public static func -=(a: inout Self, b: Self) {
a = a - b
}
public static func *(a: Element, b: Self) -> Self {
Self(a * b.width, a * b.height)
}
public static func *(a: Self, b: Element) -> Self {
b * a
}
public static func *=(a: inout Self, b: Element) {
a = a * b
}
public var transposed: Self {
Self(height, width)
}
}
extension SizeProtocol where Element: Comparable {
public var isLandscape: Bool {
width > height
}
public func isWiderThan(_ other: Self) -> Bool {
width * other.height >= other.width * height
}
}
extension SizeProtocol where Element: FloatingPoint {
public static func /(a: Self, b: Element) -> Self {
Self(a.width / b, a.height / b)
}
public static func /=(a: inout Self, b: Element) {
a = a / b
}
}
extension SizeProtocol where Element: BinaryFloatingPoint {
public func to<T: SizeProtocol>(type: T.Type) -> T where
T.Element: BinaryFloatingPoint
{
T(T.Element(width), T.Element(height))
}
}