Skip to main content

irox_tools/
vec.rs

1// SPDX-License-Identifier: MIT
2// Copyright 2025 IROX Contributors
3//
4
5//!
6//! Bolt-ons for [`Vec`] and [`VecDeque`] - better displays and iteration tools
7
8extern crate alloc;
9use crate::buf::ZeroedBuffer;
10use alloc::boxed::Box;
11use alloc::collections::VecDeque;
12use alloc::string::String;
13use alloc::{vec, vec::Vec};
14use core::fmt::{Display, Formatter, UpperHex, Write};
15
16///
17/// This struct purely exists to implement [`Display`] and [`UpperHex`] for a borrowed Vec, whose elements implement [`Display`] or [`UpperHex`]
18pub struct PrettyVec<'a, T>(pub &'a Vec<T>);
19
20///
21/// This struct purely exists to implement [`Display`] and [`UpperHex`] for a borrowed VecDeque, whose elements implement [`Display`] or [`UpperHex`]
22pub struct PrettyVecDeque<'a, T>(pub &'a VecDeque<T>);
23
24impl<T> Display for PrettyVec<'_, T>
25where
26    T: Display,
27{
28    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
29        let vals: Vec<String> = self.0.iter().map(|f| format!("{f}")).collect();
30        if f.alternate() {
31            f.write_fmt(format_args!("{vals:#?}"))
32        } else {
33            f.write_fmt(format_args!("{vals:?}"))
34        }
35    }
36}
37
38impl<T> UpperHex for PrettyVec<'_, T>
39where
40    T: UpperHex,
41{
42    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
43        let mut buf = String::new();
44        for val in self.0 {
45            buf.write_fmt(format_args!("{val:0X}"))?;
46        }
47        f.write_fmt(format_args!("{buf}"))
48    }
49}
50
51impl<T> UpperHex for PrettyVecDeque<'_, T>
52where
53    T: UpperHex,
54{
55    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
56        let mut buf = String::new();
57        for val in self.0 {
58            buf.write_fmt(format_args!("{val:0X}"))?;
59        }
60        f.write_fmt(format_args!("{buf}"))
61    }
62}
63
64///
65/// The `retain+take` operation is exactly what it sounds like.  Retain only those elements that
66/// match the predicate, but return whole owned copies of the items.  For efficiency's sake, some
67/// implementations *may* iterate backwards through the container.
68pub trait RetainTake<T> {
69    fn retain_take<F>(&mut self, predicate: F) -> Vec<T>
70    where
71        F: FnMut(&T) -> bool;
72}
73
74impl<T> RetainTake<T> for Vec<T> {
75    fn retain_take<F>(&mut self, mut predicate: F) -> Vec<T>
76    where
77        F: FnMut(&T) -> bool,
78    {
79        let mut idx = self.len();
80        let mut out: Vec<T> = Vec::new();
81        loop {
82            idx -= 1;
83            if let Some(elem) = self.get(idx) {
84                if !predicate(elem) {
85                    out.push(self.swap_remove(idx));
86                }
87            }
88            if idx == 0 {
89                break;
90            }
91        }
92        out
93    }
94}
95
96impl<T> RetainTake<T> for VecDeque<T> {
97    fn retain_take<F>(&mut self, mut predicate: F) -> Vec<T>
98    where
99        F: FnMut(&T) -> bool,
100    {
101        let mut idx = self.len();
102        let mut out: Vec<T> = Vec::new();
103        loop {
104            idx -= 1;
105            if let Some(elem) = self.get(idx) {
106                if !predicate(elem) {
107                    if let Some(elem) = self.swap_remove_back(idx) {
108                        out.push(elem);
109                    }
110                }
111            }
112            if idx == 0 {
113                break;
114            }
115        }
116        out
117    }
118}
119
120impl<T: Default + Sized + Copy> ZeroedBuffer for Vec<T> {
121    type Output = Self;
122
123    fn new_zeroed(capacity: usize) -> Self::Output {
124        vec![T::default(); capacity]
125    }
126}
127
128impl<T: Default + Sized + Copy> ZeroedBuffer for VecDeque<T> {
129    type Output = Self;
130
131    fn new_zeroed(capacity: usize) -> Self::Output {
132        VecDeque::from(vec![T::default(); capacity])
133    }
134}
135impl<T: Default + Sized + Copy> ZeroedBuffer for Box<[T]> {
136    type Output = Self;
137
138    fn new_zeroed(capacity: usize) -> Self::Output {
139        let mut vec = Vec::new();
140        vec.resize_with(capacity, Default::default);
141        vec.into_boxed_slice()
142    }
143}