3 ms·
The problem with C-style bitfield values/arbitrary-sized integers is that they don't have addresses, so you can't take references to them. This means that you n
by pcwalton 7y ago
The problem with C-style bitfield values/arbitrary-sized integers is that they don't have addresses, so you can't take references to them. This means that you need special cases everywhere, and it increases the complexity of the language a lot. In Rust, integers often have methods that take self by reference, which demands an actual address. For these reasons, in Rust I think it's better that arbitrarily-sized integers aren't first class. They're never really first class anyway.
- AndyKelley 7y agoIn Zig they do; here is an example: https://clbin.com/HlJ0X https://clbin.com/HlJ0X Output: Test [1/1] test "bit field access"... *align(:3:1) u3 All 1 tests passed. Zig's pointer type has optional metadata to describe alignment, sub-byte offset, and SIMD vector element index. This generally makes things just work, and you'll get a compile error if you expected an unadorned aligned pointer. If I were to swap: - fn deref(ptr: var) u3 { + fn deref(ptr: *u3) u3 { Then I'd get: test.zig:13:23: error: expected type '*u3', found '*align(:3:1) u3' assert(deref(&data.b) == 2); ^
- simias 7y agoHow do you deal with atomicity though? A big deal in Rust is that you can only have one mutable reference to an object at any given time which prevents all sorts of aliasing issues, but here if you have two mutable fat pointers, one to and and one to b, and you attempt to write them without synchronization you're going to have a big problem, won't you? This is the main risk with bitfields in C, it makes reads and writes that appear to be independent actually access the same memory cell behind the scenes. I'm not convinced by the idea of adding even more magic on top of it to be honest, it is true that packing and unpacking bitfields is annoying and requires some boilerplate but in the end that is how it the hardware does it anyway.
- AndyKelley 7y agoThe builtin functions for atomic operations provided by the language do not allow unaligned pointers, so it would be a compile error.