bevy_reflect/
type_info_stack.rs

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
use crate::TypeInfo;
use core::{
    fmt::{Debug, Formatter},
    slice::Iter,
};

/// Helper struct for managing a stack of [`TypeInfo`] instances.
///
/// This is useful for tracking the type hierarchy when serializing and deserializing types.
#[derive(Default, Clone)]
pub(crate) struct TypeInfoStack {
    stack: Vec<&'static TypeInfo>,
}

impl TypeInfoStack {
    /// Create a new empty [`TypeInfoStack`].
    pub const fn new() -> Self {
        Self { stack: Vec::new() }
    }

    /// Push a new [`TypeInfo`] onto the stack.
    pub fn push(&mut self, type_info: &'static TypeInfo) {
        self.stack.push(type_info);
    }

    /// Pop the last [`TypeInfo`] off the stack.
    pub fn pop(&mut self) {
        self.stack.pop();
    }

    /// Get an iterator over the stack in the order they were pushed.
    pub fn iter(&self) -> Iter<&'static TypeInfo> {
        self.stack.iter()
    }
}

impl Debug for TypeInfoStack {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        let mut iter = self.iter();

        if let Some(first) = iter.next() {
            write!(f, "`{}`", first.type_path())?;
        }

        for info in iter {
            write!(f, " -> `{}`", info.type_path())?;
        }

        Ok(())
    }
}