AIFeed

Zig 中的类型化索引

Translation(model translation, not the source's own text)

Zig 中的类型化索引

模式

命名整数或 Newtype Index 模式可以防止不同数组之间的索引混用。

上述示例对我来说并没有特别大的启发。Andrew 的示例没有太多展示如何在调用点强制保证安全性:任何调用者都可以调用 backingInt(以前是 @intFromEnum)来恢复一个数值索引,并将其传给错误的数组,或者用普通整数访问数组元素。而 matklad 的示例侧重于用一种简洁的方式构建树数据结构,但这与数组索引混用这一入门问题完全是不同的挑战,所以对我来说并不是一个特别有说服力的例证。

在实践中,为了充分利用这个模式,需要一个 getter 辅助函数,作为访问数组元素的常规方式。它可以是数组类型上的方法——也可以是索引类型上的方法。


        // 声明
const Elem = struct {...};
const Array = struct {
    items: []Elem,

const Index = enum(u32) { _ };

fn get(a: *Array, i: Index) *Elem {
        return &a.items[@backingInt(i)];
    }
};

// 用法
const a = Array{ .items = &.{...} };

var i: Index = @fromBackingInt(57);
_ = a.get(i);

_ = a.get(57); // 无法编译:类型错误。
_ = a[57]; // 可行,但 `Array.get` 的存在不鼓励这样做。
      

结构体数组示例

在结构体数组数据结构中,为每个切片设置一个类型化索引,而不是依赖仔细的命名,这一点尤其有价值。

考虑这个电子表格示例,其中很容易混淆索引:


        pub const Sheet = struct {
    row_height: []f32,
    col_width: []f32,
};

var s: Sheet = .{...};
var r: usize = 0; // 行索引。
var c: usize = 0; // 列索引。

// 用户修改列宽。
s.col_width[r].* = new_col_width; // bug:用列索引访问了行数据!
      

我们可以通过使用类型化索引强制进行编译时字段访问检查来防止此类 bug。


        pub const Sheet = struct {
    row_height: []f32,
    col_width: []f32,

pub const Row = enum(u32) { _ };
    pub const Column = enum(u32) { _ };

pub fn getRowHeight(s: *Sheet, r: Row) *f32 {
        return &s[@backingInt(r)];
    }

pub fn getColWidth(s: *Sheet, c: Column) *f32 {
        return &s[@backingInt(c)];
    }
};

var s: Sheet = .{ ... };
var r: Sheet.Row = @fromBackingInt(0); // 类型化行索引。
var c: Sheet.Column = @fromBackingInt(0); // 类型化列索引。

// 用户修改列宽。
const new_col_width: f32 = undefined;

s.getColWidth(r).* = new_col_width; // 编译时错误:类型错误。
s.getColWidth(c).* = new_col_width; // 正确!

s.col_width[@backingInt(r)]  // 可行,但非常刻意。

s.col_width[57]  // 可行,但 Sheet 声明
                 // 和文档给出的约定
                 // 不鼓励这样做。
      

通用方案

为每个字段维护一个索引类型和一个访问器很笨拙。我们可以用一点 comptime 来简化这个模式,让方案更通用,以适配任意结构体。下面是一个完整的示例。


        pub const Sheet = struct {
    row_height: []f32,
    row_hidden: []bool,

col_width: []f32,
    col_hidden: []bool,

title: []const u8,

pub const Field = enum {
        row_height,
        row_hidden,
        col_width,
        col_hidden,
    };

comptime {
        for (std.enums.values(Field)) |f| {
            std.debug.assert(@hasField(Sheet, @tagName(f)));
        }
    }

pub const Kind = enum { row, col };

pub fn kindOf(f: Field) Kind {
        return switch (f) {
            .row_height, .row_hidden => .row,
            .col_width, .col_hidden => .col,
        };
    }

pub fn Index(comptime k: Kind) type {
        return enum(u32) {
            _,
        };
    }

pub fn at(
        s: *Sheet,
        comptime f: Field,
        i: Index(kindOf(f)),
    ) *std.meta.Elem(@FieldType(Sheet, @tagName(f))) {
        return &@field(s, @tagName(f))[@backingInt(i)];
    }
};
      

让我们逐步分析。


        pub const Sheet = struct {
    row_height: []f32,
    row_hidden: []bool,

col_width: []f32,
    col_hidden: []bool,

title: []const u8,
};
      

我们的电子表格现在有几个字段:一个标题,以及行和列的属性。在遍历它们时,我们有两种索引:行索引和列索引。添加类型化索引很有吸引力,可以防止调用方将它们混淆。


        pub const Field = enum {
    row_height,
    row_hidden,
    col_width,
    col_hidden,
};
      

这个枚举为我们提供了一种方式来引用所有我们将为其构造类型化索引的结构体字段。如果所有字段都要被索引,我们会使用 std.meta.FieldEnum(Sheet),但我们的电子表格有一个标题。


        comptime {
    for (std.enums.values(Field)) |f| {
        std.debug.assert(@hasField(Sheet, @tagName(f)));
    }
}
      

这在编译时检查每个 Field 枚举变体的名称确实是 Sheet 中的一个字段。正如我们稍后将看到的,我们将不得不按名称访问 Sheet 的字段,因此检查 Field 变体的名称与 Sheet 字段的名称匹配是很好的。


        pub const Kind = enum { row, col };
      

这定义了我们将会构造的类型索引的种类:一个用于行数据切片,一个用于列数据切片。Sheet 的每个被索引字段都有一个正确的类型化索引种类。我们通过一个针对 Field 的穷举 switch 来匹配它们。


        pub fn kindOf(f: Field) Kind {
    return switch(f) {
        .row_height, .row_hidden => .row,
        .col_width, .col_hidden => .col,
    }
}
      

我们现在拥有构造两种类型化索引(种类为 .row 和 .col)所需的一切。一个在 comptime 返回类型的泛型函数就是实现方法。


        pub fn Index(comptime k: Kind) type {
    return enum(u32) {
        _,
    };
}
      

行的类型化索引类型是 Sheet.Index(.row),列的类型化索引类型是 Sheet.Index(.col)。注意 Index 函数的标题大小写,这符合 Zig 对类型的命名约定。

剩下的就是提供一种使用这些类型的方法。


        pub fn at(
    s: *Sheet,
    comptime f: Field,
    i: Index(kindOf(f)),
) *std.meta.Elem(@FieldType(Sheet, @tagName(f))) {
    return &@field(s, @tagName(f))[@backingInt(i)];
}
      

如果你不熟悉 Zig 中支持 comptime 的泛型,这部分可能看起来复杂,所以让我们精确说明。这在 Sheet 上定义了一个方法,要求 f 是一个在编译时已知的 Field 实例。这允许在编译时推断 i 的类型和返回类型。

Index(kindOf(f)) 只是对已知值的一系列函数调用。因此它是 comptime 已知的。最重要的是,i 的类型在编译时绑定到 f 的类型。鉴于 Sheet.kindOf 的主体,很容易看出 s.at(.row_width, i) 只有在 i 具有类型 Index(.row) 时才会编译!

Zig 函数的返回类型必须是 comptime 已知的,这里通过使用一些反射做到了这一点。@FieldType(Sheet, name) 返回 Sheet 中名为 name 的字段的类型(以 []const u8 给出)。@tagName(f) 恰好为输入枚举变体提供了这个。std.meta.Elem 返回集合类型(这里是切片)的元素类型。最后,我们返回一个指针以允许调用方修改,但对于只读情况,返回值也可以正常工作。

这为我们在调用点提供了清晰的用法。


        var s: Sheet = .{ ... };
var r: Sheet.Index(.row) = @fromBackingInt(0); // Typed row index.
var c: Sheet.Index(.col) = @fromBackingInt(0); // Typed column index.

// Several iterations later,
// the column width must be changed.

const new_col_width: f32 = 57;
s.at(.col_width, r).* = new_col_width; // comptime error: wrong type.
s.at(.col_width, c).* = new_col_width; // ok: Sheet.Index(Sheet.kindOf(.col_width)) == Sheet.Index(.col).
      

Sheet.Index(.row) 语法特别可爱:一个方法调用,感觉就像是一个限定符的具体类型。

不过,正如我先前所暗示的,这个设计并不能完全杜绝 bug。没有什么能阻止你用 @fromBackingInt 从任意整数伪造一个 Sheet.Index(.row)。而不透明类型实际上只是为了与 C 交互。

此外,任何调用者都可以直接访问 Sheet 字段(Zig 没有私有字段的概念)。


        s.at(.col_width, @fromBackingInt(@backingInt(r)))  // Possible, but very intentional.
s.col_width[@backingInt(r)]  // Possible, but very intentional.
s.col_width[57]  // Possible, but discouraged by convention given by Sheet decls and documentation.
      

对于所有 Zig 代码,都必须遵循文档化的用法(“不鼓励直接访问。请使用 Sheet.at。”),并通过主动检查类型来善用公共方法。

The translation is machine-generated and individual terms may be off. Nothing is rewritten or cut; the original is authoritative.

Published by Lobsters
This site only summarises and aggregates; copyright stays with the original author. Headlines and summaries follow the source — where they differ, the original wins.
Read the original ↗