Concatenate array slices

后端 未结 3 2212
失恋的感觉
失恋的感觉 2021-02-20 02:13

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

3条回答
  •  感动是毒
    2021-02-20 02:38

    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 of k array slices, an arbitrary array access for result 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.

提交回复
热议问题