~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zat

atproto utils for zig · mirror of https://tangled.org/zat.dev/zat

0
0
362 lines · 15.1 KB Raw History
//! atproto datetime syntax — https://atproto.com/specs/lexicon#datetime
//!
//! the pinned atproto profile of RFC 3339 — stricter than the RFC, and the
//! spec text pins each divergence:
//! - upper-case 'T' and 'Z' required ("lower-case is not allowed")
//! - timezone required; "-00:00" ("negative zero") specifically disallowed
//! - "Datetimes before year zero ... are specifically disallowed" — enforced
//!   on the NORMALIZED instant, so an offset cannot smuggle one in
//! - fraction: "arbitrary fractional precision digits are allowed"; parsed
//!   at microsecond precision (truncation is the spec's own acknowledged
//!   "loss-of-precision" round-trip ambiguity)
//! - second 60 (leap second) is not in the profile's grammar and is
//!   rejected. general RFC 3339 parsers differ here (rust's jiff clamps
//!   :60 to the last instant of :59; chrono represents-but-ignores) — a
//!   deliberate divergence from them, matching the interop-fixture-passing
//!   validator this type replaces.
//! validated against the atproto interop fixtures (interop_tests.zig runs
//! Datetime.parse over datetime_syntax_valid / _invalid / _parse_invalid).
//!
//! this type exists because the string↔instant conversion kept being
//! hand-rolled: two byte-identical formatRfc3339s in stream, a 45-line
//! parser in the jetstream SDK example. parse and format live here, next
//! to the rest of the atproto syntax family (Tid, Did, Nsid, Rkey).

const std = @import("std");

/// microseconds since the unix epoch, UTC. negative = before 1970.
micros: i64,

/// canonical rendering length: "YYYY-MM-DDTHH:MM:SS.ffffffZ".len = 27
pub const string_len = "YYYY-MM-DDTHH:MM:SS.ffffffZ".len;

/// millisecond rendering length: "YYYY-MM-DDTHH:MM:SS.fffZ".len = 24
pub const millis_string_len = "YYYY-MM-DDTHH:MM:SS.fffZ".len;

pub fn fromMicros(micros: i64) @This() {
    return .{ .micros = micros };
}

/// the instant `seconds` after the unix epoch (negative = before 1970).
/// null outside the years 0000 through 9999, which the profile's
/// four-digit year cannot render.
pub fn fromSeconds(seconds: i64) ?@This() {
    return fromScaled(seconds, std.time.us_per_s);
}

/// the instant `millis` after the unix epoch, as JavaScript's `Date` holds
/// it. null outside the years 0000 through 9999.
pub fn fromMillis(millis: i64) ?@This() {
    return fromScaled(millis, std.time.us_per_ms);
}

fn fromScaled(value: i64, us_per_unit: i64) ?@This() {
    const micros = std.math.mul(i64, value, us_per_unit) catch return null;
    if (micros < min_micros or micros > max_micros) return null;
    return .{ .micros = micros };
}

