Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Proposal: make std.rb more type safe #1

Open
codehz opened this issue Sep 7, 2020 · 1 comment
Open

Proposal: make std.rb more type safe #1

codehz opened this issue Sep 7, 2020 · 1 comment

Comments

@codehz
Copy link

codehz commented Sep 7, 2020

(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..

@codehz codehz changed the title Proposal: make std.rb more type safety Proposal: make std.rb more type safe Sep 7, 2020
@tadeokondrak
Copy link

std.rb is no longer in the standard library: ziglang/zig@6368519

@andrewrk andrewrk transferred this issue from ziglang/zig Sep 30, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants