Debian Codegraph @

third_party/rust/uniffi_bindgen/src/bindings/python/templates/TimestampHelper.py

raw
1 # The Timestamp type.
2 Timestamp = datetime.datetime
3
4 # There is a loss of precision when converting from Rust timestamps,
5 # which are accurate to the nanosecond,
6 # to Python datetimes, which have a variable precision due to the use of float as representation.
7 class _UniffiConverterTimestamp(_UniffiConverterRustBuffer):
8 @staticmethod
9 def read(buf):
10 seconds = buf.read_i64()
11 microseconds = buf.read_u32() / 1000
12 # Use fromtimestamp(0) then add the seconds using a timedelta. This
13 # ensures that we get OverflowError rather than ValueError when
14 # seconds is too large.
15 if seconds >= 0:
16 return datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc) + datetime.timedelta(seconds=seconds, microseconds=microseconds)
17 else:
18 return datetime.datetime.fromtimestamp(0, tz=datetime.timezone.utc) - datetime.timedelta(seconds=-seconds, microseconds=microseconds)
19
20 @staticmethod
21 def check_lower(value):
22 pass
23
24 @staticmethod
25 def write(value, buf):
26 if value >= datetime.datetime.fromtimestamp(0, datetime.timezone.utc):
27 sign = 1
28 delta = value - datetime.datetime.fromtimestamp(0, datetime.timezone.utc)
29 else:
30 sign = -1
31 delta = datetime.datetime.fromtimestamp(0, datetime.timezone.utc) - value
32
33 seconds = delta.seconds + delta.days * 24 * 3600
34 nanoseconds = delta.microseconds * 1000
35 buf.write_i64(sign * seconds)
36 buf.write_u32(nanoseconds)