跳转到内容
标准库Zig 0.17.0官方原文
源码std/tz.zig

第 1 行

时区信息格式(TZif) https://datatracker.ietf.org/doc/html/rfc8536

std.tz.Allocator

别名

第 8 行

别名目标 std.mem.Allocator

std.tz.builtin

常量

第 4 行

std.tz.Leapsecond

容器

第 37 行

字段

occurrence: i48
correction: i16

std.tz.Reader

别名

第 7 行

别名目标 std.Io.Reader

std.tz.std

别名

第 6 行

别名目标 std

std.tz.Timetype

容器

第 15 行

字段

offset: i32
flags: u8
name_data: [6:0]u8

std.tz.Timetype.isDst

函数

第 24 行

pub fn isDst(self: Timetype) bool

参数

self: Timetype

std.tz.Timetype.name

函数

第 20 行

pub fn name(self: *const Timetype) [:0]const u8

参数

self: *const Timetype

std.tz.Timetype.standardTimeIndicator

函数

第 28 行

pub fn standardTimeIndicator(self: Timetype) bool

参数

self: Timetype

std.tz.Timetype.utIndicator

函数

第 32 行

pub fn utIndicator(self: Timetype) bool

参数

self: Timetype

std.tz.Transition

容器

第 10 行

字段

ts: i64
timetype: *Timetype

std.tz.Tz

容器

第 42 行

字段

allocator: Allocator
transitions: []const Transition
timetypes: []const Timetype
leapseconds: []const Leapsecond
footer: ?[]const u8

std.tz.Tz.deinit

函数

第 207 行

pub fn deinit(self: *Tz) void

参数

self: *Tz

std.tz.Tz.Header

容器

第 49 行

字段

magic: [4]u8
version: u8
reserved: [15]u8
counts: extern struct {
    isutcnt: u32,
    isstdcnt: u32,
    leapcnt: u32,
    timecnt: u32,
    typecnt: u32,
    charcnt: u32,
}

std.tz.Tz.parse

函数

第 63 行

pub fn parse(allocator: Allocator, reader: *Reader) !Tz

参数

allocator: Allocator
reader: *Reader

std.tz.Tz.parseBlock

函数

第 86 行

fn parseBlock(allocator: Allocator, reader: *Reader, header: Header, legacy: bool) !Tz

参数

allocator: Allocator
reader: *Reader
header: Header
legacy: bool
源码

std/tz.zig

//! 时区信息格式(TZif)
//! https://datatracker.ietf.org/doc/html/rfc8536

const builtin = @import("builtin");

const std = @import("std.zig");
const Reader = std.Io.Reader;
const Allocator = std.mem.Allocator;

pub const Transition = struct {
    ts: i64,
    timetype: *Timetype,
};

pub const Timetype = struct {
    offset: i32,
    flags: u8,
    name_data: [6:0]u8,

    pub fn name(self: *const Timetype) [:0]const u8 {
        return std.mem.sliceTo(self.name_data[0..], 0);
    }

    pub fn isDst(self: Timetype) bool {
        return (self.flags & 0x01) > 0;
    }

    pub fn standardTimeIndicator(self: Timetype) bool {
        return (self.flags & 0x02) > 0;
    }

    pub fn utIndicator(self: Timetype) bool {
        return (self.flags & 0x04) > 0;
    }
};

pub const Leapsecond = struct {
    occurrence: i48,
    correction: i16,
};

