Way to Do Something Like `#[repr(simd)]` on Stable Rust?

I'm trying to create a Rust vector type that only needs to work on WASM, but that I want to map to the WASM v128 type.

I can accomplish a working version by creating a type like this:

use core::arch::wasm32;

pub struct Vec4(wasm32::v128);

impl Vec4 {
    // impl vector functions

But I want to, for ergonomics sake be able to access individual fields in the type by just doing my_var.x, my_var.y, etc.

I could easily create functions such as get_x() and set_x(), but that is much more typing that just x.

On nightly you can use #[repr(simd)], it looks like, and do this:

pub struct Vec4 {
    x: f32,
    y: f32,
    z: f32,
    w: f32,

I'm really trying to avoid having to use nightly, though. Are there any hacks I can use to somehow make this work?

I'm fairly certain there's no way in Rust to make field access resolve to a function right? Like automatically converting my_var.x = 3 to my_var.set_x(3)?

The only way I can think of is:

struct Vector4 {
    data: core::arch::wasm32::v128,

struct Vector4Mut<'a> {
    x: &'a mut f32,
    y: &'a mut f32,
    z: &'a mut f32,
    w: &'a mut f32,

impl Vector4 {
    // single getter instead of four
    fn as_mut(&mut self) -> Vector4Mut {
        let (x, y, z, w) = &mut self.data;
        // or whatever
        Vector4Mut { x, y, z, w }

// usage

let mut v = Vector4::new();

*v.as_mut().x = 10.0;
*v.as_mut().z = 33.0;

but I don't know if this is significatly better than having multiple getters...

1 Like

That's not horrible. :thinking:

I'll keep it in mind. For now I found a 100% different approach for my use-case that I think will work, so hopefully I won't need it now, but we'll see.


1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.