Re: [TECH TOPIC] Rust for Linux

Miguel Ojeda
2021-07-19T15:43:52Z

On Mon, Jul 19, 2021 at 5:15 PM Andrew Lunn <andrew@lunn.ch> wrote:
>
> Can you express endianness here as well? There are often cases where
> the hardware is always big endian independent of the CPU
> endianness. Some of the readl/writel macros handle this, adding a swap
> when the two don't match.

Yes, of course!

Querying the endianness can be done as usual, similar to the C preprocessor:

pub fn f(n: i32) -> i32 {
#[cfg(target_endian = "little")]
return n + 42;

#[cfg(target_endian = "big")]
return n;
}

As well as with the `cfg!` macro, more ergonomic for small things like this:

pub fn f(n: i32) -> i32 {
if cfg!(target_endian = "little") {
n + 42
} else {
n
}
}

As well in macros (like the `memory_map!` shown above).

If you just need the most common case, i.e. converting from/to a given
endianness, the primitive types come with functions for that, e.g. the
following would include a `bswap` in x86:

pub fn f(n: i32) -> i32 {
i32::from_be(n)
}

See `{from,to}_{be,le}` in https://doc.rust-lang.org/std/primitive.i32.html

Cheers,
Miguel