gpu: begin switching from enum(usize) to opaque pointers
WebGPU objects, like say `WGPUTexture`, could be represented in one of two ways:
1. As an `enum(usize)` as we were doing previously
2. As an `*opaque` pointer
In `webgpu.h` natively, `void*` opaque pointers are used. However, WebGPU objects are not
actually pointers: they are just IDs. A concrete example of this is how it is almost always
valid to for example pass a `WGPUTexture` that has been freed into the API. Doing so does
not result in undefined behavior, instead the implementation considers the texture to be an
ID and since it can't find such an ID it knows that texture has been free'd and to generate
an error instead of undefined behavior. In this regard, we can say that `enum(usize)` is the
more faithful representation.
`enum(usize)` is not without issues, though: it cannot effectively represent nullability in
Zig, which is used in the `webgpu.h` C ABI to represent _optionality_. `?enum(usize)` is not
a valid exported C type, the Zig compiler rejects it. And so in practice to maintain C ABI
compatability with descriptor struct types (which we do not want to copy or bitcast), we must
represent nullability with a `null` value:
```zig
pub const Texture = enum(usize) {
_,
pub const null: Texture = @intToEnum(Texture, 0);
pub const Descriptor = extern struct {
next_in_chain: *const ChainedStruct,
};
pub fn init() Texture {
return Texture.null;
}
};
```
The downside to this is that `init` cannot return a clear optional `?Texture`, and instead
must return a `Texture` which may be `== .null`. This downside seems significant enough to
warrant _not_ going with `enum(usize)` and instead going with `*opaque`:
```zig
pub const Texture = *opaque {
pub fn init() ?Texture { return null }
};
pub const TextureDescriptor = extern struct {
next_in_chain: *const ChainedStruct,
};
```
The downside to `*opaque` is that the namespace cannot have types nested below it.
`gpu.Texture.Descriptor` becomes `gpu.TextureDescriptor`.
Not ideal, but a tradeoff we'll accept to be able to represent optionality with the actual
Zig type system.
Signed-off-by: Stephen Gutekanst <stephen@hexops.com>
This commit is contained in:
parent
7f6cb8b511
commit
5741082848
3 changed files with 9 additions and 13 deletions
|
|
@ -1,12 +1,7 @@
|
|||
const ChainedStruct = @import("types.zig").ChainedStruct;
|
||||
|
||||
pub const Instance = enum(usize) {
|
||||
_,
|
||||
pub const Instance = *opaque {};
|
||||
|
||||
// TODO: verify there is a use case for nullable value of this type.
|
||||
pub const none: Instance = @intToEnum(Instance, 0);
|
||||
|
||||
pub const Descriptor = extern struct {
|
||||
next_in_chain: *const ChainedStruct,
|
||||
};
|
||||
pub const InstanceDescriptor = extern struct {
|
||||
next_in_chain: *const ChainedStruct,
|
||||
};
|
||||
|
|
|
|||
Loading…
Add table
Add a link
Reference in a new issue