/// parse the full atproto datetime profile, applying any UTC offset.
/// null on syntactic or semantic invalidity (month 0, Feb 30, hour 25,
/// "-00:00", instants before year 0). fractional digits beyond
/// microseconds are truncated.
pub fn parse(s: []const u8) ?@This() {
    if (s.len < "0000-01-01T00:00:00Z".len or s.len > 64) return null;

    const head = s[0.."0000-01-01T00:00:00".len];
    const delimiters = [_]struct { u5, u8 }{
        .{ 4, '-' },
        .{ 7, '-' },
        .{ 10, 'T' },
        .{ 13, ':' },
        .{ 16, ':' },
    };
    for (delimiters) |delimiter|
        if (head[delimiter[0]] != delimiter[1])
            return null;

    const year = parse4(head[0..4]) orelse return null;
    const month = parse2(head[5..7], 12) orelse return null;
    if (month == 0)
        return null;
    const day = parse2(head[8..10], daysInMonth(year, month)) orelse return null;
    if (day == 0)
        return null;
    const hour = parse2(head[11..13], 23) orelse return null;
    const minute = parse2(head[14..16], 59) orelse return null;
    const second = parse2(head[17..], 59) orelse return null;

    const pos, const frac_us = if (s[head.len] == '.') pos: {
        const start = head.len + 1;
        const len = @min(20, s.len - start);
        var frac_us: u32 = 0;
        var scale: u32 = 100_000;
        const frac_len = for (s[start..][0..len], 0..) |c, i| {
            if (c < '0' or c > '9')
                break i;
            if (scale > 0) {
                frac_us += scale * (c - '0');
                scale /= 10;
            }
        } else len;
        if (frac_len == 0)
            return null;
        const pos = start + frac_len;
        if (pos == s.len)
            return null
        else
            break :pos .{ pos, frac_us };
    } else .{ head.len, 0 };

    const offset_minutes = offset_minutes: {
        const tz_sign: i12 = switch (s[pos]) {
            'Z' => if (pos + 1 != s.len)
                return null
            else
                break :offset_minutes 0,

            '+' => 1,

            '-' => -1,

            else => return null,
        };

        const remaining = if (pos + 6 == s.len)
            s[pos + 1 ..][0..5]
        else
            return null;
        if (remaining[2] != ':')
            return null;
        const tz_hour = parse2(remaining[0..2], 23) orelse return null;
        const tz_minute = parse2(remaining[3..], 59) orelse return null;
        // RFC 3339 §4.3: "-00:00" means "offset unknown" and the
        // atproto profile rejects it
        if (tz_sign < 0 and tz_hour == 0 and tz_minute == 0) return null;
        break :offset_minutes tz_sign * (@as(i12, tz_hour) * 60 + tz_minute);
    };

    const civil: Civil = .{
        .year = year,
        .month = month,
        .day = day,
    };

    const days = civil.daysSinceUnixEpoch();
    const local_micros = days * std.time.us_per_day +
        (@as(i64, hour) * 3600 + @as(i64, minute) * 60 + @as(i64, second)) * std.time.us_per_s +
        frac_us;
    const utc_micros = local_micros - @as(i64, offset_minutes) * std.time.us_per_min;

    // the profile's floor: nothing normalizes before 0000-01-01T00:00:00Z
    // (this generalizes the fixtures' "normalizes to a negative time" case)
    if (utc_micros < min_micros) return null;
    return .{ .micros = utc_micros };
}

/// canonical atproto form, microsecond precision, always 'Z':
/// "1985-04-12T23:20:50.123456Z". the instant must lie in years 0000-9999.
pub fn toString(self: @This()) [string_len]u8 {
    return self.render(6);
}

/// millisecond precision, always 'Z': "1985-04-12T23:20:50.123Z", the form
/// JavaScript's `Date.prototype.toISOString` emits and the reference PDS
/// writes. sub-millisecond digits are truncated toward the past. the instant
/// must lie in years 0000-9999.
pub fn toStringMillis(self: @This()) [millis_string_len]u8 {
    return self.render(3);
}

fn render(self: @This(), comptime frac_digits: comptime_int) ["YYYY-MM-DDTHH:MM:SS.Z".len + frac_digits]u8 {
    std.debug.assert(self.micros >= min_micros and self.micros <= max_micros);
    const days = @divFloor(self.micros, std.time.us_per_day);
    const day_us = self.micros - days * std.time.us_per_day;
    const civil: Civil = .fromDays(days);
    const day_s: u64 = @intCast(@divTrunc(day_us, std.time.us_per_s));
    const frac: u64 = @intCast(@divTrunc(@mod(day_us, std.time.us_per_s), std.math.pow(i64, 10, 6 - frac_digits)));
    var buf: ["YYYY-MM-DDTHH:MM:SS.Z".len + frac_digits]u8 = undefined;
    _ = std.fmt.bufPrint(&buf, "{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}.{d:0>" ++ std.fmt.comptimePrint("{d}", .{frac_digits}) ++ "}Z", .{
        @as(u64, @intCast(civil.year)),
        civil.month,
        civil.day,
        day_s / 3600,
        (day_s % 3600) / 60,
        day_s % 60,
        frac,
    }) catch unreachable;
    return buf;
}

/// 0000-01-01T00:00:00Z in unix-epoch microseconds
const min_micros: i64 = Civil.unix_epoch.daysSinceUnixEpoch() * std.time.us_per_day;
/// 9999-12-31T23:59:59.999999Z in unix-epoch microseconds
const max_micros: i64 = (Civil{ .year = 10000, .month = 1, .day = 1 }).daysSinceUnixEpoch() * std.time.us_per_day - 1;

