1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
use alloc::vec::Vec;
use atomic_refcell::AtomicRef;

use crate::{
    filter::All,
    system::{Access, AsBorrowed, SystemAccess, SystemContext, SystemData},
    Fetch, Planar, Query, World,
};

use super::QueryStrategy;

impl<Q, F, S> SystemAccess for Query<Q, F, S>
where
    Q: 'static + for<'x> Fetch<'x>,
    F: 'static + for<'x> Fetch<'x>,
    S: for<'x> QueryStrategy<'x, Q, F>,
{
    fn access(&self, world: &World, dst: &mut Vec<Access>) {
        self.strategy.access(world, &self.fetch, dst);
    }
}

/// Combined reference to a query and a world.
///
/// Allow for executing a query inside a system without violating access rules.
pub struct QueryData<'a, Q, F = All, S = Planar>
where
    Q: for<'x> Fetch<'x> + 'static,
    F: for<'x> Fetch<'x> + 'static,
{
    world: AtomicRef<'a, World>,
    query: &'a mut Query<Q, F, S>,
}

impl<'a, Q, F, S> SystemData<'a> for Query<Q, F, S>
where
    Q: 'static + for<'x> Fetch<'x>,
    F: 'static + for<'x> Fetch<'x>,
    S: 'static + for<'x> QueryStrategy<'x, Q, F>,
{
    type Value = QueryData<'a, Q, F, S>;

    fn acquire(&'a mut self, ctx: &'a SystemContext<'_, '_, '_>) -> Self::Value {
        let world = ctx.world();

        QueryData { world, query: self }
    }

    fn describe(&self, f: &mut alloc::fmt::Formatter<'_>) -> alloc::fmt::Result {
        f.write_str("Query<")?;
        self.fetch.describe(f)?;
        f.write_str(", ")?;
        f.write_str(&tynm::type_name::<S>())?;
        f.write_str(">")
    }
}

impl<'a, Q, F, S> QueryData<'a, Q, F, S>
where
    Q: for<'x> Fetch<'x>,
    F: for<'x> Fetch<'x>,
    S: for<'x> QueryStrategy<'x, Q, F>,
{
    /// Prepare the query.
    ///
    /// This will borrow all required archetypes for the duration of the
    /// `PreparedQuery`.
    ///
    /// The same query can be prepared multiple times, though not
    /// simultaneously.
    pub fn borrow(&mut self) -> <S as QueryStrategy<Q, F>>::Borrow {
        self.query.borrow(&self.world)
    }
}

impl<'a, 'w, Q, F, S> AsBorrowed<'a> for QueryData<'w, Q, F, S>
where
    Q: for<'x> Fetch<'x> + 'static,
    F: for<'x> Fetch<'x> + 'static,
    S: for<'x> QueryStrategy<'x, Q, F>,
    <S as QueryStrategy<'a, Q, F>>::Borrow: 'a,
{
    type Borrowed = <S as QueryStrategy<'a, Q, F>>::Borrow;

    fn as_borrowed(&'a mut self) -> Self::Borrowed {
        self.borrow()
    }
}