polars_arrow/legacy/
index.rs

1use std::fmt::Display;
2
3use num_traits::{NumCast, Signed, Zero};
4use polars_error::{polars_err, PolarsResult};
5use polars_utils::IdxSize;
6
7use crate::array::PrimitiveArray;
8
9pub trait IndexToUsize: Display {
10    /// Translate the negative index to an offset.
11    fn negative_to_usize(self, len: usize) -> Option<usize>;
12
13    fn try_negative_to_usize(self, len: usize) -> PolarsResult<usize>
14    where
15        Self: Sized + Copy,
16    {
17        self.negative_to_usize(len)
18            .ok_or_else(|| polars_err!(OutOfBounds: "index {} for length: {}", self, len))
19    }
20}
21
22impl<I> IndexToUsize for I
23where
24    I: PartialOrd + PartialEq + NumCast + Signed + Zero + Display,
25{
26    #[inline]
27    fn negative_to_usize(self, len: usize) -> Option<usize> {
28        if self >= Zero::zero() {
29            if (self.to_usize().unwrap()) < len {
30                Some(self.to_usize().unwrap())
31            } else {
32                None
33            }
34        } else {
35            let subtract = self.abs().to_usize().unwrap();
36            if subtract > len {
37                None
38            } else {
39                Some(len - subtract)
40            }
41        }
42    }
43}
44
45pub fn indexes_to_usizes(idx: &[IdxSize]) -> impl Iterator<Item = usize> + '_ {
46    idx.iter().map(|idx| *idx as usize)
47}
48
49pub type IdxArr = PrimitiveArray<IdxSize>;