Skip to main content

endpoint_libs/libs/
datatable.rs

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