For instance I'm not familiar with this boost library so I'd have a lot of trouble piecing out what your snippet does, especially since there's no explicit function call besides the printf.
Personally if we're going the OOP route I'd much prefer something like Rust's `var.to_be()`, `var.to_le` etc... At least it's very explicit.
My hot take is that operator overloading should only ever be used for mathematical operators (multiplying vectors etc...), everything else is almost invariably a bad idea.
Boost.Endian actually lets you pick between arithmetic and buffer types.
'big_uint32_buf_t' is a buffer type that requires you to call .value() or do a conversion to an integral type. It does not support arithmetic operations.
'big_uint32_t' is an arithmetic type, and supports all the arithmetic operators.
There are also variants of both endian suffixed '_at' for when you know you have aligned access.
If I have a 3 byte big endian integer can I access it easily in rust without resorting to shifts?
In C++ I could probably create a fairly convincing big_uint24_t type and use it in a packed struct and there would be no inconsistencies with how it's used with respect to the more common varieties
I'm not sure about a 3 byte big endian integer. I mean, that's going to compile down to some combination of shifting and masking operations anyway, isn't it? I suspect that if you have some oddball binary format that needs, this it will be possible to write some code to marshal it, that compiles down to the best possible asm. Godbolt is your friend here :)
[1]: https://rust-lang.github.io/rfcs/0445-extension-trait-conven...
I think there's no need for explicit shifts. You need to memcpy anyway to deal with alignment issues, so you may as well just copy in to the last 3 bytes of a zero-initialized, big endian, 32bit uint.
https://gcc.godbolt.org/z/9qGqh6M1E
And I think we're on the same page, it should be possible to get similar results in Rust.
If you need to change byte orders, you should use library to achieve that.
This is why ubsan is silent and not even injecting a check in to the compiled code.
You can check the alignment constraints with static_assert (something else you can't do in standard C): https://gcc.godbolt.org/z/KTcf9ax6r
Is also has _Generic() so you can roll up a family of endianness conversion functions and safely change types without blowing up somewhere else with a hardcoded conversion routine.
This example is demonstrating:
- First class treatment of user (or library) defined types
- Operator overloading
- The fact that it produces fast machine code. Try changing big_uint32_t to regular uint32_t to see how this changes. When you use the later ubsan will introduce a trap for runtime checks, but it doesn't need to in this case.