Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the best way to convert a [[T; 4]; 3] into a [T; 12]?

As I understand it, a [[T; 4]; 3] and a [T; 12] have the same layout in memory. What is the best way to convert a value between these types? Can I convert a reference to one into a reference to the other? Can I avoid copying all the elements? Do I need unsafe?

like image 524
apt1002 Avatar asked Dec 13 '16 01:12

apt1002


People also ask

Can T8 replace T12?

Options for replacing T12 fluorescent tubesThe easiest and lowest price option to replace a T12 is a T8 linear fluorescent. They have become the go-to option for pre-existing T12s. If you still have magnetic ballasts, switching to a T8 will require a ballast swap.

What is a T12 fluorescent tube?

The T12 is an older generation fluorescent bulb that generates light through electromagnetic induction, which is considered less efficient method of creating light compared to that of newer electronic based circuits.

Can I replace T12 fluorescent tube with LED?

These LED tubes are the newest, easiest to install and most expensive. They work with any kind of existing technology – whether it is T12 (Magnetic Ballast) or T8 (Electronic Ballast). To install them all you need to do is take the old fluorescent tube out and install the LED tube in its place.


1 Answers

Yes, you can convert a reference to a [[T; 4]; 3] into a reference to a [T; 12], but only with unsafe code, using mem::transmute. It's best to wrap this in a function so that the resulting reference is assigned the proper lifetime, as otherwise transmute would make it possible to obtain a reference with a larger lifetime than the reference should have.

fn convert<'a>(a: &'a [[u8; 4]; 3]) -> &'a [u8; 12] {
    unsafe { std::mem::transmute(a) }
}

This can be shortened thanks to the lifetime elision rules:

fn convert(a: &[[u8; 4]; 3]) -> &[u8; 12] {
    unsafe { std::mem::transmute(a) }
}

Though when dealing with unsafe code, I'd understand if you preferred the more explicit version!

like image 65
Francis Gagné Avatar answered Sep 18 '22 10:09

Francis Gagné