-
Notifications
You must be signed in to change notification settings - Fork 460
/
Google_Protobuf_Duration+Extensions.swift
240 lines (222 loc) · 7.81 KB
/
Google_Protobuf_Duration+Extensions.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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
// Sources/SwiftProtobuf/Google_Protobuf_Duration+Extensions.swift - Extensions for Duration type
//
// Copyright (c) 2014 - 2016 Apple Inc. and the project authors
// Licensed under Apache License v2.0 with Runtime Library Exception
//
// See LICENSE.txt for license information:
// https://github.com/apple/swift-protobuf/blob/main/LICENSE.txt
//
// -----------------------------------------------------------------------------
///
/// Extends the generated Duration struct with various custom behaviors:
/// * JSON coding and decoding
/// * Arithmetic operations
///
// -----------------------------------------------------------------------------
import Foundation
private let minDurationSeconds: Int64 = -maxDurationSeconds
private let maxDurationSeconds: Int64 = 315_576_000_000
private func parseDuration(text: String) throws -> (Int64, Int32) {
var digits = [Character]()
var digitCount = 0
var total = 0
var chars = text.makeIterator()
var seconds: Int64?
var nanos: Int32 = 0
var isNegative = false
while let c = chars.next() {
switch c {
case "-":
// Only accept '-' as very first character
if total > 0 {
throw JSONDecodingError.malformedDuration
}
digits.append(c)
isNegative = true
case "0", "1", "2", "3", "4", "5", "6", "7", "8", "9":
digits.append(c)
digitCount += 1
case ".":
if let _ = seconds {
throw JSONDecodingError.malformedDuration
}
let digitString = String(digits)
if let s = Int64(digitString),
s >= minDurationSeconds && s <= maxDurationSeconds
{
seconds = s
} else {
throw JSONDecodingError.malformedDuration
}
digits.removeAll()
digitCount = 0
case "s":
if let _ = seconds {
// Seconds already set, digits holds nanos
while digitCount < 9 {
digits.append(Character("0"))
digitCount += 1
}
while digitCount > 9 {
digits.removeLast()
digitCount -= 1
}
let digitString = String(digits)
if let rawNanos = Int32(digitString) {
if isNegative {
nanos = -rawNanos
} else {
nanos = rawNanos
}
} else {
throw JSONDecodingError.malformedDuration
}
} else {
// No fraction, we just have an integral number of seconds
let digitString = String(digits)
if let s = Int64(digitString),
s >= minDurationSeconds && s <= maxDurationSeconds
{
seconds = s
} else {
throw JSONDecodingError.malformedDuration
}
}
// Fail if there are characters after 's'
if chars.next() != nil {
throw JSONDecodingError.malformedDuration
}
return (seconds!, nanos)
default:
throw JSONDecodingError.malformedDuration
}
total += 1
}
throw JSONDecodingError.malformedDuration
}
private func formatDuration(seconds: Int64, nanos: Int32) -> String? {
let (seconds, nanos) = normalizeForDuration(seconds: seconds, nanos: nanos)
guard seconds >= minDurationSeconds && seconds <= maxDurationSeconds else {
return nil
}
let nanosString = nanosToString(nanos: nanos) // Includes leading '.' if needed
if seconds == 0 && nanos < 0 {
return "-0\(nanosString)s"
}
return "\(seconds)\(nanosString)s"
}
extension Google_Protobuf_Duration {
/// Creates a new `Google_Protobuf_Duration` equal to the given number of
/// seconds and nanoseconds.
///
/// - Parameter seconds: The number of seconds.
/// - Parameter nanos: The number of nanoseconds.
public init(seconds: Int64 = 0, nanos: Int32 = 0) {
self.init()
self.seconds = seconds
self.nanos = nanos
}
}
extension Google_Protobuf_Duration: _CustomJSONCodable {
mutating func decodeJSON(from decoder: inout JSONDecoder) throws {
let s = try decoder.scanner.nextQuotedString()
(seconds, nanos) = try parseDuration(text: s)
}
func encodedJSONString(options: JSONEncodingOptions) throws -> String {
if let formatted = formatDuration(seconds: seconds, nanos: nanos) {
return "\"\(formatted)\""
} else {
throw JSONEncodingError.durationRange
}
}
}
extension Google_Protobuf_Duration: ExpressibleByFloatLiteral {
public typealias FloatLiteralType = Double
/// Creates a new `Google_Protobuf_Duration` from a floating point literal
/// that is interpreted as a duration in seconds, rounded to the nearest
/// nanosecond.
public init(floatLiteral value: Double) {
let sd = trunc(value)
let nd = round((value - sd) * TimeInterval(nanosPerSecond))
let (s, n) = normalizeForDuration(seconds: Int64(sd), nanos: Int32(nd))
self.init(seconds: s, nanos: n)
}
}
extension Google_Protobuf_Duration {
/// Creates a new `Google_Protobuf_Duration` that is equal to the given
/// `TimeInterval` (measured in seconds), rounded to the nearest nanosecond.
///
/// - Parameter timeInterval: The `TimeInterval`.
public init(timeInterval: TimeInterval) {
let sd = trunc(timeInterval)
let nd = round((timeInterval - sd) * TimeInterval(nanosPerSecond))
let (s, n) = normalizeForDuration(seconds: Int64(sd), nanos: Int32(nd))
self.init(seconds: s, nanos: n)
}
/// The `TimeInterval` (measured in seconds) equal to this duration.
public var timeInterval: TimeInterval {
TimeInterval(self.seconds) + TimeInterval(self.nanos) / TimeInterval(nanosPerSecond)
}
}
private func normalizeForDuration(
seconds: Int64,
nanos: Int32
) -> (seconds: Int64, nanos: Int32) {
var s = seconds
var n = nanos
// If the magnitude of n exceeds a second then
// we need to factor it into s instead.
if n >= nanosPerSecond || n <= -nanosPerSecond {
s += Int64(n / nanosPerSecond)
n = n % nanosPerSecond
}
// The Duration spec says that when s != 0, s and
// n must have the same sign.
if s > 0 && n < 0 {
n += nanosPerSecond
s -= 1
} else if s < 0 && n > 0 {
n -= nanosPerSecond
s += 1
}
return (seconds: s, nanos: n)
}
public prefix func - (
operand: Google_Protobuf_Duration
) -> Google_Protobuf_Duration {
let (s, n) = normalizeForDuration(
seconds: -operand.seconds,
nanos: -operand.nanos
)
return Google_Protobuf_Duration(seconds: s, nanos: n)
}
public func + (
lhs: Google_Protobuf_Duration,
rhs: Google_Protobuf_Duration
) -> Google_Protobuf_Duration {
let (s, n) = normalizeForDuration(
seconds: lhs.seconds + rhs.seconds,
nanos: lhs.nanos + rhs.nanos
)
return Google_Protobuf_Duration(seconds: s, nanos: n)
}
public func - (
lhs: Google_Protobuf_Duration,
rhs: Google_Protobuf_Duration
) -> Google_Protobuf_Duration {
let (s, n) = normalizeForDuration(
seconds: lhs.seconds - rhs.seconds,
nanos: lhs.nanos - rhs.nanos
)
return Google_Protobuf_Duration(seconds: s, nanos: n)
}
public func - (
lhs: Google_Protobuf_Timestamp,
rhs: Google_Protobuf_Timestamp
) -> Google_Protobuf_Duration {
let (s, n) = normalizeForDuration(
seconds: lhs.seconds - rhs.seconds,
nanos: lhs.nanos - rhs.nanos
)
return Google_Protobuf_Duration(seconds: s, nanos: n)
}