Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/swift/templates/TimestampHelper.swift

raw
1 #if swift(>=5.8)
2 @_documentation(visibility: private)
3 #endif
4 fileprivate struct FfiConverterTimestamp: FfiConverterRustBuffer {
5 typealias SwiftType = Date
6
7 public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> Date {
8 let seconds: Int64 = try readInt(&buf)
9 let nanoseconds: UInt32 = try readInt(&buf)
10 if seconds >= 0 {
11 let delta = Double(seconds) + (Double(nanoseconds) / 1.0e9)
12 return Date.init(timeIntervalSince1970: delta)
13 } else {
14 let delta = Double(seconds) - (Double(nanoseconds) / 1.0e9)
15 return Date.init(timeIntervalSince1970: delta)
16 }
17 }
18
19 public static func write(_ value: Date, into buf: inout [UInt8]) {
20 var delta = value.timeIntervalSince1970
21 var sign: Int64 = 1
22 if delta < 0 {
23 // The nanoseconds portion of the epoch offset must always be
24 // positive, to simplify the calculation we will use the absolute
25 // value of the offset.
26 sign = -1
27 delta = -delta
28 }
29 if delta.rounded(.down) > Double(Int64.max) {
30 fatalError("Timestamp overflow, exceeds max bounds supported by Uniffi")
31 }
32 let seconds = Int64(delta)
33 let nanoseconds = UInt32((delta - Double(seconds)) * 1.0e9)
34 writeInt(&buf, sign * seconds)
35 writeInt(&buf, nanoseconds)
36 }
37 }