1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
use arrow_buffer::ArrowNativeType;
use vortex_dtype::{match_each_integer_ptype, match_each_native_ptype, NativePType};
use vortex_error::VortexResult;

use crate::array::PrimitiveArray;
use crate::patches::Patches;
use crate::validity::Validity;
use crate::variants::PrimitiveArrayTrait;
use crate::{ArrayLen, IntoArrayVariant};

impl PrimitiveArray {
    #[allow(clippy::cognitive_complexity)]
    pub fn patch(self, patches: Patches) -> VortexResult<Self> {
        let (_, patch_indices, patch_values) = patches.into_parts();
        let patch_indices = patch_indices.into_primitive()?;
        let patch_values = patch_values.into_primitive()?;

        let patched_validity =
            self.validity()
                .patch(self.len(), patch_indices.as_ref(), patch_values.validity())?;

        match_each_integer_ptype!(patch_indices.ptype(), |$I| {
            match_each_native_ptype!(self.ptype(), |$T| {
                self.patch_typed::<$T, $I>(patch_indices, patch_values, patched_validity)
            })
        })
    }

    fn patch_typed<T, I>(
        self,
        patch_indices: PrimitiveArray,
        patch_values: PrimitiveArray,
        patched_validity: Validity,
    ) -> VortexResult<Self>
    where
        T: NativePType + ArrowNativeType,
        I: NativePType + ArrowNativeType,
    {
        let mut own_values = self.into_maybe_null_slice::<T>();

        let patch_indices = patch_indices.into_maybe_null_slice::<I>();
        let patch_values = patch_values.into_maybe_null_slice::<T>();
        for (idx, value) in itertools::zip_eq(patch_indices, patch_values) {
            own_values[idx.as_usize()] = value;
        }
        Ok(Self::from_vec(own_values, patched_validity))
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::compute::slice;
    use crate::validity::Validity;
    use crate::IntoArrayVariant;

    #[test]
    fn patch_sliced() {
        let input = PrimitiveArray::from_vec(vec![2u32; 10], Validity::AllValid);
        let sliced = slice(input, 2, 8).unwrap();
        assert_eq!(
            sliced
                .into_primitive()
                .unwrap()
                .into_maybe_null_slice::<u32>(),
            vec![2u32; 6]
        );
    }
}