Convert vectors to arrays and back

dirvine

I am attempting to figure the most Rust-like way of converting from a vector to array and back. These macros will work and can even be made generic with some unsafe blocks, but it all feels very un-Rust like.

I would appreciate any input and hold no punches, I think this code is far from nice or optimal. I have only played with Rust for a few weeks now and chasing releases and docs so really appreciate help.

macro_rules! convert_u8vec_to_array {
    ($container:ident, $size:expr) => {{
    if $container.len() != $size {
            None
    } else {
        use std::mem;
        let mut arr : [_; $size] = unsafe { mem::uninitialized() };
        for element in $container.into_iter().enumerate() {
            let old_val = mem::replace(&mut arr[element.0],element.1);
            unsafe { mem::forget(old_val) };
        }
        Some(arr)
        }
    }};
}

fn array_to_vec(arr: &[u8]) -> Vec<u8> {
     let mut vector = Vec::new();
     for i in arr.iter() {
         vector.push(*i);
     }
     vector
}

fn vector_as_u8_4_array(vector: Vec<u8>) -> [u8;4] {
    let mut arr = [0u8;4];
    for i in (0..4) {
        arr[i] = vector[i];
    }
    arr
}
huon

The code seems fine to me, although there's a very important safety thing to note: there can be no panics while arr isn't fully initialised. Running destructors on uninitialised memory could easily lead be undefined behaviour, and, in particular, this means that into_iter and the next method of it should never panic (I believe it is impossible for the enumerate and mem::* parts of the iterator to panic given the constraints of the code).

That said, one can express the replace/forget idiom with a single function: std::ptr::write.

for (idx, element) in $container.into_iter().enumerate() {
    ptr::write(&mut arr[idx], element);
}

Although, I would write it as:

for (place, element) in arr.iter_mut().zip($container.into_iter()) {
    ptr::write(place, element);
}

Similarly, one can apply some iterator goodness to the u8 specialised versions:

fn array_to_vec(arr: &[u8]) -> Vec<u8> {
     arr.iter().cloned().collect()
}
fn vector_as_u8_4_array(vector: Vec<u8>) -> [u8;4] {
    let mut arr = [0u8;4];
    for (place, element) in arr.iter_mut().zip(vector.iter()) {
        *place = *element;
    }
    arr
}

Although the first is probably better written as arr.to_vec(), and the second as

let mut arr = [0u8; 4];
std::slice::bytes::copy_memory(&vector, &mut arr);
arr

Although that function is unstable currently, and hence only usable on nightly.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

How to convert vectors to arrays in ECLiPSe (CLP)? (or Prolog)

From Dev

Aggregate Initialization - Vectors and Arrays

From Dev

Vectors and Arrays in C++

From Dev

Comparing byte arrays and vectors

From Dev

array of vectors or vector of arrays?

From Dev

Matlab arrays, vectors

From Dev

Comparing byte arrays and vectors

From Dev

C++ Arrays and Vectors

From Dev

How convert this DataFrame in vectors?

From Dev

Convert map of vectors to vectors of columns in Clojure

From Dev

Convert map of vectors to vectors of columns in Clojure

From Dev

Arrays better for serialization than Vectors

From Dev

Numpy broadcasting sliced arrays and vectors

From Dev

Difference between vectors and arrays in Modelica

From Dev

Numpy broadcasting sliced arrays and vectors

From Dev

Use of Vectors of vectors in C++ & push_back( )

From Dev

Perl: Arrays to Methods and Back

From Dev

Convert local Vectors to RDD[Vector]

From Dev

How to convert a Matrix into a Vector of Vectors?

From Dev

Using `push_back()` with multidimensional vectors

From Dev

push_back a vector of vectors into a vector

From Dev

initializing arrays of vectors on the heap, c++

From Java

Dictionary from two Arrays/Vectors in Julia

From Dev

Changing a function to use vectors instead of arrays

From Dev

.double arrays to sse vectors and operations on them

From Dev

C# arrays to C++ vectors

From Dev

About sets using arrays and bit vectors

From Dev

plotting 3d vectors (arrays) in python

From Dev

How to use arrays or vectors of pointers polymorphically?