I have two (very large) arrays foo
and bar
of the same type. To be able to write some nice code, I would like to obtain a read-only slice, result
There isn't a predefined type, but you can easily create your own by implementing the Index
trait for a type that holds both your slices:
use std::ops::Index;
struct Slice<'a, T: 'a>(&'a[T], &'a[T]);
impl<'a, T: 'a> Index for Slice<'a, T> {
type Output = T;
fn index(&self, index: usize) -> &T {
if index < self.0.len() {
&self.0[index]
} else {
&self.1[index - self.0.len()]
}
}
}
More generally, if
result
were the concatenation ofk
array slices, an arbitrary array access forresult
should run in O(k
).
You can get slice access in O(log(k))
, if your slice concatenation is O(k)
, by creating an array that holds the cumulative lengths of the slices and using a binary search to find the actual slice to index into.
This would require a macro, because we don't have a good enough constant evaluator yet and no value generics.