Re: [PATCH 00/13] [RFC] Rust support

From: Miguel Ojeda
Date: Mon Apr 26 2021 - 14:01:43 EST


On Mon, Apr 26, 2021 at 2:18 AM Linus Walleij <linus.walleij@xxxxxxxxxx> wrote:
>
> static void yas53x_extract_calibration(u8 *data, struct yas5xx_calibration *c)
> {
> u64 val = get_unaligned_be64(data);
>
> c->a2 = FIELD_GET(GENMASK_ULL(63, 58), val) - 32;
> c->a3 = FIELD_GET(GENMASK_ULL(57, 54), val) - 8;
> c->a4 = FIELD_GET(GENMASK_ULL(53, 48), val) - 32;
> c->a5 = FIELD_GET(GENMASK_ULL(47, 42), val) + 38;
> c->a6 = FIELD_GET(GENMASK_ULL(41, 36), val) - 32;
> c->a7 = FIELD_GET(GENMASK_ULL(35, 29), val) - 64;
> c->a8 = FIELD_GET(GENMASK_ULL(28, 23), val) - 32;
> c->a9 = FIELD_GET(GENMASK_ULL(22, 15), val);
> c->k = FIELD_GET(GENMASK_ULL(14, 10), val) + 10;
> c->dck = FIELD_GET(GENMASK_ULL(9, 7), val);
> }

By the way, to give a more concrete example, this function could look like this:

fn yas53x_extract_calibration(data: [u8; 8], c: &mut yas5xx_calibration)
{
let val = u64::from_be_bytes(data);

c.a2 = FIELD_GET(GENMASK_ULL(63, 58), val) - 32;
c.a3 = FIELD_GET(GENMASK_ULL(57, 54), val) - 8;
c.a4 = FIELD_GET(GENMASK_ULL(53, 48), val) - 32;
c.a5 = FIELD_GET(GENMASK_ULL(47, 42), val) + 38;
c.a6 = FIELD_GET(GENMASK_ULL(41, 36), val) - 32;
c.a7 = FIELD_GET(GENMASK_ULL(35, 29), val) - 64;
c.a8 = FIELD_GET(GENMASK_ULL(28, 23), val) - 32;
c.a9 = FIELD_GET(GENMASK_ULL(22, 15), val);
c.k = FIELD_GET(GENMASK_ULL(14, 10), val) + 10;
c.dck = FIELD_GET(GENMASK_ULL(9, 7), val) as u8;
}

assuming `FIELD_GET()` returns `i32`. In particular, `GENMASK_ULL` and
`FIELD_GET` can be written as normal functions, no need for macros
(and can be `const fn` too -- i.e. can be evaluated at compile-time if
needed).

As you see, it looks remarkably similar, and there is no `unsafe`
because we pass the array of bytes instead of a raw pointer.

The caller needs to get the array from somewhere, of course -- if you
only have a raw pointer to start with, then the caller will need an
`unsafe` line to dereference it, as usual.

Cheers,
Miguel