Something went wrong. Try again.
A Microsoft 365 mail client library for Zig, over Microsoft Graph
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie <jeff@ocjtech.us>// SPDX-License-Identifier: MIT
//! The timestamps Microsoft Graph writes, in and out.//!//! Every instant in a Graph mail response is an ISO 8601 string --//! `"2018-09-09T03:15:05Z"` -- rather than the epoch count Gmail sends, so a//! client that wants to sort a mailbox or ask for everything since Tuesday has//! to read and write them. Both directions are needed: reading, for//! `receivedDateTime` on a message, and writing, for the//! `$filter=receivedDateTime ge <value>` that is the only filter a delta query//! accepts.//!//! `std.time.epoch` is no help in either direction. It only decodes -- it turns//! a second count into a date and has nothing going the other way -- so what is//! here is Howard Hinnant's `days_from_civil` and `civil_from_days`, which are//! about fifteen lines each and exact over the whole proleptic Gregorian//! calendar.//!//! ## What is accepted//!//! `YYYY-MM-DDTHH:MM:SS`, then optionally a fraction of a second, then//! optionally a zone: `Z`, or `+HH:MM` / `-HH:MM`. Graph sends UTC with a `Z`//! and seven fractional digits at most, but an offset is legal ISO 8601 and//! accepting one costs a dozen lines.//!//! A string that is not one of those reads as `null` rather than as an error,//! for the reason every parser in this library is lenient: a mailbox walk that//! stops on one odd message has to be understood before it can be resumed, and//! a message with an unreadable date is still a message.//!//! The one thing that is *not* lenient is the range check, and the order of it.//! A month field is validated as a `u32` and narrowed afterwards, never the//! other way around: `@intCast` into a `u4` is a panic rather than an error, so//! a parser that narrows `99` first crashes instead of rejecting it.
const std = @import("std");
/// Seconds from the Unix epoch to the civil date and time given, with no zone/// applied. Split out from `parse` because it is also what `render` inverts,/// and because it is the part worth testing against known dates.pub fn secondsFromCivil( year: i64, month: u32, day: u32, hour: u32, minute: u32, second: u32,) i64 { const days = daysFromCivil(year, month, day); return days * std.time.s_per_day + @as(i64, hour) * std.time.s_per_hour + @as(i64, minute) * std.time.s_per_min + @as(i64, second);}
/// Howard Hinnant's `days_from_civil`: days since 1970-01-01 for a proleptic/// Gregorian date. Exact for every year this can be handed.////// `month` is 1-12 and `day` is 1-31; a date outside those is not rejected/// here but simply lands somewhere else on the line, which is why `parse`/// checks the ranges before calling it.pub fn daysFromCivil(year: i64, month: u32, day: u32) i64 { const m: i64 = @intCast(month); // March is treated as the first month, which is what puts the leap day at // the end of the year and makes the rest of this arithmetic exact. const y = year - @as(i64, if (m <= 2) 1 else 0); // Floor division rather than truncating: Hinnant writes `(y >= 0 ? y : y - // 399) / 400` for languages that truncate, and this is the same thing said // directly. const era = @divFloor(y, 400); const yoe = y - era * 400; // [0, 399] const doy = @divTrunc(153 * (m + (if (m > 2) @as(i64, -3) else 9)) + 2, 5) + @as(i64, @intCast(day)) - 1; // [0, 365] const doe = yoe * 365 + @divTrunc(yoe, 4) - @divTrunc(yoe, 100) + doy; // [0, 146096] // 719468 is the number of days from 0000-03-01 to 1970-01-01. return era * 146097 + doe - 719468;}
pub const Civil = struct { year: i64, month: u32, day: u32,};
/// Hinnant's `civil_from_days`, the inverse of the above.pub fn civilFromDays(days: i64) Civil { const z = days + 719468; const era = @divFloor(z, 146097); const doe = z - era * 146097; // [0, 146096] const yoe = @divTrunc( doe - @divTrunc(doe, 1460) + @divTrunc(doe, 36524) - @divTrunc(doe, 146096), 365, ); // [0, 399] const y = yoe + era * 400; const doy = doe - (365 * yoe + @divTrunc(yoe, 4) - @divTrunc(yoe, 100)); // [0, 365] const mp = @divTrunc(5 * doy + 2, 153); // [0, 11] const d = doy - @divTrunc(153 * mp + 2, 5) + 1; // [1, 31] const m = mp + (if (mp < 10) @as(i64, 3) else -9); // [1, 12] return .{ .year = y + @as(i64, if (m <= 2) 1 else 0), .month = @intCast(m), .day = @intCast(d), };}
/// Reads a Graph timestamp. `null` for anything that is not one.////// The result is a `std.Io.Timestamp`, which is nanoseconds in an `i96`, so/// the sub-second part Graph sends survives rather than being rounded away.pub fn parse(text: []const u8) ?std.Io.Timestamp { // `YYYY-MM-DDTHH:MM:SS` is nineteen characters, and nothing shorter can be // a timestamp. Checking it once here is what lets the field reads below be // plain slices. if (text.len < 19) return null;
// A four-digit year, which is what Graph sends and what keeps every // multiplication below inside an i64 by construction: the widest year // reachable is 9999, and `era * 146097` for that is nowhere near the edge. const year = digits(i64, text[0..4]) orelse return null; if (text[4] != '-') return null; const month = digits(u32, text[5..7]) orelse return null; if (text[7] != '-') return null; const day = digits(u32, text[8..10]) orelse return null; // Graph writes `T`; ISO 8601 also permits a space, and some proxies // rewrite it. if (text[10] != 'T' and text[10] != 't' and text[10] != ' ') return null; const hour = digits(u32, text[11..13]) orelse return null; if (text[13] != ':') return null; const minute = digits(u32, text[14..16]) orelse return null; if (text[16] != ':') return null; const second = digits(u32, text[17..19]) orelse return null;
// Validated as the wide type, and narrowed nowhere: `@intCast` into a // four-bit month is a panic rather than an error, so a check that comes // after the narrowing is a check that never runs. if (month < 1 or month > 12) return null; if (day < 1 or day > daysInMonth(year, month)) return null; if (hour > 23 or minute > 59) return null; // 60 is a leap second, which is legal and which the arithmetic below // carries into the next minute on its own. if (second > 60) return null;
var rest = text[19..];
// An optional fraction of a second. Graph sends up to seven digits; // anything past nanosecond resolution is read and dropped, because there // is nowhere finer to put it. var subsecond_ns: i96 = 0; if (rest.len > 0 and (rest[0] == '.' or rest[0] == ',')) { rest = rest[1..]; var taken: usize = 0; var scale: i96 = 100_000_000; // the first digit is tenths of a second while (taken < rest.len and rest[taken] >= '0' and rest[taken] <= '9') : (taken += 1) { if (scale > 0) { subsecond_ns += @as(i96, rest[taken] - '0') * scale; scale = @divTrunc(scale, 10); } } // A lone `.` with no digit after it is not a fraction. if (taken == 0) return null; rest = rest[taken..]; }
// And an optional zone. No zone at all means UTC here, which is a choice: // ISO 8601 says such a string is local time, and there is no local time in // a mail store that several machines read. var offset_s: i64 = 0; if (rest.len > 0) { switch (rest[0]) { 'Z', 'z' => if (rest.len != 1) return null, '+', '-' => { const sign: i64 = if (rest[0] == '-') -1 else 1; const body = rest[1..]; // `+HH:MM` and `+HHMM` are both written in the wild. const oh, const om = switch (body.len) { 5 => if (body[2] == ':') .{ digits(i64, body[0..2]), digits(i64, body[3..5]) } else return null, 4 => .{ digits(i64, body[0..2]), digits(i64, body[2..4]) }, 2 => .{ digits(i64, body[0..2]), @as(?i64, 0) }, else => return null, }; const offset_hours = oh orelse return null; const offset_minutes = om orelse return null; if (offset_hours > 23 or offset_minutes > 59) return null; offset_s = sign * (offset_hours * std.time.s_per_hour + offset_minutes * std.time.s_per_min); }, else => return null, } }
const seconds = secondsFromCivil(year, month, day, hour, minute, second) - offset_s; return .fromNanoseconds(@as(i96, seconds) * std.time.ns_per_s + subsecond_ns);}
/// Writes `YYYY-MM-DDTHH:MM:SSZ`, which is the spelling a `$filter` on/// `receivedDateTime` wants.////// Whole seconds, deliberately: the fraction is not needed for a filter/// bound, and a `$filter` value Graph cannot read is a 400 rather than a/// misordered page.pub fn render(timestamp: std.Io.Timestamp, w: *std.Io.Writer) std.Io.Writer.Error!void { // Floor, not truncate. An instant before 1970 with a fraction belongs to // the second below it, and truncating would round it towards the epoch and // put it in the wrong second. const total_s: i64 = @intCast(@divFloor(timestamp.nanoseconds, std.time.ns_per_s)); const days = @divFloor(total_s, std.time.s_per_day); const rem = total_s - days * std.time.s_per_day; // [0, 86399]
const civil = civilFromDays(days);
// Every field is widened to an unsigned type before it is printed. // `{d:0>2}` on a *signed* integer does not zero-pad -- it writes a sign, // so an hour of 3 comes out as `+3` and the whole timestamp is something // Graph answers with a 400. // // The year is saturated into the four digits the format has room for. // Nothing in a mailbox reaches either end of that, and the alternative -- // ISO 8601's signed expanded years -- is not a spelling Graph accepts, so // there would be nothing useful to write instead. const year: u64 = @intCast(std.math.clamp(civil.year, 0, 9999)); try w.print("{d:0>4}-{d:0>2}-{d:0>2}T{d:0>2}:{d:0>2}:{d:0>2}Z", .{ year, @as(u64, civil.month), @as(u64, civil.day), @as(u64, @intCast(@divTrunc(rem, std.time.s_per_hour))), @as(u64, @intCast(@divTrunc(@mod(rem, std.time.s_per_hour), std.time.s_per_min))), @as(u64, @intCast(@mod(rem, std.time.s_per_min))), });}
/// `render` into caller-owned scratch space. Twenty bytes is the whole of a/// `YYYY-MM-DDTHH:MM:SSZ`, and every caller passes at least that.pub fn bufRender(buf: []u8, timestamp: std.Io.Timestamp) []const u8 { var w: std.Io.Writer = .fixed(buf); render(timestamp, &w) catch return ""; return w.buffered();}
/// Exactly `text.len` decimal digits and nothing else. `null` for a field/// with a sign, a space or a letter in it, which is what keeps/// `std.fmt.parseInt`'s tolerance of `+` and `_` out of a fixed-width field.fn digits(comptime T: type, text: []const u8) ?T { var value: T = 0; for (text) |c| { if (c < '0' or c > '9') return null; value = value * 10 + (c - '0'); } return value;}
fn isLeapYear(year: i64) bool { return @mod(year, 4) == 0 and (@mod(year, 100) != 0 or @mod(year, 400) == 0);}
fn daysInMonth(year: i64, month: u32) u32 { return switch (month) { 1, 3, 5, 7, 8, 10, 12 => 31, 4, 6, 9, 11 => 30, 2 => if (isLeapYear(year)) 29 else 28, else => 0, };}
const testing = std.testing;
fn expectSeconds(expected: i64, text: []const u8) !void { const got = parse(text) orelse return error.NotATimestamp; try testing.expectEqual(@as(i96, expected) * std.time.ns_per_s, got.nanoseconds);}
test "the shape Graph actually sends" { // The example from the message resource reference. try expectSeconds(1536462905, "2018-09-09T03:15:05Z"); try expectSeconds(0, "1970-01-01T00:00:00Z"); try expectSeconds(1700000000, "2023-11-14T22:13:20Z");}
test "a fraction of a second survives" { // Graph writes up to seven digits; nanoseconds hold nine. const got = parse("2018-09-09T03:15:05.1234567Z").?; try testing.expectEqual( @as(i96, 1536462905) * std.time.ns_per_s + 123456700, got.nanoseconds, );
// And anything past nanoseconds is dropped rather than rejected. const finer = parse("2018-09-09T03:15:05.123456789123Z").?; try testing.expectEqual( @as(i96, 1536462905) * std.time.ns_per_s + 123456789, finer.nanoseconds, );}
test "an offset moves the instant, and the sign is the right way round" { // 03:15:05 at +02:00 is 01:15:05 UTC: an eastward offset is *earlier* in // UTC, which is the direction it is easiest to get backwards. try expectSeconds(1536462905 - 2 * 3600, "2018-09-09T03:15:05+02:00"); try expectSeconds(1536462905 + 5 * 3600, "2018-09-09T03:15:05-05:00"); try expectSeconds(1536462905 - 2 * 3600, "2018-09-09T03:15:05+0200"); try expectSeconds(1536462905 - 2 * 3600, "2018-09-09T03:15:05+02"); // No zone is read as UTC. try expectSeconds(1536462905, "2018-09-09T03:15:05");}
test "dates before the epoch" { // A `Date:` header claiming 1900 is one a real message has, and Graph // will carry it into `sentDateTime`. try expectSeconds(-2208988800, "1900-01-01T00:00:00Z"); try expectSeconds(-1, "1969-12-31T23:59:59Z");}
test "a leap day is a day and a non-leap one is not" { try expectSeconds(951782400, "2000-02-29T00:00:00Z"); // 1900 is divisible by 4 and by 100 and not by 400, so it had no 29th. try testing.expectEqual(@as(?std.Io.Timestamp, null), parse("1900-02-29T00:00:00Z")); try testing.expectEqual(@as(?std.Io.Timestamp, null), parse("2023-02-29T00:00:00Z")); try expectSeconds(1709164800, "2024-02-29T00:00:00Z");}
test "a field out of range is rejected rather than narrowed" { // The whole reason the range check comes before any cast: `@intCast` into // a four-bit month would panic on these rather than return null. for ([_][]const u8{ "2018-99-09T03:15:05Z", "2018-00-09T03:15:05Z", "2018-09-32T03:15:05Z", "2018-09-00T03:15:05Z", "2018-09-09T25:15:05Z", "2018-09-09T03:99:05Z", "2018-09-09T03:15:99Z", "2018-09-31T03:15:05Z", }) |text| { try testing.expectEqual(@as(?std.Io.Timestamp, null), parse(text)); }}
test "a leap second is accepted and lands in the next minute" { try expectSeconds( // 2016-12-31T23:59:60Z is the instant 2017 begins. 1483228800, "2016-12-31T23:59:60Z", );}
test "things that are not timestamps" { for ([_][]const u8{ "", "2018-09-09", "not a date at all", "2018/09/09T03:15:05Z", "2018-09-09X03:15:05Z", "2018-09-09T03:15:05ZZ", "2018-09-09T03:15:05+2:00", "2018-09-09T03:15:05.Z", "2018-09-09T03:15:05+99:00", // A sign inside a fixed-width field, which `parseInt` would have // taken. "+018-09-09T03:15:05Z", "2018-+9-09T03:15:05Z", // Unicode digits are not digits. "٢٠١٨-09-09T03:15:05Z", }) |text| { try testing.expectEqual(@as(?std.Io.Timestamp, null), parse(text)); }}
test "render is the inverse of parse" { for ([_][]const u8{ "2018-09-09T03:15:05Z", "1970-01-01T00:00:00Z", "1900-01-01T00:00:00Z", "2000-02-29T23:59:59Z", "2024-12-31T00:00:01Z", "9999-12-31T23:59:59Z", }) |text| { const parsed = parse(text) orelse return error.NotATimestamp; var buf: [32]u8 = undefined; try testing.expectEqualStrings(text, bufRender(&buf, parsed)); }}
test "render floors rather than truncating towards the epoch" { // Half a second after 1969-12-31T23:59:59 belongs to that second, not to // the one after it. Truncating division would round towards zero and // print `1970-01-01T00:00:00Z`. const ts: std.Io.Timestamp = .fromNanoseconds(-500 * std.time.ns_per_ms); var buf: [32]u8 = undefined; try testing.expectEqualStrings("1969-12-31T23:59:59Z", bufRender(&buf, ts));}
test "the calendar round trips over four centuries" { // Every day from 1800 to 2200, which covers all three leap year rules in // both directions. var day = daysFromCivil(1800, 1, 1); const end = daysFromCivil(2200, 1, 1); while (day < end) : (day += 1) { const civil = civilFromDays(day); try testing.expectEqual(day, daysFromCivil(civil.year, civil.month, civil.day)); try testing.expect(civil.month >= 1 and civil.month <= 12); try testing.expect(civil.day >= 1 and civil.day <= 31); }}