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

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
53 lines · 1.6 KB Raw History
const std = @import("std");
const zat = @import("zat");
const Io = std.Io;

var configured_io: ?Io = null;

pub fn init(io: Io) void {
    configured_io = io;
}

fn currentIo() Io {
    return configured_io orelse std.Options.debug_io;
}

pub fn nowNanos() i96 {
    return Io.Timestamp.now(currentIo(), .real).nanoseconds;
}

/// nanoseconds on the suspend-excluding monotonic clock; for durations only
pub fn monotonicNs() u64 {
    return @intCast(@max(0, Io.Timestamp.now(currentIo(), .awake).nanoseconds));
}

pub fn nowMs() i64 {
    return @intCast(@divTrunc(nowNanos(), std.time.ns_per_ms));
}

pub fn nowSeconds() i64 {
    return @intCast(@divTrunc(nowNanos(), std.time.ns_per_s));
}

test "clock runs without init and is monotone-ish across calls" {
    const a = nowSeconds();
    const b = nowMs();
    try std.testing.expect(a > 1_700_000_000);
    try std.testing.expect(@divTrunc(b, 1000) >= a);
}

/// `seconds` as the reference PDS writes datetimes (`toISOString`: milliseconds, UTC).
pub fn isoMillis(allocator: std.mem.Allocator, seconds: i64) ![]const u8 {
    const datetime = zat.Datetime.fromSeconds(seconds) orelse return error.TimestampOutOfRange;
    return allocator.dupe(u8, &datetime.toStringMillis());
}

test "datetimes render like toISOString" {
    const a = std.testing.allocator;
    const text = try isoMillis(a, 1_700_000_000);
    defer a.free(text);
    try std.testing.expectEqualStrings("2023-11-14T22:13:20.000Z", text);
    const epoch = try isoMillis(a, 0);
    defer a.free(epoch);
    try std.testing.expectEqualStrings("1970-01-01T00:00:00.000Z", epoch);
}