summaryrefslogtreecommitdiffstats
path: root/third_party/rust/uniffi_bindgen/src/bindings/python/templates/DurationHelper.py
blob: ecb035b7f40c0f8f15e13dd495bbdeb7bbdb7d0b (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
25
# The Duration type.
Duration = datetime.timedelta

# There is a loss of precision when converting from Rust durations,
# which are accurate to the nanosecond,
# to Python durations, which are only accurate to the microsecond.
class _UniffiConverterDuration(_UniffiConverterRustBuffer):
    @staticmethod
    def read(buf):
        seconds = buf.read_u64()
        microseconds = buf.read_u32() / 1.0e3
        return datetime.timedelta(seconds=seconds, microseconds=microseconds)

    @staticmethod
    def check_lower(value):
        seconds = value.seconds + value.days * 24 * 3600
        if seconds < 0:
            raise ValueError("Invalid duration, must be non-negative")

    @staticmethod
    def write(value, buf):
        seconds = value.seconds + value.days * 24 * 3600
        nanoseconds = value.microseconds * 1000
        buf.write_i64(seconds)
        buf.write_u32(nanoseconds)