If you're using unsafe anyway, I'd go the other direction, casting from the 
larger alignment to the smaller one. That avoids any alignment concerns.

var x uint32
b := (*[4]byte)(unsafe.Pointer(&x))[:]
r.buff.Read(b)
return x

I would encourage you to use encoding/binary though. It all works out just 
as well without unsafe, with a bit of trickiness around making sure that 
calls can be resolved and inlined.

b := make([]byte, 4)
buf.Read(b)
if little { // some global variable (or constant) you set
   return binary.LittleEndian.Uint32(b)
}
return binary.BigEndian.Uint32(b)
On Friday, March 3, 2023 at 12:30:37 PM UTC-8 TheDiveO wrote:

> In dealing with Linux netlink messages I need to decode and encode uint16, 
> uint32, and uint64 numbers that are in an arbitrary aligned byte buffer in 
> an arbitrary position. In any case, these numbers are in native endianess, 
> so I would like to avoid having to go through encoding/binary.
>
> buff := bytes.NewBuffer(/* some data */)
>
> // ...
>
> func foo() uint32 {
>     var s struct {
>         _ [0]uint32
>         b [4]byte
>     }
>     r.buff.Read(s.b[:])
>     return *(*uint32)(unsafe.Pointer(&s.b[0]))
> }
>
> Will the go compiler (1.19+) allocate on the stack with the correct 
> alignment for its element b, so that the unsafe.Pointer operation correctly 
> works on different CPU architectures?
>
> Or is this inefficient anyway in a subtle way that my attempt to avoid 
> non-stack allocations is moot anyway?
>

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/golang-nuts/7b241c86-3295-4488-888c-1beb467dd1b1n%40googlegroups.com.

Reply via email to