// SPDX-FileCopyrightText: © 2026 Jeffrey C. Ollie // SPDX-License-Identifier: MIT //! Reading members out of a `std.json.Value` without failing on the ones that //! are not there. //! //! Every resource here is parsed this way rather than by mapping a Zig struct //! onto the JSON, and the reason is what a Gmail response actually looks like. //! Fields are omitted when they are empty rather than sent as `null`, and //! Google adds new ones without warning, so `std.json.parseFromSlice` into a //! struct fails on a live mailbox in two different ways -- `MissingField` for //! the omissions and `UnknownField` for the additions. A client that walks a //! mailbox cannot afford either. //! //! The other reason is `numberAsString`. Anything that does not fit a double //! is sent as a *string* of digits, so `historyId` and `internalDate` arrive //! quoted and a struct field of `u64` or `i64` will not take them. const std = @import("std"); pub fn object(value: std.json.Value, name: []const u8) ?std.json.Value { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .object => member, else => null, }; } pub fn array(value: std.json.Value, name: []const u8) ?[]const std.json.Value { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .array => |a| a.items, else => null, }; } pub fn string(value: std.json.Value, name: []const u8) ?[]const u8 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .string => |s| s, else => null, }; } /// A string with at least one byte in it. Gmail sends `""` where it means /// "none" often enough that the distinction is worth having: an empty /// `nextPageToken` means the walk is over, and asking for the next page with /// it would start again from the beginning. pub fn nonEmptyString(value: std.json.Value, name: []const u8) ?[]const u8 { const s = string(value, name) orelse return null; return if (s.len == 0) null else s; } pub fn unsigned(value: std.json.Value, name: []const u8) ?u32 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .integer => |i| std.math.cast(u32, i), // `numberAsString` for something that fits a u32 would be unusual, // but costs nothing to accept. .string => |s| std.fmt.parseInt(u32, s, 10) catch null, else => null, }; } /// A 64-bit count that Gmail sends as a quoted decimal string, which is what /// the reference means by "string (uint64 format)": `historyId`, and the /// `startHistoryId` that goes back the other way. /// /// The `.integer` case is not the API's doing but a test's or a proxy's, and /// accepting it costs one branch. pub fn unsigned64(value: std.json.Value, name: []const u8) ?u64 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .string => |s| std.fmt.parseInt(u64, s, 10) catch null, .integer => |i| std.math.cast(u64, i), .number_string => |s| std.fmt.parseInt(u64, s, 10) catch null, else => null, }; } /// The same, signed: `internalDate`, which is milliseconds since the Unix /// epoch and so is an `i64` rather than a `u64` -- a message can predate 1970 /// if its `Date:` header says so, and Gmail believes the header. pub fn signed64(value: std.json.Value, name: []const u8) ?i64 { if (value != .object) return null; const member = value.object.get(name) orelse return null; return switch (member) { .string => |s| std.fmt.parseInt(i64, s, 10) catch null, .integer => |i| i, .number_string => |s| std.fmt.parseInt(i64, s, 10) catch null, else => null, }; } /// Decodes a `bytes format` member: base64url, which Gmail sends without /// padding for `raw` and with it for an attachment body, so both are accepted. /// The result is owned by `alloc`. pub fn base64Url( alloc: std.mem.Allocator, value: std.json.Value, name: []const u8, ) std.mem.Allocator.Error!?[]u8 { const encoded = string(value, name) orelse return null; return decodeBase64Url(alloc, encoded) catch |err| switch (err) { error.OutOfMemory => return error.OutOfMemory, // Undecodable content is not worth failing the whole message over; // the caller sees a message with no body rather than no message. error.InvalidBase64 => null, }; } pub fn decodeBase64Url( alloc: std.mem.Allocator, encoded: []const u8, ) (std.mem.Allocator.Error || error{InvalidBase64})![]u8 { const decoder = if (std.mem.endsWith(u8, encoded, "=")) std.base64.url_safe.Decoder else std.base64.url_safe_no_pad.Decoder; const size = decoder.calcSizeForSlice(encoded) catch return error.InvalidBase64; const out = try alloc.alloc(u8, size); errdefer alloc.free(out); decoder.decode(out, encoded) catch return error.InvalidBase64; return out; } const testing = std.testing; fn parse(text: []const u8) !std.json.Parsed(std.json.Value) { return std.json.parseFromSlice(std.json.Value, testing.allocator, text, .{}); } test "a missing member is null, not an error" { var p = try parse("{}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), string(p.value, "nope")); try testing.expectEqual(@as(?u32, null), unsigned(p.value, "nope")); try testing.expectEqual(@as(?u64, null), unsigned64(p.value, "nope")); try testing.expectEqual(@as(?i64, null), signed64(p.value, "nope")); try testing.expectEqual(@as(?[]const std.json.Value, null), array(p.value, "nope")); try testing.expectEqual(@as(?std.json.Value, null), object(p.value, "nope")); } test "a member of the wrong type is null, not an error" { var p = try parse("{\"a\":[],\"b\":{},\"c\":\"x\",\"d\":true}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), string(p.value, "a")); try testing.expectEqual(@as(?u32, null), unsigned(p.value, "d")); try testing.expectEqual(@as(?std.json.Value, null), object(p.value, "a")); try testing.expectEqual(@as(?[]const std.json.Value, null), array(p.value, "b")); } test "the 64-bit counts arrive quoted" { var p = try parse( \\{"historyId":"18446744073709551615","internalDate":"-2208988800000", \\ "small":"7","sizeEstimate":4096} ); defer p.deinit(); try testing.expectEqual(@as(?u64, std.math.maxInt(u64)), unsigned64(p.value, "historyId")); // 1900-01-01, which is a `Date:` header a real message has. try testing.expectEqual(@as(?i64, -2208988800000), signed64(p.value, "internalDate")); try testing.expectEqual(@as(?u32, 7), unsigned(p.value, "small")); try testing.expectEqual(@as(?u32, 4096), unsigned(p.value, "sizeEstimate")); } test "a 64-bit count that is not a number is null" { var p = try parse("{\"a\":\"twelve\",\"b\":\"\",\"c\":\"-1\"}"); defer p.deinit(); try testing.expectEqual(@as(?u64, null), unsigned64(p.value, "a")); try testing.expectEqual(@as(?u64, null), unsigned64(p.value, "b")); try testing.expectEqual(@as(?u64, null), unsigned64(p.value, "c")); try testing.expectEqual(@as(?i64, -1), signed64(p.value, "c")); } test "an empty string is not a token" { var p = try parse("{\"nextPageToken\":\"\",\"other\":\"x\"}"); defer p.deinit(); try testing.expectEqual(@as(?[]const u8, null), nonEmptyString(p.value, "nextPageToken")); try testing.expectEqualStrings("x", nonEmptyString(p.value, "other").?); } test "base64url, padded and not" { // "hello world" in both spellings. for ([_][]const u8{ "aGVsbG8gd29ybGQ", "aGVsbG8gd29ybGQ=" }) |encoded| { const out = try decodeBase64Url(testing.allocator, encoded); defer testing.allocator.free(out); try testing.expectEqualStrings("hello world", out); } } test "base64url that is not base64url" { try testing.expectError( error.InvalidBase64, decodeBase64Url(testing.allocator, "not base64!"), ); // The `+/` alphabet is the other base64, and Gmail does not send it. try testing.expectError( error.InvalidBase64, decodeBase64Url(testing.allocator, "a+b/c"), ); } test "an undecodable body yields no body rather than an error" { var p = try parse("{\"raw\":\"!!!not base64!!!\"}"); defer p.deinit(); try testing.expectEqual(@as(?[]u8, null), try base64Url(testing.allocator, p.value, "raw")); }