Skip to main content

zlink_idl/type/
type_ref.rs

1use super::Type;
2use alloc::boxed::Box;
3use core::{fmt, ops::Deref};
4
5/// A type reference that can be either borrowed or owned.
6#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct TypeRef<'a>(TypeRefInner<'a>);
8
9impl<'a> TypeRef<'a> {
10    /// Creates a new type reference with a borrowed type reference.
11    pub const fn new(inner: &'a Type<'a>) -> Self {
12        Self(TypeRefInner::Borrowed(inner))
13    }
14
15    /// Creates a new type reference with an owned type.
16    pub fn new_owned(inner: Type<'a>) -> Self {
17        Self(TypeRefInner::Owned(Box::new(inner)))
18    }
19
20    /// Returns a reference to the inner type.
21    pub const fn inner(&self) -> &Type<'a> {
22        self.0.ty()
23    }
24}
25
26impl<'a> Deref for TypeRef<'a> {
27    type Target = Type<'a>;
28
29    fn deref(&self) -> &Self::Target {
30        self.inner()
31    }
32}
33
34impl<'a> fmt::Display for TypeRef<'a> {
35    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
36        write!(f, "{}", self.inner())
37    }
38}
39
40impl<'a> PartialEq<Type<'a>> for TypeRef<'a> {
41    fn eq(&self, other: &Type<'a>) -> bool {
42        self.inner() == other
43    }
44}
45
46#[derive(Debug, Clone, Eq)]
47enum TypeRefInner<'a> {
48    Borrowed(&'a Type<'a>),
49    Owned(Box<Type<'a>>),
50}
51
52impl<'a> TypeRefInner<'a> {
53    /// A reference to the inner type.
54    const fn ty(&self) -> &Type<'a> {
55        match self {
56            TypeRefInner::Borrowed(inner) => inner,
57            TypeRefInner::Owned(inner) => inner,
58        }
59    }
60}
61
62impl PartialEq for TypeRefInner<'_> {
63    fn eq(&self, other: &Self) -> bool {
64        let ty = self.ty();
65        let other_ty = other.ty();
66
67        ty.eq(other_ty)
68    }
69}