use crate::{
math::{ConstZero, NumberWithMonotoneOps},
prelude::TryIntoPatch,
};
pub fn add_item_to_max_sized_list<T>(
list: &mut Vec<T>,
max_size: usize,
item: T,
) {
list.push(item);
if core::intrinsics::unlikely(list.len() < max_size) {
return;
}
let to_remove = list.len() - max_size;
for _ in 0..to_remove {
list.remove(0);
}
}
#[must_use]
pub fn get_sub_vec_of_vec<T: Copy>(
vec: &[T],
width: usize,
cutout_x: usize,
cutout_y: usize,
cutout_width: usize,
cutout_height: usize,
) -> Vec<T> {
let mut sub_vec: Vec<T> = Vec::new();
for y in cutout_y..cutout_y + cutout_height {
for x in cutout_x..cutout_x + cutout_width {
sub_vec.push(vec[y * width + x]);
}
}
sub_vec
}
pub fn combined<T: Clone + Sized>(vec: &[T], other: T) -> Vec<T> {
let mut new_vec = vec.to_vec();
new_vec.push(other);
new_vec
}
pub fn combined_list<T: Clone + Sized>(vec: &[T], other: &[T]) -> Vec<T> {
let mut new_vec = vec.to_vec();
new_vec.extend_from_slice(other);
new_vec
}
#[must_use]
pub fn combined_contents<T: Clone + Sized>(
vec: Vec<T>,
other: Vec<T>,
) -> Vec<T> {
let mut new = vec;
for i in other {
new.push(i);
}
new
}
#[must_use]
pub fn average<T: ConstZero + Copy + PartialEq + NumberWithMonotoneOps>(
vec: &[T],
) -> Option<T>
where
usize: TryIntoPatch<T>,
{
let len = (vec.len()).try_into_value()?;
if core::intrinsics::unlikely(len == T::ZERO) {
return None;
}
let sum: T = vec.iter().copied().fold(T::ZERO, |a, b| a + b);
Some(sum / len)
}
#[must_use]
pub fn get_difference_new<'a, T: core::cmp::PartialEq>(
old: &'a [T],
new: &'a [T],
) -> Vec<&'a T> {
let mut result = Vec::new();
for i in new {
if !old.contains(i) {
result.push(i);
}
}
result
}
#[must_use]
pub fn get_difference_new_cloned<T: core::cmp::PartialEq + Clone>(
old: &[T],
new: &[T],
) -> Vec<T> {
let mut result = Vec::new();
for i in new {
if !old.contains(i) {
result.push(i.clone());
}
}
result
}
#[must_use]
pub fn has_duplicates<T: core::hash::Hash + Eq>(vec: &Vec<T>) -> bool {
let mut seen = std::collections::HashSet::new();
for item in vec {
if !seen.insert(item) {
return true;
}
}
false
}
pub fn find_in_list<T: core::cmp::PartialEq>(
vec: &[T],
item: &T,
) -> Option<usize> {
vec.iter().position(|x| *x == *item)
}
#[must_use]
pub fn collect_options<T>(vec: Vec<Option<T>>) -> Option<Vec<T>> {
vec.into_iter().collect()
}