fn parse2(s: *const [2]u8, upperbound: anytype) ?switch (@TypeOf(upperbound)) {
    comptime_int => std.math.IntFittingRange(0, upperbound),
    void => u7,
    else => |T| T,
} {
    const a, const b = s.*;
    if (a < '0' or a > '9' or b < '0' or b > '9') return null;
    const val = @as(u7, @intCast(a - '0')) * 10 + @as(u4, @intCast(b - '0'));
    if (@TypeOf(upperbound) != void and val > upperbound)
        return null;
    return @intCast(val);
}

fn parse4(s: *const [4]u8) ?u14 {
    const hi = parse2(s[0..2], {}) orelse return null;
    const lo = parse2(s[2..], {}) orelse return null;
    return @as(u14, hi) * 100 + lo;
}

fn isLeap(year: u14) bool {
    return (year % 4 == 0 and year % 100 != 0) or year % 400 == 0;
}

fn daysInMonth(year: u14, month: u4) u5 {
    return switch (month) {
        1, 3, 5, 7, 8, 10, 12 => 31,
        4, 6, 9, 11 => 30,
        2 => if (isLeap(year)) 29 else 28,
        else => 0,
    };
}

const Civil = struct {
    year: i64,
    month: u4,
    day: u5,

    const unix_epoch: @This() = .{
        .year = 0,
        .month = 1,
        .day = 1,
    };

    const constants = enum {
        const magic_leap_year = 400;
        const max_yoe = magic_leap_year - 1; // 399
        const max_doy = 365;
        const max_doe = max_yoe * max_doy + (max_yoe / 4) - (max_yoe / 100) + max_doy; // 146096

        const min_no_of_leap_years_in_a_century = 100 / 4 - 1; // 24

        const some_magic = 153;

        const unix_epoch_days_offset = 719468;
    };

    /// Hinnant's civil_from_days: inverse of daysFromCivil.
    fn fromDays(z0: i64) @This() {
        const z = z0 + constants.unix_epoch_days_offset;
        const era = @divFloor(z, constants.max_doe + 1);
        const doe = z - era * (constants.max_doe + 1); // [0, 146096]
        const yoe = @divFloor(doe - @divFloor(doe, constants.max_doy * 4) + @divFloor(doe, constants.max_doy * 100 + constants.min_no_of_leap_years_in_a_century) - @divFloor(doe, constants.max_doe), constants.max_doy); // [0, 399]
        const y = yoe + era * constants.magic_leap_year;
        const doy = doe - (constants.max_doy * yoe + @divFloor(yoe, 4) - @divFloor(yoe, 100)); // [0, 365]
        const mp = @divFloor(5 * doy + 2, constants.some_magic); // [0, 11]
        const d = doy - @divFloor(constants.some_magic * mp + 2, 5) + 1; // [1, 31]
        const m = if (mp < 10) mp + 3 else mp - 9; // [1, 12]
        return .{ .year = if (m <= 2) y + 1 else y, .month = @intCast(m), .day = @intCast(d) };
    }

    /// Howard Hinnant's days_from_civil: days since 1970-01-01 for a proleptic
    /// Gregorian date. exact over the whole 0000..9999 profile, unlike
    /// std.time.epoch which is unsigned and 1970-anchored.
    fn daysSinceUnixEpoch(self: @This()) i64 {
        const y = if (self.month <= 2) self.year - 1 else self.year;
        const era = @divFloor(y, constants.magic_leap_year);
        const yoe = y - era * constants.magic_leap_year; // [0, 399]
        const mp: u4 = @intCast(@mod(@as(u5, self.month) + 9, 12)); // Mar=0 .. Feb=11
        const doy: u9 = @intCast(@divFloor(@as(u11, constants.some_magic) * mp + 2, 5) + self.day - 1); // [0, 365]
        const doe = yoe * constants.max_doy + @divFloor(yoe, 4) - @divFloor(yoe, 100) + doy; // [0, 146096]
        return era * (constants.max_doe + 1) + doe - constants.unix_epoch_days_offset;
    }
};

// === tests ===
// the atproto interop fixtures run against Datetime.parse in
// interop_tests.zig; these pin the numeric semantics fixtures can't.

const testing = std.testing;

test "parse and toString round-trip the canonical form" {
    const dt = parse("1985-04-12T23:20:50.123456Z").?;
    try testing.expectEqual(482196050123456, dt.micros);
    try testing.expectEqualStrings("1985-04-12T23:20:50.123456Z", &dt.toString());
}

