diff --git a/src/binarycookies/_serialize.py b/src/binarycookies/_serialize.py index 03551df..ce8087b 100644 --- a/src/binarycookies/_serialize.py +++ b/src/binarycookies/_serialize.py @@ -26,12 +26,16 @@ FLAG_VALUES = {Flag.UNKNOWN: 0, Flag.SECURE: 1, Flag.HTTPONLY: 4, Flag.SECURE_HTTPONLY: 5} -def date_to_mac_epoch(date: datetime) -> int: - """Converts a datetime object to mac epoch time. Naive datetimes are assumed to be UTC.""" +def date_to_mac_epoch(date: datetime) -> float: + """Converts a datetime object to mac epoch time. Naive datetimes are assumed to be UTC. + + The value is stored on disk as a 64-bit double, so the fractional part of the + timestamp is preserved instead of being truncated to whole seconds. + """ if date.tzinfo is None: date = date.replace(tzinfo=timezone.utc) mac_epoch_start = datetime(2001, 1, 1, tzinfo=timezone.utc) - return int((date - mac_epoch_start).total_seconds()) + return (date - mac_epoch_start).total_seconds() def write_string(data: BytesIO, value: str): diff --git a/tests/test_serialize.py b/tests/test_serialize.py index 7d49bb2..b6101e7 100644 --- a/tests/test_serialize.py +++ b/tests/test_serialize.py @@ -248,3 +248,44 @@ def test_domain_alias(): assert result.url == "aliased.com" assert result.domain == "aliased.com" + + +def test_date_to_mac_epoch_keeps_fractional_seconds(): + """The Mac epoch is stored as a double, so sub-second precision must be kept.""" + created = datetime(2023, 10, 1, 12, 34, 56, 789000, tzinfo=timezone.utc) + assert date_to_mac_epoch(created) == 717856496.789 + + +def test_dumps_stores_fractional_seconds_in_the_timestamp_double(): + """The on-disk timestamp is a double, so its fractional part must survive serialization.""" + created = datetime(2023, 10, 1, 12, 34, 56, 789000, tzinfo=timezone.utc) + data = dumps([{**COOKIE, "create_datetime": created.isoformat()}]) + + page_size = unpack(">i", data[8:12])[0] + page = data[12 : 12 + page_size] + cookie_offset = unpack("