Skip to content
Open
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
14 changes: 13 additions & 1 deletion Sources/MessagePackExtension.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,19 @@ extension MessagePackExtension {
case let (0, value):
self.data = packInteger(for: value.bigEndian)
default:
self.data = packInteger(for: UInt32(timestamp.nanoseconds).bigEndian) + packInteger(for: Int64(timestamp.seconds).bigEndian)
if timestamp.nanoseconds < 0 {
// Adjust these values from
// "negative nanosec from nearest larger negative integer"
// to
// "positive nanosec from nearest smaller nagative integer".
let seconds = timestamp.seconds - 1
let nanoSeconds = (MessagePackTimestamp.NSEC_MAX + 1) + timestamp.nanoseconds
self.data = packInteger(for: UInt32(nanoSeconds).bigEndian) + packInteger(for: Int64(seconds).bigEndian)
}
else {
self.data = packInteger(for: UInt32(timestamp.nanoseconds).bigEndian) + packInteger(for: Int64(timestamp.seconds).bigEndian)
}

}
}
}
Expand Down
1 change: 1 addition & 0 deletions Sources/MessagePackTimestamp.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
import Foundation

public struct MessagePackTimestamp: Equatable {
internal static let NSEC_MAX: Int64 = 999999999
public var seconds: Int64
public var nanoseconds: Int64

Expand Down
13 changes: 13 additions & 0 deletions Tests/MessagePackerTests/TimestampPackedTests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,17 @@ class TimestampPackedTests: XCTestCase {
let output = Data([199, 12, 255, 25, 69, 229, 222, 0, 0, 0, 14, 211, 132, 20, 74])
XCTAssertEqual(try encoder.encode(input), output)
}

func testTimestamp96WithNegativeDate() throws {
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"
formatter.locale = Locale(identifier: "en_US_POSIX")
formatter.timeZone = TimeZone(abbreviation: "UTC")
let date = formatter.date(from: "0023-09-24T00:36:30.078Z")!

let timestamp = MessagePackTimestamp(date: date)
let encoded = try encoder.encode(timestamp)
let decoded = try MessagePackDecoder().decode(MessagePackTimestamp.self, from: encoded)
XCTAssertEqual(date, Date(timestamp: decoded))
}
}