- Notifications
You must be signed in to change notification settings - Fork14
Dynamic dispatch for zig made easy
License
NotificationsYou must be signed in to change notification settings
alexnask/interface.zig
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Easy solution for all your zig dynamic dispatch needs!
- Fully decoupled interfaces and implementations
- Control over the storage/ownership of interface objects
- Comptime support (including comptime-only interfaces)
- Async function partial support (blocking on#4621)
- Optional function support
- Support for manually written vtables
constinterface=@import("interface.zig");constInterface=interface.Interface;constSelfType=interface.SelfType;// Let us create a Reader interface.// We wrap it in our own struct to make function calls more natural.constReader=struct {pubconstReadError=error {CouldNotRead };constIFace=Interface(struct {// Our interface requires a single non optional, non-const read function.read:fn (*SelfType,buf: []u8)ReadError!usize, },interface.Storage.NonOwning);// This is a non owning interface, similar to Rust dyn traits.iface:IFace,// Wrap the interface's init, since the interface is non owning it requires no allocator argument.pubfninit(impl_ptr:var)Reader {return .{ .iface=tryIFace.init(.{impl_ptr}) }; }// Wrap the read function callpubfnread(self:*Reader,buf: []u8)ReadError!usize {returnself.iface.call("read", .{buf}); }// Define additional, non-dynamic functions!pubfnreadAll(self:*Self,buf: []u8)ReadError!usize {varindex:usize=0;while (index!=buf.len) {constpartial_amt=tryself.read(buffer[index..]);if (partial_amt==0)returnindex;index+=partial_amt; }returnindex; }};// Let's create an example readerconstExampleReader=struct {state:u8,// Note that this reader cannot return an error, the return type// of our implementation functions only needs to coerce to the// interface's function return type.pubfnread(self:ExampleReader,buf: []u8)usize {for (buf)|*c| {c.*=self.state; }returnbuf.len; }};test"Use our reader interface!" {varexample_reader=ExampleReader{ .state=42 };varreader=Reader.init(&example_reader);varbuf: [100]u8=undefined;_=reader.read(&buf)catchunreachable;}
See examples.zig for more examples.
About
Dynamic dispatch for zig made easy
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.
Stars
Watchers
Forks
Releases
No releases published
Packages0
No packages published