Let it conform to `Codable`.
This commit is contained in:
parent
a1f456e63d
commit
5f285e886f
|
@ -58,6 +58,25 @@ public struct TimeSpecification {
|
|||
}
|
||||
}
|
||||
|
||||
extension TimeSpecification: Codable {
|
||||
public enum CodingKeys: String, CodingKey {
|
||||
case seconds, nanoseconds
|
||||
}
|
||||
|
||||
public func encode(to encoder: Encoder) throws {
|
||||
var container = encoder.container(keyedBy: CodingKeys.self)
|
||||
try container.encode(self.seconds, forKey: .seconds)
|
||||
try container.encode(self.nanoseconds, forKey: .nanoseconds)
|
||||
}
|
||||
|
||||
public init(from decoder: Decoder) throws {
|
||||
let container = try decoder.container(keyedBy: CodingKeys.self)
|
||||
let seconds = try container.decode(Int64.self, forKey: .seconds)
|
||||
let nanoseconds = try container.decode(Int32.self, forKey: .nanoseconds)
|
||||
self.init(seconds: seconds, nanoseconds: nanoseconds)
|
||||
}
|
||||
}
|
||||
|
||||
extension TimeSpecification: Equatable {
|
||||
public static func ==(lhs:TimeSpecification, rhs:TimeSpecification) -> Bool {
|
||||
return lhs.seconds == rhs.seconds && lhs.nanoseconds == rhs.nanoseconds
|
||||
|
|
|
@ -8,6 +8,8 @@
|
|||
import XCTest
|
||||
@testable import TimeSpecification
|
||||
|
||||
import Foundation
|
||||
|
||||
class TimeSpecificationTests: XCTestCase {
|
||||
func test_normalization() {
|
||||
let N1 = TimeSpecification(seconds:0, nanoseconds:1_234_567_890)
|
||||
|
@ -17,6 +19,15 @@ class TimeSpecificationTests: XCTestCase {
|
|||
XCTAssertTrue(N2.seconds == -3 && N2.nanoseconds == 765_432_110, "Normalization Test 2")
|
||||
}
|
||||
|
||||
func test_codable() throws {
|
||||
let spec = TimeSpecification(seconds: 123, nanoseconds: 456_789)
|
||||
let encoded = try JSONEncoder().encode(spec)
|
||||
XCTAssertEqual(String(data: encoded, encoding: .utf8), #"{"seconds":123,"nanoseconds":456789}"#)
|
||||
|
||||
let decoded = try JSONDecoder().decode(TimeSpecification.self, from: encoded)
|
||||
XCTAssertEqual(decoded, spec)
|
||||
}
|
||||
|
||||
func test_comparison() {
|
||||
let C1 = TimeSpecification(seconds:100, nanoseconds:100)
|
||||
let C2 = TimeSpecification(seconds: 98, nanoseconds:2_000_000_100)
|
||||
|
|
|
@ -6,7 +6,10 @@ extension TimeSpecificationTests {
|
|||
// `swift test --generate-linuxmain`
|
||||
// to regenerate.
|
||||
static let __allTests__TimeSpecificationTests = [
|
||||
("test_codable", test_codable),
|
||||
("test_comparison", test_comparison),
|
||||
("test_date", test_date),
|
||||
("test_description", test_description),
|
||||
("test_floatLiteral", test_floatLiteral),
|
||||
("test_integerLiteral", test_integerLiteral),
|
||||
("test_normalization", test_normalization),
|
||||
|
|
Loading…
Reference in New Issue