Data: &[u8], width: usize -> Vec<&[u8]>

I want to write a function:

(data: &[u8], width: usize) -> Vec<&[u8]>

where the output is:

vec![
  data[0 .. width-1],
  data[width .. 2*width-1],
  ...
  data[i * width, (i+1)* width-1]
 ...
  data[ multiple of width, data.len() ]
]

Is there a builtin for this?

data.chunks(width).collect()
3 Likes

That looks so much better than:

pub struct U8Grid<'a> {
    data: Vec<&'a [u8]>,
}

impl<'a> U8Grid<'a> {
    pub fn new(width: usize, data: &[u8]) -> U8Grid {
        let mut ans = vec![];
        let len = data.len();
        let end = len / width;

        for i in 0..(len / width) {
            ans.push(&data[i * width..(i + 1) * width]);
        }

        if end * width < len {
            ans.push(&data[end * width..len]);
        }

        U8Grid { data: ans }
    }
}

:slight_smile: