Skip to main content

endpoint_libs/libs/
datatable.rs

1use alloc::vec::{self, Vec};
2use core::future::Future;
3
4#[cfg(not(any(feature = "std", feature = "std-deps")))]
5use crate::eyre::Result;
6#[cfg(any(feature = "std", feature = "std-deps"))]
7use eyre::Result;
8use serde::*;
9
10#[derive(Serialize, Deserialize, Debug, Clone)]
11pub struct RDataTable<T> {
12    rows: Vec<T>,
13}
14
15impl<T> IntoIterator for RDataTable<T> {
16    type Item = T;
17    type IntoIter = vec::IntoIter<T>;
18
19    fn into_iter(self) -> Self::IntoIter {
20        self.rows.into_iter()
21    }
22}
23impl<T> RDataTable<T> {
24    pub fn with_capacity(capacity: usize) -> Self {
25        Self {
26            rows: Vec::with_capacity(capacity),
27        }
28    }
29    pub fn first<R>(&self, f: impl Fn(&T) -> R) -> Option<R> {
30        self.rows.first().map(f)
31    }
32    pub fn rows(&self) -> &Vec<T> {
33        &self.rows
34    }
35    pub fn into_rows(self) -> Vec<T> {
36        self.rows
37    }
38    pub fn iter(&self) -> impl Iterator<Item = &T> {
39        self.rows.iter()
40    }
41    pub fn len(&self) -> usize {
42        self.rows.len()
43    }
44    pub fn is_empty(&self) -> bool {
45        self.rows.is_empty()
46    }
47    pub fn into_result(self) -> Option<T> {
48        self.rows.into_iter().next()
49    }
50    pub fn push(&mut self, row: T) {
51        self.rows.push(row);
52    }
53    pub fn map<R>(self, f: impl Fn(T) -> R) -> Vec<R> {
54        self.rows.into_iter().map(f).collect()
55    }
56    pub async fn map_async<R, F: Future<Output = Result<R>>>(
57        self,
58        f: impl Fn(T) -> F,
59    ) -> Result<Vec<R>> {
60        let mut futures = Vec::with_capacity(self.rows.len());
61        for row in self.rows {
62            futures.push(f(row).await?);
63        }
64        Ok(futures)
65    }
66}