tustvold commented on code in PR #3553:
URL: https://github.com/apache/arrow-rs/pull/3553#discussion_r1084292191


##########
arrow-array/src/array/run_array.rs:
##########
@@ -0,0 +1,499 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use std::any::Any;
+
+use arrow_data::{ArrayData, ArrayDataBuilder};
+use arrow_schema::{ArrowError, DataType, Field};
+
+use crate::{
+    builder::StringRunBuilder,
+    make_array,
+    types::{Int16Type, Int32Type, Int64Type, RunEndIndexType},
+    Array, ArrayRef, PrimitiveArray,
+};
+
+///
+/// A run-end encoding (REE) is a variation of [run-length encoding 
(RLE)](https://en.wikipedia.org/wiki/Run-length_encoding).
+///
+/// This encoding is good for representing data containing same values 
repeated consecutively.
+///
+/// [`RunArray`] contains `run_ends` array and `values` array of same length.
+/// The `run_ends` array stores the indexes at which the run ends. The 
`values` array
+/// stores the value of each run. Below example illustrates how a logical 
array is represented in
+/// [`RunArray`]
+///
+///
+/// ```text
+/// ┌ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┐
+///   ┌─────────────────┐  ┌─────────┐       ┌─────────────────┐
+/// │ │        A        │  │    2    │ │     │        A        │     
+///   ├─────────────────┤  ├─────────┤       ├─────────────────┤
+/// │ │        D        │  │    3    │ │     │        A        │    run length 
of 'A' = runs_ends[0] - 0 = 2
+///   ├─────────────────┤  ├─────────┤       ├─────────────────┤
+/// │ │        B        │  │    6    │ │     │        D        │    run length 
of 'D' = run_ends[1] - run_ends[0] = 1
+///   └─────────────────┘  └─────────┘       ├─────────────────┤
+/// │        values          run_ends  │     │        B        │     
+///                                          ├─────────────────┤
+/// └ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─┘     │        B        │     
+///                                          ├─────────────────┤
+///                RunArray                  │        B        │    run length 
of 'B' = run_ends[2] - run_ends[1] = 3
+///               length = 3                 └─────────────────┘
+///  
+///                                             Logical array
+///                                                Contents
+/// ```
+
+pub struct RunArray<R: RunEndIndexType> {
+    data: ArrayData,
+    run_ends: PrimitiveArray<R>,
+    values: ArrayRef,
+}
+
+impl<R: RunEndIndexType> RunArray<R> {
+    /// Attempts to create RunArray using given run_ends (index where a run 
ends)
+    /// and the values (value of the run). Returns an error if the given data 
is not compatible
+    /// with RunEndEncoded specification.
+    pub fn try_new(
+        run_ends: &PrimitiveArray<R>,
+        values: &dyn Array,
+    ) -> Result<Self, ArrowError> {
+        let run_ends_type = run_ends.data_type().clone();
+        let values_type = values.data_type().clone();
+        let ree_array_type = DataType::RunEndEncoded(
+            Box::new(Field::new("run_ends", run_ends_type, false)),
+            Box::new(Field::new("values", values_type, true)),
+        );
+        let builder = ArrayDataBuilder::new(ree_array_type)
+            .add_child_data(run_ends.data().clone())
+            .add_child_data(values.data().clone());
+
+        // `build_unchecked` is used to avoid recursive validation of child 
arrays.
+        let array_data = unsafe { builder.build_unchecked() };
+
+        // Safety: `validate_data` checks below
+        //    1. The given array data has exactly two child arrays.
+        //    2. The first child array (run_ends) has valid data type.
+        //    3. run_ends array does not have null values
+        //    4. run_ends array has non-zero and strictly increasing values.
+        //    5. The length of run_ends array and values array are the same.
+        array_data.validate_data()?;
+
+        Ok(array_data.into())
+    }
+    /// Returns a reference to run_ends array
+    ///
+    /// Note: any slicing of this array is not applied to the returned array
+    /// and must be handled separately
+    pub fn run_ends(&self) -> &PrimitiveArray<R> {
+        &self.run_ends
+    }
+
+    /// Returns a reference to values array
+    pub fn values(&self) -> &ArrayRef {
+        &self.values
+    }
+}
+
+impl<R: RunEndIndexType> From<ArrayData> for RunArray<R> {
+    // The method assumes the caller already validated the data using 
`ArrayData::validate_data()`
+    fn from(data: ArrayData) -> Self {
+        match data.data_type() {
+            DataType::RunEndEncoded(_, _) => {}
+            _ => {
+                panic!("Invalid data type for RunArray. The data type should 
be DataType::RunEndEncoded");
+            }
+        }
+
+        let run_ends = PrimitiveArray::<R>::from(data.child_data()[0].clone());
+        let values = make_array(data.child_data()[1].clone());
+        Self {
+            data,
+            run_ends,
+            values,
+        }
+    }
+}
+
+impl<R: RunEndIndexType> From<RunArray<R>> for ArrayData {
+    fn from(array: RunArray<R>) -> Self {
+        array.data
+    }
+}
+
+impl<T: RunEndIndexType> Array for RunArray<T> {
+    fn as_any(&self) -> &dyn Any {
+        self
+    }
+
+    fn data(&self) -> &ArrayData {
+        &self.data
+    }
+
+    fn into_data(self) -> ArrayData {
+        self.into()
+    }
+}
+
+impl<R: RunEndIndexType> std::fmt::Debug for RunArray<R> {
+    fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result {
+        writeln!(
+            f,
+            "RunArray {{run_ends: {:?}, values: {:?}}}",
+            self.run_ends, self.values
+        )
+    }
+}
+
+/// Constructs a `RunArray` from an iterator of optional strings.
+///
+/// # Example:
+/// ```
+/// use arrow_array::{RunArray, PrimitiveArray, StringArray, types::Int16Type};
+///
+/// let test = vec!["a", "a", "b", "c", "c"];
+/// let array: RunArray<Int16Type> = test
+///     .iter()
+///     .map(|&x| if x == "b" { None } else { Some(x) })
+///     .collect();
+/// assert_eq!(
+///     "RunArray {run_ends: PrimitiveArray<Int16>\n[\n  2,\n  3,\n  5,\n], 
values: StringArray\n[\n  \"a\",\n  null,\n  \"c\",\n]}\n",
+///     format!("{:?}", array)
+/// );
+/// ```
+impl<'a, T: RunEndIndexType> FromIterator<Option<&'a str>> for RunArray<T> {
+    fn from_iter<I: IntoIterator<Item = Option<&'a str>>>(iter: I) -> Self {
+        let it = iter.into_iter();
+        let (lower, _) = it.size_hint();
+        let mut builder = StringRunBuilder::with_capacity(lower, 256);
+        it.for_each(|i| {
+            if let Some(i) = i {
+                builder.append_value(i);
+            } else {
+                builder.append_null();
+            }
+        });
+
+        builder.finish()
+    }
+}
+
+/// Constructs a `RunArray` from an iterator of strings.
+///
+/// # Example:
+///
+/// ```
+/// use arrow_array::{RunArray, PrimitiveArray, StringArray, types::Int16Type};
+///
+/// let test = vec!["a", "a", "b", "c"];
+/// let array: RunArray<Int16Type> = test.into_iter().collect();
+/// assert_eq!(
+///     "RunArray {run_ends: PrimitiveArray<Int16>\n[\n  2,\n  3,\n  4,\n], 
values: StringArray\n[\n  \"a\",\n  \"b\",\n  \"c\",\n]}\n",
+///     format!("{:?}", array)
+/// );
+/// ```
+impl<'a, T: RunEndIndexType> FromIterator<&'a str> for RunArray<T> {
+    fn from_iter<I: IntoIterator<Item = &'a str>>(iter: I) -> Self {
+        let it = iter.into_iter();
+        let (lower, _) = it.size_hint();
+        let mut builder = StringRunBuilder::with_capacity(lower, 256);
+        it.for_each(|i| {
+            builder.append_value(i);
+        });
+
+        builder.finish()
+    }
+}
+
+///
+/// A [`RunArray`] array where run ends are stored using `i16` data type.
+///
+/// # Example: Using `collect`
+/// ```
+/// # use arrow_array::{Array, Int16RunArray, Int16Array, StringArray};
+/// # use std::sync::Arc;
+///
+/// let array: Int16RunArray = vec!["a", "a", "b", "c", 
"c"].into_iter().collect();
+/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", 
"c"]));
+/// assert_eq!(array.run_ends(), &Int16Array::from(vec![2, 3, 5]));
+/// assert_eq!(array.values(), &values);
+/// ```
+pub type Int16RunArray = RunArray<Int16Type>;
+
+///
+/// A [`RunArray`] array where run ends are stored using `i32` data type.
+///
+/// # Example: Using `collect`
+/// ```
+/// # use arrow_array::{Array, Int32RunArray, Int32Array, StringArray};
+/// # use std::sync::Arc;
+///
+/// let array: Int32RunArray = vec!["a", "a", "b", "c", 
"c"].into_iter().collect();
+/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", 
"c"]));
+/// assert_eq!(array.run_ends(), &Int32Array::from(vec![2, 3, 5]));
+/// assert_eq!(array.values(), &values);
+/// ```
+pub type Int32RunArray = RunArray<Int32Type>;
+
+///
+/// A [`RunArray`] array where run ends are stored using `i64` data type.
+///
+/// # Example: Using `collect`
+/// ```
+/// # use arrow_array::{Array, Int64RunArray, Int64Array, StringArray};
+/// # use std::sync::Arc;
+///
+/// let array: Int64RunArray = vec!["a", "a", "b", "c", 
"c"].into_iter().collect();
+/// let values: Arc<dyn Array> = Arc::new(StringArray::from(vec!["a", "b", 
"c"]));
+/// assert_eq!(array.run_ends(), &Int64Array::from(vec![2, 3, 5]));
+/// assert_eq!(array.values(), &values);
+/// ```
+pub type Int64RunArray = RunArray<Int64Type>;
+
+#[cfg(test)]
+mod tests {
+    use std::sync::Arc;
+
+    use super::*;
+    use crate::builder::PrimitiveRunBuilder;
+    use crate::types::{Int16Type, Int32Type, Int8Type, UInt32Type};
+    use crate::{Array, Int16Array, Int32Array, StringArray};
+    use arrow_schema::Field;
+
+    #[test]
+    fn test_run_array() {
+        // Construct a value array
+        let value_data = PrimitiveArray::<Int8Type>::from_iter_values([
+            10_i8, 11, 12, 13, 14, 15, 16, 17,
+        ])
+        .into_data();
+
+        // Construct a run_ends array:
+        let run_ends_data = PrimitiveArray::<Int16Type>::from_iter_values([
+            4_i16, 6, 7, 9, 13, 18, 20, 22,
+        ])
+        .into_data();
+
+        // Construct a run ends encoded array from the above two
+        let run_ends_type = Field::new("run_ends", DataType::Int16, false);
+        let value_type = Field::new("values", DataType::Int8, true);
+        let ree_array_type =
+            DataType::RunEndEncoded(Box::new(run_ends_type), 
Box::new(value_type));
+        let dict_data = ArrayData::builder(ree_array_type)
+            .add_child_data(run_ends_data.clone())
+            .add_child_data(value_data.clone())
+            .build()
+            .unwrap();
+        let ree_array = Int16RunArray::from(dict_data);
+
+        let values = ree_array.values();
+        assert_eq!(&value_data, values.data());
+        assert_eq!(&DataType::Int8, values.data_type());
+

Review Comment:
   ```suggestion
   assert_eq!(ree_array.len(), 22)
   ```



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]

Reply via email to