pub const Tz = struct {
    allocator: Allocator,
    transitions: []const Transition,
    timetypes: []const Timetype,
    leapseconds: []const Leapsecond,
    footer: ?[]const u8,

    const Header = extern struct {
        magic: [4]u8,
        version: u8,
        reserved: [15]u8,
        counts: extern struct {
            isutcnt: u32,
            isstdcnt: u32,
            leapcnt: u32,
            timecnt: u32,
            typecnt: u32,
            charcnt: u32,
        },
    };

    pub fn parse(allocator: Allocator, reader: *Reader) !Tz {
        const legacy_header = try reader.takeStruct(Header, .big);
        if (!std.mem.eql(u8, &legacy_header.magic, "TZif")) return error.BadHeader;
        if (legacy_header.version != 0 and legacy_header.version != '2' and legacy_header.version != '3')
            return error.BadVersion;

        if (legacy_header.version == 0)
            return parseBlock(allocator, reader, legacy_header, true);

        // 若为现代格式,直接跳过旧版数据。
        const skip_n = legacy_header.counts.timecnt * 5 +
            legacy_header.counts.typecnt * 6 +
            legacy_header.counts.charcnt + legacy_header.counts.leapcnt * 8 +
            legacy_header.counts.isstdcnt + legacy_header.counts.isutcnt;
        try reader.discardAll(skip_n);

        var header = try reader.takeStruct(Header, .big);
        if (!std.mem.eql(u8, &header.magic, "TZif")) return error.BadHeader;
        if (header.version != '2' and header.version != '3') return error.BadVersion;

        return parseBlock(allocator, reader, header, false);
    }

    fn parseBlock(allocator: Allocator, reader: *Reader, header: Header, legacy: bool) !Tz {
        if (header.counts.isstdcnt != 0 and header.counts.isstdcnt != header.counts.typecnt) return error.Malformed; // rfc8536:isstdcnt […] 必须为零或等于 "typecnt"
        if (header.counts.isutcnt != 0 and header.counts.isutcnt != header.counts.typecnt) return error.Malformed; // rfc8536:isutcnt […] 必须为零或等于 "typecnt"
        if (header.counts.typecnt == 0) return error.Malformed; // rfc8536:typecnt [...] 不得为零
        if (header.counts.charcnt == 0) return error.Malformed; // rfc8536:charcnt [...] 不得为零
        if (header.counts.charcnt > 256 + 6) return error.Malformed; // rfc8536 未明确禁止此项,但它毫无意义

        var leapseconds = try allocator.alloc(Leapsecond, header.counts.leapcnt);
        errdefer allocator.free(leapseconds);
        var transitions = try allocator.alloc(Transition, header.counts.timecnt);
        errdefer allocator.free(transitions);
        var timetypes = try allocator.alloc(Timetype, header.counts.typecnt);
        errdefer allocator.free(timetypes);

        // 解析转换类型
        var i: usize = 0;
        while (i < header.counts.timecnt) : (i += 1) {
            transitions[i].ts = if (legacy) try reader.takeInt(i32, .big) else try reader.takeInt(i64, .big);
        }

        i = 0;
        while (i < header.counts.timecnt) : (i += 1) {
            const tt = try reader.takeByte();
            if (tt >= timetypes.len) return error.Malformed; // rfc8536:每个类型索引必须位于 [0, "typecnt" - 1] 范围内
            transitions[i].timetype = &timetypes[tt];
        }

        // 解析时间类型
        i = 0;
        while (i < header.counts.typecnt) : (i += 1) {
            const offset = try reader.takeInt(i32, .big);
            if (offset < -2147483648) return error.Malformed; // rfc8536:utoff [...] 必须不等于 -2**31
            const dst = try reader.takeByte();
            if (dst != 0 and dst != 1) return error.Malformed; // rfc8536:(is)dst [...] 的值必须为 0 或 1。
            const idx = try reader.takeByte();
            if (idx > header.counts.charcnt - 1) return error.Malformed; // rfc8536:(desig)idx [...] 每个索引必须位于 [0, "charcnt" - 1] 范围内
            timetypes[i] = .{
                .offset = offset,
                .flags = dst,
                .name_data = undefined,
            };

            // 暂时将 idx 缓存在 name_data 中,待读取下方指示符名称后处理。
            timetypes[i].name_data[0] = idx;
        }

        var designators_data: [256 + 6]u8 = undefined;
        try reader.readSliceAll(designators_data[0..header.counts.charcnt]);
        const designators = designators_data[0..header.counts.charcnt];
        if (designators[designators.len - 1] != 0) return error.Malformed; // rfc8536:charcnt [...] 包含末尾的 NUL (0x00) 八位字节

        // 再次遍历时间类型,设置指示符名称
        for (timetypes) |*tt| {
            const name = std.mem.sliceTo(designators[tt.name_data[0]..], 0);
            // 强制采用“SHOULD”规定的 6 字符限制,以改善结构体布局并符合 POSIX。
            if (name.len > 6) return error.Malformed; // rfc8536:时区名称应由至少三(3)个且不超过六(6)个 ASCII 字符组成。
            @memcpy(tt.name_data[0..name.len], name);
            tt.name_data[name.len] = 0;
        }

        // 解析闰秒
        i = 0;
        while (i < header.counts.leapcnt) : (i += 1) {
            const occur: i64 = if (legacy) try reader.takeInt(i32, .big) else try reader.takeInt(i64, .big);
            if (occur < 0) return error.Malformed; // rfc8536:occur [...] 必须非负
            if (i > 0 and leapseconds[i - 1].occurrence + 2419199 > occur) return error.Malformed; // rfc8536:发生 […] 每个后续值必须至少比前一个值大 2419199
            if (occur > std.math.maxInt(i48)) return error.Malformed; // 未来时间超出合理范围

            const corr = try reader.takeInt(i32, .big);
            if (i == 0 and corr != -1 and corr != 1) return error.Malformed; // rfc8536:若存在首条闰秒记录,其修正值必须为一(1)或负一(-1)
            if (i > 0 and leapseconds[i - 1].correction != corr + 1 and leapseconds[i - 1].correction != corr - 1) return error.Malformed; // rfc8536:相邻闰秒记录中的修正值必须恰好相差一(1)。
            if (corr > std.math.maxInt(i16)) return error.Malformed; // 不合理的大修正量

            leapseconds[i] = .{
                .occurrence = @as(i48, @intCast(occur)),
                .correction = @as(i16, @intCast(corr)),
            };
        }

        // 解析标准时间/墙上时间指示符
        i = 0;
        while (i < header.counts.isstdcnt) : (i += 1) {
            const stdtime = try reader.takeByte();
            if (stdtime == 1) {
                timetypes[i].flags |= 0x02;
            }
        }

        // 解析 UT/本地时间指示符
        i = 0;
        while (i < header.counts.isutcnt) : (i += 1) {
            const ut = try reader.takeByte();
            if (ut == 1) {
                timetypes[i].flags |= 0x04;
                if (!timetypes[i].standardTimeIndicator()) return error.Malformed; // rfc8536:如果 UT/local 值为一(1),则 standard/wall 值必须为一(1)。
            }
        }

        // 尾部
        var footer: ?[]u8 = null;
        if (!legacy) {
            if ((try reader.takeByte()) != '\n') return error.Malformed; // rfc8536 尾部必须以换行符开始
            const footer_mem = reader.takeSentinel('\n') catch |err| switch (err) {
                error.StreamTooLong => return error.OverlargeFooter, // 读取超过 128 字节,远大于任何合理的 POSIX TZ 字符串。
                else => return err,
            };
            if (footer_mem.len != 0) {
                footer = try allocator.dupe(u8, footer_mem);
            }
        }
        errdefer if (footer) |ft| allocator.free(ft);

        return .{
            .allocator = allocator,
            .transitions = transitions,
            .timetypes = timetypes,
            .leapseconds = leapseconds,
            .footer = footer,
        };
    }

    pub fn deinit(self: *Tz) void {
        if (self.footer) |footer| {
            self.allocator.free(footer);
        }
        self.allocator.free(self.leapseconds);
        self.allocator.free(self.transitions);
        self.allocator.free(self.timetypes);
    }
};

