You should be able to coerce, as usize should be larger than c_uint on any reasonable platform. You can do that explicitly with @as, or it'll just happen implicitly where applicable (e.g. const x: usize = my_uint_val).
If you want explicit support for some weird architectures that may or may not exist where usize is smaller than c_uint, then yes, @intCast is probably what you want - it's safety-checked UB if it underflows.
#Convert a `c_uint` to `usize`
1 messages · Page 1 of 1 (latest)
@ptrCast doesn't modify alignment of pointers - it's a compile error to do e.g. @ptrCast(*u32, x) where x: *u8. To do that, you need to do @ptrCast(*u32, @alignCast(4, x)) (although you'd normally use @alignOf(u32) rather than 4 there). @alignCast is safety-checked UB if the alignment is incorrect - i.e. in safe release modes (Debug and ReleaseSafe) it panics, in others it's UB.
So if you don't know that the alignment will be correct even in correct code, you should explicitly check it and error/panic if necessary, but I don't see that being a common case
Almost. Firstly, you just want @alignOf(u8) there, i.e. the alignment of the pointer's child type. But secondly, I believe it's guaranteed on any platform that @alignOf(u8) is 1, so you don't need an @alignCast in that instance, giving you just const buffer = @ptrCast([*]u8, data orelse @panic("null"));
no worries! :)
well, it's not necessarily guaranteed. If zig were to be ported to a platform where bytes are < 8 bits, then that would probably be @alignOf(u8) == 2. Of course that's highly unlikely, and your assertion will hold true for most reasonable architectures, but it'd do one well to not confuse a convention for a guarantee
I wasn't sure if Zig guaranteed 8-bit bytes, I guess not. Although tbf you'd prooobably only be using [*]u8 to represent an arbitrary buffer on 8-bit-byte platforms
afaik it doesn't, not on the language level, it just happens that most of the stdlib (e.g. std.mem.) assumes 8-bit bytes
Yeah that makes sense