3 ms·
C also has structs, there is no need to assemble data structures in byte arrays.
by pantalaimon 2y ago
C also has structs, there is no need to assemble data structures in byte arrays.
- pavlov 2y agoWith the caveat that structs are padded by default so that members are aligned on architecture-friendly boundaries. For example, if a struct contains a char a followed by an int b, typically b would be at offset 4, even though sizeof(a) is 1. To get tight packing, you need to explicitly tell the compiler to disable padding.
- pantalaimon 2y agoThat's why where is __attribute__((packed))
- anacrolix 2y agoFound the fresh grad
- hi-v-rocknroll 2y agoWhile under-researched statements aren't good, personal attacks don't help either. Prefer to educate instead. C structs have packing, alignment, and endianness gotchas that can be portably addressed with byte-level de/ser. Example: https://gist.github.com/cd089675a6088b0b8482c005a0e3897a https://gist.github.com/cd089675a6088b0b8482c005a0e3897a
- libcheet 2y agoFrom product C code perspective, this code is of course bad. But here idea was to show data manipulation closer to how it is shown in documentation. Also a lot requests have dynamic size and cannot be as easily packed and serialized to be sent over the "wire". So for example you could put pointer to string into struct, malloc required space, then assign pointer. After when you want to send data you would have to write serialization methods to put it in correct order. It is all fine and should be done when you build bulletproof system to manage X11. But here these techniques just draws too much attention away from X11.
- deleted 2y ago[deleted]
- pavon 2y agoThere is no portable way to define structure alignment and padding in C. Your options are to make assumptions about how structs are aligned for a specific ABI, but which could be different on other ABIs or architectures resulting in broken code. Or to use compiler extensions to force packing which will make the alignment deterministic, but which could still blow up on other architectures if the alignment you used isn't valid on that architecture. In some cases you could manually pad your structs to satisfy lowest common denominator architecture requirements, and use compiler extensions mark them as packed (which should be a noop on the architectures you've considered), if the protocol padding/alignment is compatible with those requirements. But the code still theoretically could break on ABIs you didn't consider. Manually packing and unpacking bytes is the safest way to do things in production.
- pantalaimon 2y ago> There is no portable way to define structure alignment and padding in C Of course there is __attribute__((packed)) and __attribute__((aligned(8)))