test "slim" {
    const data = @embedFile("tz/asia_tokyo.tzif");
    var in_stream: Reader = .fixed(data);

    var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
    defer tz.deinit();

    try std.testing.expectEqual(tz.transitions.len, 9);
    try std.testing.expect(std.mem.eql(u8, tz.transitions[3].timetype.name(), "JDT"));
    try std.testing.expectEqual(tz.transitions[5].ts, -620298000); // 1950-05-06 15:00:00 UTC
    try std.testing.expectEqual(tz.leapseconds[13].occurrence, 567993613); // 1988-01-01 00:00:00 UTC(TAI 中为 +23s;数据中为 +13,因为未存储最初的 10 秒偏移)
}

test "fat" {
    const data = @embedFile("tz/antarctica_davis.tzif");
    var in_stream: Reader = .fixed(data);

    var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
    defer tz.deinit();

    try std.testing.expectEqual(tz.transitions.len, 8);
    try std.testing.expect(std.mem.eql(u8, tz.transitions[3].timetype.name(), "+05"));
    try std.testing.expectEqual(tz.transitions[4].ts, 1268251224); // 2010-03-10 20:00:00 UTC
}

test "legacy" {
    // 取自 2001 年的 Slackware 8.0
    const data = @embedFile("tz/europe_vatican.tzif");
    var in_stream: Reader = .fixed(data);

    var tz = try std.Tz.parse(std.testing.allocator, &in_stream);
    defer tz.deinit();

    try std.testing.expectEqual(tz.transitions.len, 170);
    try std.testing.expect(std.mem.eql(u8, tz.transitions[69].timetype.name(), "CET"));
    try std.testing.expectEqual(tz.transitions[123].ts, 1414285200); // 2014-10-26 01:00:00 UTC
}