Struct as slice?

#1

Is it possible to get a struct as a slice - or maybe a slice as a struct?

In other words given something like:

struct Color {
  r: f64,
  g: f64,
  b: f64,
  a: f64
}

It would be really nice to be able to get a &[f64] from that for free, without allocating a new one each time - i.e. just to view it as a contiguous block of memory.

Alternatively, I guess one could just keep a private backing vector or array, and setup accessors so that they’re gotten via calling color.r() etc…

But for now I’m wondering if there’s something built-in to allow this for free

0 Likes

#2

Seems that this won’t be possible without unsafe. You’re essentially requesting some kind of the “reinterpret_cast”, which is unsafe by design.

2 Likes

#3

Oh interesting… I am curious how it would look with unsafe too :slight_smile:

0 Likes

#4
  1. You must add #[repr(C)]. Without this the compiler is free to store fields in any layout/order it wants.
  2. std::slice_from_raw_parts(&color as *const Color as *const f64, 4). It needs to infer proper lifetimes. The easiest way is to put it in a function that takes and returns a reference.

Also, it already exists for RGBA: https://docs.rs/rgb/0.8.11/rgb/trait.ComponentSlice.html

type Color = rgb::RGBA<f64>;

let c = Color::new(0.,0.,0.,1.);
let s = c.as_slice();
4 Likes

#5

You were faster :slight_smile: Anyway, I’ll leave it here: https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=be1f0a0435355f9aef42bd24f0b4bcd4 (note that here lifetimes are not a problem, since all the program fits in main; in real cases this must be thought of).

2 Likes

#6

BTW: It’s best to avoid transmute. It’s very easy to do something very wrong with it if you don’t specify types explicitly transmute::<from, to>(). For pointer types the as operator works fine.

0 Likes

#7

Thanks, I’ve tried to do this before, but missed the fact that I should do double cast. Updated link in the previous reply.

1 Like

#8

Neat! Do you have other crates for Point, Area, and similar structs?

0 Likes

#9

For area I’ve got https://crates.rs/crates/imgref

1 Like