Skip to main content

bevy_enhanced_input/
smallvec_template.rs

1use std::vec::Vec;
2
3use bevy::ecs::{
4    error::Result,
5    template::{Template, TemplateContext},
6};
7use smallvec::{Array, SmallVec};
8
9/// Like [`VecTemplate`](bevy::ecs::template::VecTemplate), but for [`SmallVec`].
10///
11/// Can be constructed from arrays, vectors, and small vectors whose elements convert into `T`.
12#[derive(Debug)]
13pub struct SmallVecTemplate<T, const N: usize>(pub SmallVec<[T; N]>)
14where
15    [T; N]: Array<Item = T>;
16
17impl<T, const N: usize> Default for SmallVecTemplate<T, N>
18where
19    [T; N]: Array<Item = T>,
20{
21    fn default() -> Self {
22        Self(SmallVec::new())
23    }
24}
25
26impl<T, const N: usize> Template for SmallVecTemplate<T, N>
27where
28    T: Template,
29    [T; N]: Array<Item = T>,
30    [T::Output; N]: Array<Item = T::Output>,
31{
32    type Output = SmallVec<[T::Output; N]>;
33
34    fn build_template(&self, context: &mut TemplateContext) -> Result<Self::Output> {
35        self.0
36            .iter()
37            .map(|template| template.build_template(context))
38            .collect()
39    }
40
41    fn clone_template(&self) -> Self {
42        Self(self.0.iter().map(Template::clone_template).collect())
43    }
44}
45
46impl<T, U, const N: usize, const M: usize> From<[U; M]> for SmallVecTemplate<T, N>
47where
48    U: Into<T>,
49    [T; N]: Array<Item = T>,
50{
51    fn from(values: [U; M]) -> Self {
52        Self(values.into_iter().map(Into::into).collect())
53    }
54}
55
56impl<T, U, const N: usize> From<Vec<U>> for SmallVecTemplate<T, N>
57where
58    U: Into<T>,
59    [T; N]: Array<Item = T>,
60{
61    fn from(values: Vec<U>) -> Self {
62        Self(values.into_iter().map(Into::into).collect())
63    }
64}
65
66impl<T, A, const N: usize> From<SmallVec<A>> for SmallVecTemplate<T, N>
67where
68    A: Array,
69    A::Item: Into<T>,
70    [T; N]: Array<Item = T>,
71{
72    fn from(values: SmallVec<A>) -> Self {
73        Self(values.into_iter().map(Into::into).collect())
74    }
75}