Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
pola-rs
GitHub Repository: pola-rs/polars
Path: blob/main/crates/polars-arrow/src/legacy/index.rs
6939 views
1
use std::fmt::Display;
2
3
use num_traits::{NumCast, Signed, Zero};
4
use polars_error::{PolarsResult, polars_err};
5
use polars_utils::IdxSize;
6
7
use crate::array::PrimitiveArray;
8
9
pub 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
22
impl<I> IndexToUsize for I
23
where
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
45
pub fn indexes_to_usizes(idx: &[IdxSize]) -> impl Iterator<Item = usize> + '_ {
46
idx.iter().map(|idx| *idx as usize)
47
}
48
49
pub type IdxArr = PrimitiveArray<IdxSize>;
50
51