Skip to main content

polars_ops/chunked_array/list/
get.rs

1use polars_core::prelude::{Column, IdxCa, Int64Chunked, ListChunked};
2use polars_core::series::Series;
3use polars_error::{PolarsResult, polars_bail};
4use polars_utils::IdxSize;
5
6use super::ListNameSpaceImpl;
7use crate::series::convert_and_bound_idx_ca;
8
9pub fn lst_get(ca: &ListChunked, index: &Int64Chunked, null_on_oob: bool) -> PolarsResult<Column> {
10    match index.len() {
11        1 => {
12            let index = index.get(0);
13            if let Some(index) = index {
14                ca.lst_get(index, null_on_oob).map(Column::from)
15            } else {
16                Ok(Column::full_null(
17                    ca.name().clone(),
18                    ca.len(),
19                    ca.inner_dtype(),
20                ))
21            }
22        },
23        len if len == ca.len() => {
24            let tmp = ca.rechunk();
25            let arr = tmp.downcast_as_array();
26            let offsets = arr.offsets().as_slice();
27            let take_by = if ca.null_count() == 0 {
28                index
29                    .iter()
30                    .enumerate()
31                    .map(|(i, opt_idx)| match opt_idx {
32                        Some(idx) => {
33                            let (start, end) = unsafe {
34                                (*offsets.get_unchecked(i), *offsets.get_unchecked(i + 1))
35                            };
36                            let offset = if idx >= 0 {
37                                start.saturating_add(idx)
38                            } else {
39                                end + idx
40                            };
41                            if offset >= end || offset < start || start == end {
42                                if null_on_oob {
43                                    Ok(None)
44                                } else {
45                                    polars_bail!(ComputeError: "get index is out of bounds");
46                                }
47                            } else {
48                                Ok(Some(offset as IdxSize))
49                            }
50                        },
51                        None => Ok(None),
52                    })
53                    .collect::<Result<IdxCa, _>>()?
54            } else {
55                index
56                    .iter()
57                    .zip(arr.validity().unwrap())
58                    .enumerate()
59                    .map(|(i, (opt_idx, valid))| match (valid, opt_idx) {
60                        (true, Some(idx)) => {
61                            let (start, end) = unsafe {
62                                (*offsets.get_unchecked(i), *offsets.get_unchecked(i + 1))
63                            };
64                            let offset = if idx >= 0 {
65                                start.saturating_add(idx)
66                            } else {
67                                end + idx
68                            };
69                            if offset >= end || offset < start || start == end {
70                                if null_on_oob {
71                                    Ok(None)
72                                } else {
73                                    polars_bail!(ComputeError: "get index is out of bounds");
74                                }
75                            } else {
76                                Ok(Some(offset as IdxSize))
77                            }
78                        },
79                        _ => Ok(None),
80                    })
81                    .collect::<Result<IdxCa, _>>()?
82            };
83            let s = Series::try_from((ca.name().clone(), arr.values().clone())).unwrap();
84            unsafe {
85                s.take_unchecked(&take_by)
86                    .from_physical_unchecked(ca.inner_dtype())
87                    .map(Column::from)
88            }
89        },
90        _ if ca.len() == 1 => {
91            if let Some(list) = ca.get(0) {
92                let idx = convert_and_bound_idx_ca(index, list.len(), null_on_oob)?;
93                let s = Series::try_from((ca.name().clone(), vec![list])).unwrap();
94                unsafe {
95                    s.take_unchecked(&idx)
96                        .from_physical_unchecked(ca.inner_dtype())
97                        .map(Column::from)
98                }
99            } else {
100                Ok(Column::full_null(
101                    ca.name().clone(),
102                    index.len(),
103                    ca.inner_dtype(),
104                ))
105            }
106        },
107        len => polars_bail!(
108            ComputeError:
109            "`list.get` expression got an index array of length {} while the list has {} elements",
110            len, ca.len()
111        ),
112    }
113}