jswrenn / typic

Type-safe transmutations between layout-compatible types.
https://crates.io/crates/typic
Apache License 2.0
121 stars 4 forks source link

Use with slices? #7

Open rw opened 4 years ago

rw commented 4 years ago

Is there a good way to use this with slices? I see that there are tests for arrays. Maybe by asserting the length at runtime, this becomes safe?

I'm interested in using typic to unsafe code in flatbuffers (some UB that was reported recently, so I'm on a hunt to remove all unsafe https://github.com/google/flatbuffers/issues/5913).

joshlf commented 4 years ago

Hi @rw, have you seen the zerocopy crate? It currently supports slices. I'm the author, and I am hoping that typic will get to the point of supporting slices (and eventually take over zerocopy entirely), but for the time being, if you need something immediately, I'd check it out.

rw commented 4 years ago

@joshlf Very cool, thank you!

cwhan-yonsei commented 1 year ago

Is there any update regarding the topic? I need would like to transmute some struct to byte array and construct it from by trade for serial communication. is the zerocopy the only solution at this point?

joshlf commented 1 year ago

I don't believe typic is under active development. I'd check out the zerocopy or bytemuck crates. If you can describe in a bit more detail what you're trying to do, I can suggest specific APIs to look at.

cwhan-yonsei commented 1 year ago

I don't believe typic is under active development. I'd check out the zerocopy or bytemuck crates. If you can describe in a bit more detail what you're trying to do, I can suggest specific APIs to look at.

@joshlf I appreciate your kind suggestion. I'd like to construct a message for SPI communication semantically and also check the received message in a semantic manner. So I end up doing something below with zerocopy crate.

let inc_reading_tx = FullReg {
            cmd_or_dummy_byte: inc_reading_byte,
            adc_data: u24::new(),

           ...

            reserved2: 0u16,
            crc_cfg: 0u16,
        };

let mut read_buffer = FullReg::new_zeroed();
spi.transfer(read_buffer.as_bytes_mut(), inc_reading_tx.as_bytes())?;

Would there be any equivalent solution with typic? Or would it be correct to use zerocopy in such purpose?

joshlf commented 1 year ago

What is the API of the spi.transfer method? Does it read a response from the SPI peripheral into read_buffer.as_mut_bytes()? If so, then yeah I think sticking with zerocopy should work fine for you.

cwhan-yonsei commented 1 year ago

@joshlf Yes, Indeed you are right. I used as_byte_mut for the read_buffer and it works as expected. Thank you.

joshlf commented 1 year ago

You're welcome!