test "offsets normalize to UTC" {
    const utc = parse("1985-04-12T23:20:50.123Z").?;
    const minus7 = parse("1985-04-12T16:20:50.123-07:00").?;
    const plus145 = parse("1985-04-13T01:05:50.123+01:45").?;
    try testing.expectEqual(utc.micros, minus7.micros);
    try testing.expectEqual(utc.micros, plus145.micros);
}

test "fraction truncates past microseconds; short fractions scale" {
    try testing.expectEqual(
        parse("1985-04-12T23:20:50.123456Z").?.micros,
        parse("1985-04-12T23:20:50.1234567891Z").?.micros,
    );
    try testing.expectEqual(
        482196050100000,
        parse("1985-04-12T23:20:50.1Z").?.micros,
    );
}

test "epoch identities and pre-1970 instants" {
    try testing.expectEqual(0, parse("1970-01-01T00:00:00Z").?.micros);
    const pre = parse("1969-12-31T23:59:59.000001Z").?;
    try testing.expectEqual(-999_999, pre.micros);
    try testing.expectEqualStrings("1969-12-31T23:59:59.000001Z", &pre.toString());
}

test "the year-zero floor is an instant rule, not a string rule" {
    try testing.expect(parse("0000-01-01T00:00:00Z") != null);
    try testing.expect(parse("0000-01-01T00:00:00+00:00") != null);
    // anything that NORMALIZES before the floor is out, not just the
    // fixtures' exact case
    try testing.expect(parse("0000-01-01T00:00:00+01:00") == null);
    try testing.expect(parse("0000-01-01T00:30:00+01:00") == null);
}

test "rejects the profile's forbidden shapes" {
    try testing.expect(parse("1985-04-12T23:20:50.123-00:00") == null); // unknown offset
    try testing.expect(parse("1985-04-12T23:20:61.123Z") == null); // semantic
    try testing.expect(parse("1985-02-30T00:00:00Z") == null); // Feb 30
    try testing.expect(parse("1985-04-12 23:20:50.123Z") == null); // space separator
    try testing.expect(parse("1985-04-12T23:20:50.Z") == null); // empty fraction
    try testing.expect(parse("1985-04-12T23:20:50") == null); // no timezone
}

test "leap handling matches the calendar both directions" {
    const feb29 = parse("2024-02-29T12:00:00Z").?;
    try testing.expectEqualStrings("2024-02-29T12:00:00.000000Z", &feb29.toString());
    try testing.expect(parse("2023-02-29T12:00:00Z") == null);
    try testing.expect(parse("1900-02-29T12:00:00Z") == null); // century non-leap
    try testing.expect(parse("2000-02-29T12:00:00Z") != null); // 400-year leap
}

test "toStringMillis renders the JavaScript toISOString form" {
    try testing.expectEqualStrings("1970-01-01T00:00:00.000Z", &fromSeconds(0).?.toStringMillis());
    try testing.expectEqualStrings("2026-10-01T00:00:00.000Z", &fromSeconds(1790812800).?.toStringMillis());
    try testing.expectEqualStrings("2023-04-12T04:53:57.057Z", &fromMillis(1681275237057).?.toStringMillis());
    // sub-millisecond digits truncate toward the past, before and after 1970
    try testing.expectEqualStrings("1985-04-12T23:20:50.123Z", &parse("1985-04-12T23:20:50.123999Z").?.toStringMillis());
    try testing.expectEqualStrings("1969-12-31T23:59:59.999Z", &fromMicros(-1).toStringMillis());
    try testing.expectEqualStrings("1969-12-31T23:59:59.000000Z", &fromSeconds(-1).?.toString());
}

test "fromSeconds and fromMillis cover exactly the four-digit years" {
    try testing.expectEqualStrings("0000-01-01T00:00:00.000Z", &fromSeconds(-62167219200).?.toStringMillis());
    try testing.expect(fromSeconds(-62167219201) == null);
    try testing.expectEqualStrings("9999-12-31T23:59:59.999Z", &fromMillis(253402300799999).?.toStringMillis());
    try testing.expect(fromMillis(253402300800000) == null);
    try testing.expect(fromSeconds(std.math.minInt(i64)) == null);
    try testing.expect(fromSeconds(std.math.maxInt(i64)) == null);
    try testing.expectEqual(parse("2024-02-29T12:00:00Z").?.micros, fromSeconds(1709208000).?.micros);
}