Skip to content

Proposal: make std.rb more type safe #1

Open
@codehz

Description

@codehz

(since zig has fn to generate type, we can enforce the type for the node, insteads of manually @fieldParentPtr in userland.)

I'm not mean to use something like fn Node(comptime key: type, comptime value: type) type, it is a good embed container design.

proposal version:

(the naming is not matter, focus the idea)

pub fn Node(
    comptime Data: type,
    comptime nodefield: []const u8,
) type {
	return struct {
		pub const DataType = Data;

		pub fn upCast(self: *@This()) *Data {
			return @fieldParentPtr(Data, nodefield, self);
		}

		pub fn downCast(data: *Data) *@This() {
			return &@field(data, nodefield);
		}

		// other methods not got changed
	};
}

(also change the Tree definition to accept the Node)

and the userland struct for node:

const MyData = struct {
	node1: rb.Node(@This(), "node1"),
	node2: rb.Node(@This(), "node2"),
    key: u16,
    value: []u8,
};

const Tree1 = rb.Tree(MyData, "node1");
const Tree2 = rb.Tree(MyData, "node2");

people may suddenly use wrong type or field for the fieldParentPtr since a struct can have more than one node embeded (for different containers), and different struct can have node field (it is actually happens to me), so the type safe version can help people to defense those error..

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions