Struct polars_core::utils::NoNull
source · pub struct NoNull<T> { /* private fields */ }Expand description
Just a wrapper structure. Useful for certain impl specializations
This is for instance use to implement
impl<T> FromIterator<T::Native> for NoNull<ChunkedArray<T>>
as Option<T::Native> was already implemented:
impl<T> FromIterator<Option<T::Native>> for ChunkedArray<T>
Implementations§
source§impl<T> NoNull<T>
impl<T> NoNull<T>
sourcepub fn new(inner: T) -> Self
pub fn new(inner: T) -> Self
Examples found in repository?
src/chunked_array/upstream_traits.rs (line 78)
75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401
fn from_iter<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
// 2021-02-07: aligned vec was ~2x faster than arrow collect.
let av = iter.into_iter().collect::<Vec<T::Native>>();
NoNull::new(ChunkedArray::from_vec("", av))
}
}
impl FromIterator<Option<bool>> for ChunkedArray<BooleanType> {
fn from_iter<I: IntoIterator<Item = Option<bool>>>(iter: I) -> Self {
let arr = BooleanArray::from_iter(iter);
Self::from_chunks("", vec![Box::new(arr)])
}
}
impl FromIterator<bool> for BooleanChunked {
fn from_iter<I: IntoIterator<Item = bool>>(iter: I) -> Self {
// 2021-02-07: this was ~70% faster than with the builder, even with the extra Option<T> added.
let arr = BooleanArray::from_iter(iter.into_iter().map(Some));
Self::from_chunks("", vec![Box::new(arr)])
}
}
impl FromIterator<bool> for NoNull<BooleanChunked> {
fn from_iter<I: IntoIterator<Item = bool>>(iter: I) -> Self {
let ca = iter.into_iter().collect::<BooleanChunked>();
NoNull::new(ca)
}
}
// FromIterator for Utf8Chunked variants.
impl<Ptr> FromIterator<Option<Ptr>> for Utf8Chunked
where
Ptr: AsRef<str>,
{
fn from_iter<I: IntoIterator<Item = Option<Ptr>>>(iter: I) -> Self {
let arr = Utf8Array::<i64>::from_iter(iter);
Self::from_chunks("", vec![Box::new(arr)])
}
}
/// Local AsRef<T> trait to circumvent the orphan rule.
pub trait PolarsAsRef<T: ?Sized>: AsRef<T> {}
impl PolarsAsRef<str> for String {}
impl PolarsAsRef<str> for &str {}
// &["foo", "bar"]
impl PolarsAsRef<str> for &&str {}
impl<'a> PolarsAsRef<str> for Cow<'a, str> {}
impl<Ptr> FromIterator<Ptr> for Utf8Chunked
where
Ptr: PolarsAsRef<str>,
{
fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
let arr = Utf8Array::<i64>::from_iter_values(iter.into_iter());
Self::from_chunks("", vec![Box::new(arr)])
}
}
// FromIterator for BinaryChunked variants.
#[cfg(feature = "dtype-binary")]
impl<Ptr> FromIterator<Option<Ptr>> for BinaryChunked
where
Ptr: AsRef<[u8]>,
{
fn from_iter<I: IntoIterator<Item = Option<Ptr>>>(iter: I) -> Self {
let arr = BinaryArray::<i64>::from_iter(iter);
Self::from_chunks("", vec![Box::new(arr)])
}
}
#[cfg(feature = "dtype-binary")]
impl PolarsAsRef<[u8]> for Vec<u8> {}
#[cfg(feature = "dtype-binary")]
impl PolarsAsRef<[u8]> for &[u8] {}
#[cfg(feature = "dtype-binary")]
impl PolarsAsRef<[u8]> for &&[u8] {}
#[cfg(feature = "dtype-binary")]
impl<'a> PolarsAsRef<[u8]> for Cow<'a, [u8]> {}
#[cfg(feature = "dtype-binary")]
impl<Ptr> FromIterator<Ptr> for BinaryChunked
where
Ptr: PolarsAsRef<[u8]>,
{
fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
let arr = BinaryArray::<i64>::from_iter_values(iter.into_iter());
Self::from_chunks("", vec![Box::new(arr)])
}
}
impl<Ptr> FromIterator<Ptr> for ListChunked
where
Ptr: Borrow<Series>,
{
fn from_iter<I: IntoIterator<Item = Ptr>>(iter: I) -> Self {
let mut it = iter.into_iter();
let capacity = get_iter_capacity(&it);
// first take one to get the dtype.
let v = match it.next() {
Some(v) => v,
None => return ListChunked::full_null("", 0),
};
// We don't know the needed capacity. We arbitrarily choose an average of 5 elements per series.
let mut builder =
get_list_builder(v.borrow().dtype(), capacity * 5, capacity, "collected").unwrap();
builder.append_series(v.borrow());
for s in it {
builder.append_series(s.borrow());
}
builder.finish()
}
}
impl FromIterator<Option<Series>> for ListChunked {
fn from_iter<I: IntoIterator<Item = Option<Series>>>(iter: I) -> Self {
let mut it = iter.into_iter();
let capacity = get_iter_capacity(&it);
// get first non None from iter
let first_value;
let mut init_null_count = 0;
loop {
match it.next() {
Some(Some(s)) => {
first_value = Some(s);
break;
}
Some(None) => {
init_null_count += 1;
}
None => return ListChunked::full_null("", 0),
}
}
match first_value {
None => {
// already returned full_null above
unreachable!()
}
Some(ref first_s) => {
// AnyValues with empty lists in python can create
// Series of an unknown dtype.
// We use the anonymousbuilder without a dtype
// the empty arrays is then not added (we add an extra offset instead)
// the next non-empty series then must have the correct dtype.
if matches!(first_s.dtype(), DataType::Null) && first_s.is_empty() {
let mut builder = AnonymousOwnedListBuilder::new("collected", capacity, None);
for _ in 0..init_null_count {
builder.append_null();
}
builder.append_empty();
for opt_s in it {
builder.append_opt_series(opt_s.as_ref());
}
builder.finish()
} else {
match first_s.dtype() {
#[cfg(feature = "object")]
DataType::Object(_) => {
let mut builder =
first_s.get_list_builder("collected", capacity * 5, capacity);
for _ in 0..init_null_count {
builder.append_null();
}
builder.append_series(first_s);
for opt_s in it {
builder.append_opt_series(opt_s.as_ref());
}
builder.finish()
}
_ => {
// We don't know the needed capacity. We arbitrarily choose an average of 5 elements per series.
let mut builder = get_list_builder(
first_s.dtype(),
capacity * 5,
capacity,
"collected",
)
.unwrap();
for _ in 0..init_null_count {
builder.append_null();
}
builder.append_series(first_s);
for opt_s in it {
builder.append_opt_series(opt_s.as_ref());
}
builder.finish()
}
}
}
}
}
}
}
impl FromIterator<Option<Box<dyn Array>>> for ListChunked {
fn from_iter<I: IntoIterator<Item = Option<Box<dyn Array>>>>(iter: I) -> Self {
let mut cap = 0;
let mut dtype: Option<DataType> = None;
let vals = iter
.into_iter()
.map(|opt_arr| {
opt_arr.map(|arr| {
if dtype.is_none() {
dtype = Some(arr.data_type().into());
}
cap += arr.len();
arr
})
})
.collect::<Vec<_>>();
let mut builder = AnonymousListBuilder::new("collected", cap, None);
for val in &vals {
builder.append_opt_array(val.as_deref());
}
builder.finish()
}
}
#[cfg(feature = "object")]
impl<T: PolarsObject> FromIterator<Option<T>> for ObjectChunked<T> {
fn from_iter<I: IntoIterator<Item = Option<T>>>(iter: I) -> Self {
use arrow::bitmap::{Bitmap, MutableBitmap};
let iter = iter.into_iter();
let size = iter.size_hint().0;
let mut null_mask_builder = MutableBitmap::with_capacity(size);
let values: Vec<T> = iter
.map(|value| match value {
Some(value) => {
null_mask_builder.push(true);
value
}
None => {
null_mask_builder.push(false);
T::default()
}
})
.collect();
let null_bit_buffer: Option<Bitmap> = null_mask_builder.into();
let null_bitmap = null_bit_buffer;
let len = values.len();
let arr = Box::new(ObjectArray {
values: Arc::new(values),
null_bitmap,
offset: 0,
len,
});
let mut out = ChunkedArray {
field: Arc::new(Field::new("", DataType::Object(T::type_name()))),
chunks: vec![arr],
phantom: PhantomData,
bit_settings: Default::default(),
length: 0,
};
out.compute_len();
out
}
}
/// FromParallelIterator trait
// Code taken from https://docs.rs/rayon/1.3.1/src/rayon/iter/extend.rs.html#356-366
fn vec_push<T>(mut vec: Vec<T>, elem: T) -> Vec<T> {
vec.push(elem);
vec
}
fn as_list<T>(item: T) -> LinkedList<T> {
let mut list = LinkedList::new();
list.push_back(item);
list
}
fn list_append<T>(mut list1: LinkedList<T>, mut list2: LinkedList<T>) -> LinkedList<T> {
list1.append(&mut list2);
list1
}
fn collect_into_linked_list<I>(par_iter: I) -> LinkedList<Vec<I::Item>>
where
I: IntoParallelIterator,
{
let it = par_iter.into_par_iter();
// be careful optimizing allocations. Its hard to figure out the size
// needed
// https://github.com/pola-rs/polars/issues/1562
it.fold(Vec::new, vec_push)
.map(as_list)
.reduce(LinkedList::new, list_append)
}
fn get_capacity_from_par_results<T>(ll: &LinkedList<Vec<T>>) -> usize {
ll.iter().map(|list| list.len()).sum()
}
impl<T> FromParallelIterator<T::Native> for NoNull<ChunkedArray<T>>
where
T: PolarsNumericType,
{
fn from_par_iter<I: IntoParallelIterator<Item = T::Native>>(iter: I) -> Self {
// Get linkedlist filled with different vec result from different threads
let vectors = collect_into_linked_list(iter);
let capacity: usize = get_capacity_from_par_results(&vectors);
let mut av = Vec::<T::Native>::with_capacity(capacity);
for v in vectors {
av.extend_from_slice(&v)
}
let arr = to_array::<T>(av, None);
NoNull::new(ChunkedArray::from_chunks("", vec![arr]))
}More examples
src/chunked_array/trusted_len.rs (line 37)
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 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135
fn from_iter_trusted_length<I: IntoIterator<Item = T::Native>>(iter: I) -> Self {
let iter = iter.into_iter();
let values = unsafe { Vec::from_trusted_len_iter_unchecked(iter) }.into();
let arr = PrimitiveArray::new(T::get_dtype().to_arrow(), values, None);
NoNull::new(ChunkedArray::from_chunks("", vec![Box::new(arr)]))
}
}
impl<T> FromIteratorReversed<Option<T::Native>> for ChunkedArray<T>
where
T: PolarsNumericType,
{
fn from_trusted_len_iter_rev<I: TrustedLen<Item = Option<T::Native>>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let mut vals: Vec<T::Native> = Vec::with_capacity(size);
let mut validity = MutableBitmap::with_capacity(size);
validity.extend_constant(size, true);
let validity_ptr = validity.as_slice().as_ptr() as *mut u8;
unsafe {
// set to end of buffer
let mut ptr = vals.as_mut_ptr().add(size);
let mut offset = size;
iter.for_each(|opt_item| {
offset -= 1;
ptr = ptr.sub(1);
match opt_item {
Some(item) => {
std::ptr::write(ptr, item);
}
None => {
std::ptr::write(ptr, T::Native::default());
unset_bit_raw(validity_ptr, offset)
}
}
});
vals.set_len(size)
}
let arr = PrimitiveArray::new(
T::get_dtype().to_arrow(),
vals.into(),
Some(validity.into()),
);
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
impl FromIteratorReversed<Option<bool>> for BooleanChunked {
fn from_trusted_len_iter_rev<I: TrustedLen<Item = Option<bool>>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let vals = MutableBitmap::from_len_zeroed(size);
let mut validity = MutableBitmap::with_capacity(size);
validity.extend_constant(size, true);
let validity_ptr = validity.as_slice().as_ptr() as *mut u8;
let vals_ptr = vals.as_slice().as_ptr() as *mut u8;
unsafe {
let mut offset = size;
iter.for_each(|opt_item| {
offset -= 1;
match opt_item {
Some(item) => {
if item {
// set value
// validity bit is already true
set_bit_raw(vals_ptr, offset);
}
}
None => {
// unset validity bit
unset_bit_raw(validity_ptr, offset)
}
}
});
}
let arr = BooleanArray::new(ArrowDataType::Boolean, vals.into(), Some(validity.into()));
ChunkedArray::from_chunks("", vec![Box::new(arr)])
}
}
impl<T> FromIteratorReversed<T::Native> for NoNull<ChunkedArray<T>>
where
T: PolarsNumericType,
{
fn from_trusted_len_iter_rev<I: TrustedLen<Item = T::Native>>(iter: I) -> Self {
let size = iter.size_hint().1.unwrap();
let mut vals: Vec<T::Native> = Vec::with_capacity(size);
unsafe {
// set to end of buffer
let mut ptr = vals.as_mut_ptr().add(size);
iter.for_each(|item| {
ptr = ptr.sub(1);
std::ptr::write(ptr, item);
});
vals.set_len(size)
}
let arr = PrimitiveArray::new(T::get_dtype().to_arrow(), vals.into(), None);
NoNull::new(ChunkedArray::from_chunks("", vec![Box::new(arr)]))
}sourcepub fn into_inner(self) -> T
pub fn into_inner(self) -> T
Examples found in repository?
More examples
src/frame/cross_join.rs (line 27)
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
fn inner(offset: IdxSize, total_rows: IdxSize, n_rows_right: IdxSize) -> IdxCa {
let mut take: NoNull<IdxCa> = (offset..total_rows)
.map(|i| i / n_rows_right)
.collect_trusted();
take.set_sorted2(IsSorted::Ascending);
take.into_inner()
}
slice_take(total_rows, n_rows_right, slice, inner)
}
fn take_right(total_rows: IdxSize, n_rows_right: IdxSize, slice: Option<(i64, usize)>) -> IdxCa {
fn inner(offset: IdxSize, total_rows: IdxSize, n_rows_right: IdxSize) -> IdxCa {
let take: NoNull<IdxCa> = (offset..total_rows)
.map(|i| i % n_rows_right)
.collect_trusted();
take.into_inner()
}src/series/ops/unique.rs (line 26)
12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
fn unique_counts<I, J>(items: I) -> IdxCa
where
I: Iterator<Item = J>,
J: Hash + Eq,
{
let mut map = PlIndexMap::with_capacity_and_hasher(HASHMAP_INIT_SIZE, Default::default());
for item in items {
map.entry(item)
.and_modify(|cnt| {
*cnt += 1;
})
.or_insert(1 as IdxSize);
}
let out: NoNull<IdxCa> = map.into_values().collect();
out.into_inner()
}src/frame/groupby/proxy.rs (line 254)
246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363
pub fn group_lengths(&self, name: &str) -> IdxCa {
let ca: NoNull<IdxCa> = match self {
GroupsProxy::Idx(groups) => groups
.iter()
.map(|(_, groups)| groups.len() as IdxSize)
.collect_trusted(),
GroupsProxy::Slice { groups, .. } => groups.iter().map(|g| g[1]).collect_trusted(),
};
let mut ca = ca.into_inner();
ca.rename(name);
ca
}
pub fn take_group_firsts(self) -> Vec<IdxSize> {
match self {
GroupsProxy::Idx(mut groups) => std::mem::take(&mut groups.first),
GroupsProxy::Slice { groups, .. } => {
groups.into_iter().map(|[first, _len]| first).collect()
}
}
}
#[cfg(feature = "private")]
pub fn par_iter(&self) -> GroupsProxyParIter {
GroupsProxyParIter::new(self)
}
/// Get a reference to the `GroupsIdx`.
///
/// # Panic
///
/// panics if the groups are a slice.
pub fn unwrap_idx(&self) -> &GroupsIdx {
match self {
GroupsProxy::Idx(groups) => groups,
GroupsProxy::Slice { .. } => panic!("groups are slices not index"),
}
}
/// Get a reference to the `GroupsSlice`.
///
/// # Panic
///
/// panics if the groups are an idx.
pub fn unwrap_slice(&self) -> &GroupsSlice {
match self {
GroupsProxy::Slice { groups, .. } => groups,
GroupsProxy::Idx(_) => panic!("groups are index not slices"),
}
}
pub fn get(&self, index: usize) -> GroupsIndicator {
match self {
GroupsProxy::Idx(groups) => {
let first = groups.first[index];
let all = &groups.all[index];
GroupsIndicator::Idx((first, all))
}
GroupsProxy::Slice { groups, .. } => GroupsIndicator::Slice(groups[index]),
}
}
/// Get a mutable reference to the `GroupsIdx`.
///
/// # Panic
///
/// panics if the groups are a slice.
pub fn idx_mut(&mut self) -> &mut GroupsIdx {
match self {
GroupsProxy::Idx(groups) => groups,
GroupsProxy::Slice { .. } => panic!("groups are slices not index"),
}
}
pub fn len(&self) -> usize {
match self {
GroupsProxy::Idx(groups) => groups.len(),
GroupsProxy::Slice { groups, .. } => groups.len(),
}
}
pub fn is_empty(&self) -> bool {
self.len() == 0
}
pub fn group_count(&self) -> IdxCa {
match self {
GroupsProxy::Idx(groups) => {
let ca: NoNull<IdxCa> = groups
.iter()
.map(|(_first, idx)| idx.len() as IdxSize)
.collect_trusted();
ca.into_inner()
}
GroupsProxy::Slice { groups, .. } => {
let ca: NoNull<IdxCa> = groups.iter().map(|[_first, len]| *len).collect_trusted();
ca.into_inner()
}
}
}
pub fn as_list_chunked(&self) -> ListChunked {
match self {
GroupsProxy::Idx(groups) => groups
.iter()
.map(|(_first, idx)| {
let ca: NoNull<IdxCa> = idx.iter().map(|&v| v as IdxSize).collect();
ca.into_inner().into_series()
})
.collect_trusted(),
GroupsProxy::Slice { groups, .. } => groups
.iter()
.map(|&[first, len]| {
let ca: NoNull<IdxCa> = (first..first + len).collect_trusted();
ca.into_inner().into_series()
})
.collect_trusted(),
}
}Additional examples can be found in:
Trait Implementations§
source§impl<T> FromIterator<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
impl<T> FromIterator<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
source§impl FromIterator<bool> for NoNull<BooleanChunked>
impl FromIterator<bool> for NoNull<BooleanChunked>
source§impl<T> FromIteratorReversed<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
impl<T> FromIteratorReversed<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
fn from_trusted_len_iter_rev<I: TrustedLen<Item = T::Native>>(iter: I) -> Self
source§impl<T> FromParallelIterator<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
impl<T> FromParallelIterator<<T as PolarsNumericType>::Native> for NoNull<ChunkedArray<T>>where
T: PolarsNumericType,
source§fn from_par_iter<I: IntoParallelIterator<Item = T::Native>>(iter: I) -> Self
fn from_par_iter<I: IntoParallelIterator<Item = T::Native>>(iter: I) -> Self
Creates an instance of the collection from the parallel iterator
par_iter. Read more