Exploring ways of accessing cells of a 2D matrix backed by a regular Vec/array
I'm using an array/vector to back a 2-dimensional matrix. Now to get a "cell" we of course would use the `num_cols * y + x` formula, however I found 3 ways of obtaining an element:
This one can of course panic, but also, I think there's a possibility of integer overflow:
pub fn get_item2(items: &[u8], width: usize, x: usize, y: usize) -> Option {
Some(items[width * y + x])
}
This one won't panic because of an out of bounds index, but I think the integer overflow is still possible:
pub fn get_item3(items: &[u8], width: usize, x: usize, y: usize) -> Option {
items.get(width * y + x).cloned()
}
Now I came up with this version (which I ended up using) that I like because there's no possibility of out-of-bound panics and I think I eliminated the posibility of integer overflow, since I'm not multiplying anything...
pub fn get_item(items: &[u8], width: usize, x: usize, y: usize) -> Option {
items.chunks(width).nth(y).and_then(|chunk| chunk.get(x)).cloned()
}
Am I correct? Is the last version "safer"? Are there other ways of doing this?
https://redd.it/hi5ozp
@r_rust
I'm using an array/vector to back a 2-dimensional matrix. Now to get a "cell" we of course would use the `num_cols * y + x` formula, however I found 3 ways of obtaining an element:
This one can of course panic, but also, I think there's a possibility of integer overflow:
pub fn get_item2(items: &[u8], width: usize, x: usize, y: usize) -> Option {
Some(items[width * y + x])
}
This one won't panic because of an out of bounds index, but I think the integer overflow is still possible:
pub fn get_item3(items: &[u8], width: usize, x: usize, y: usize) -> Option {
items.get(width * y + x).cloned()
}
Now I came up with this version (which I ended up using) that I like because there's no possibility of out-of-bound panics and I think I eliminated the posibility of integer overflow, since I'm not multiplying anything...
pub fn get_item(items: &[u8], width: usize, x: usize, y: usize) -> Option {
items.chunks(width).nth(y).and_then(|chunk| chunk.get(x)).cloned()
}
Am I correct? Is the last version "safer"? Are there other ways of doing this?
https://redd.it/hi5ozp
@r_rust