Skip to main content

platform_data/
query.rs

1use beef::lean::Cow;
2use std::{ops::Index, slice::SliceIndex};
3
4#[derive(Clone, Debug, PartialEq, Eq)]
5pub struct Query<'a, T: Clone>(Cow<'a, [T]>);
6
7impl<'a, T: Clone> Query<'a, T> {
8    pub fn new<C>(beef: C) -> Self
9    where
10        C: Into<Cow<'a, [T]>>,
11    {
12        Query(beef.into())
13    }
14
15    #[must_use]
16    pub fn is_empty(&self) -> bool {
17        self.0.is_empty()
18    }
19
20    #[must_use]
21    pub fn len(&self) -> usize {
22        self.0.len()
23    }
24
25    #[must_use]
26    pub fn into_inner(self) -> Cow<'a, [T]> {
27        self.0
28    }
29
30    #[must_use]
31    pub fn into_owned(self) -> Vec<T> {
32        self.0.into_owned()
33    }
34}
35
36impl<I: SliceIndex<[T]>, T: Clone> Index<I> for Query<'_, T> {
37    type Output = I::Output;
38
39    fn index(&self, index: I) -> &Self::Output {
40        self.0.index(index)
41    }
42}
43
44pub trait ToQuery<T: Clone> {
45    fn to_query(&self) -> Query<'_, T>;
46}
47
48impl<T: Clone> ToQuery<T> for Query<'_, T> {
49    fn to_query(&self) -> Query<'_, T> {
50        Query::new(&self[..])
51    }
52}
53
54impl<T: Clone> ToQuery<T> for [T] {
55    fn to_query(&self) -> Query<'_, T> {
56        Query::new(self)
57    }
58}
59
60impl<'a, T: Clone> ToQuery<T> for &'a [T] {
61    fn to_query(&self) -> Query<'a, T> {
62        Query::new(*self)
63    }
64}
65
66impl<T: Clone> ToQuery<T> for Vec<T> {
67    fn to_query(&self) -> Query<'_, T> {
68        Query::new(self.as_slice())
69    }
70}
71
72impl<T: Clone, const L: usize> ToQuery<T> for [T; L] {
73    fn to_query(&self) -> Query<'_, T> {
74        Query::new(self.as_slice())
75    }
76}
77
78#[macro_export]
79macro_rules! query {
80    ($($x:expr),*) => (
81        $crate::ToQuery::to_query(&[$($x),*])
82    );
83}