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

change []const u32 to []const u8 #1

Closed
wants to merge 1 commit into from

Conversation

vkensou
Copy link

@vkensou vkensou commented Feb 12, 2025

In Zig, []const u8 is more commonly used. And converting from []const u8 to []const u32 is not safe.

@MasonRemaley
Copy link
Contributor

MasonRemaley commented Feb 12, 2025

Thanks for the PR!

You are correct that slices of u8s are very common in zig since they're a convenient representation of strings, but the data here is not a string--it's a sequence of SPIRV instructions.

SPIRV instructions are u32 sized, and must have u32 alignment. Taking a slice of u32s here prevents passing in misaligned data, or data whose size in bytes is not a multiple of u32.

It's not uncommon to see C APIs that treat SPIRV as an array of bytes, but this isn't really a great practice it's just that in C/C++ it’s not as common to use explicitly sized integers so the APIs are often a little less type safe.

If you do end up with a slice of u8s (from a C API for example or from loading bytes from a file), you will have to cast it, and you're correct that this is unsafe if it turns out the size or alignment are incorrect--but that's a good thing as it means Zig can check this for you, otherwise you’ll silently be passing in incorrect data. Once this is merged you'll be able to just use ptrCast + alignCast on the slice of bytes which will be much more convenient.

If you’re loading from a file, make sure to load into u32 aligned memory so that the instructions are properly aligned, in this case you won’t need the alignCast. This is also important if you end up passing the SPIRV to an API like Vulkan.

@vkensou
Copy link
Author

vkensou commented Feb 13, 2025

ziglang/zig#4680 (comment)

this worked

const imgui_vert_shader_aligned align(@sizeOf(usize)) = @embedFile("imgui.vert.spv").*;
const imgui_vert_shader = &imgui_vert_shader_aligned;

@MasonRemaley
Copy link
Contributor

Nice, glad you got it working!

FYI you can use @alignOf(u32) instead of @alignOf(usize) to get the alignment of u32 explicitly.

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

Successfully merging this pull request may close these issues.

2 participants