summaryrefslogtreecommitdiffstats
path: root/third_party/rust/uniffi_bindgen/src/bindings/swift/templates/DurationHelper.swift
blob: c2aa49e9d13fd0209a6146788d1fb09d408b7218 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
fileprivate struct FfiConverterDuration: FfiConverterRustBuffer {
    typealias SwiftType = TimeInterval

    public static func read(from buf: inout (data: Data, offset: Data.Index)) throws -> TimeInterval {
        let seconds: UInt64 = try readInt(&buf)
        let nanoseconds: UInt32 = try readInt(&buf)
        return Double(seconds) + (Double(nanoseconds) / 1.0e9)
    }

    public static func write(_ value: TimeInterval, into buf: inout [UInt8]) {
        if value.rounded(.down) > Double(Int64.max) {
            fatalError("Duration overflow, exceeds max bounds supported by Uniffi")
        }

        if value < 0 {
            fatalError("Invalid duration, must be non-negative")
        }

        let seconds = UInt64(value)
        let nanoseconds = UInt32((value - Double(seconds)) * 1.0e9)
        writeInt(&buf, seconds)
        writeInt(&buf, nanoseconds)
    }
}