kodept_ast/graph/
identity.rs

1#![allow(clippy::needless_lifetimes)]
2
3use std::any::type_name;
4use std::fmt::Debug;
5use std::iter::{Once, once};
6use std::ops::{Deref, DerefMut};
7
8use crate::graph::nodes::Inaccessible;
9use crate::graph::utils::{FromOptVec, OptVec, RefMut};
10
11#[repr(transparent)]
12pub struct Identity<T>(pub T);
13
14impl<T> IntoIterator for Identity<T> {
15    type Item = T;
16    type IntoIter = Once<T>;
17
18    fn into_iter(self) -> Self::IntoIter {
19        once(self.0)
20    }
21}
22
23impl<T> Deref for Identity<T> {
24    type Target = T;
25
26    fn deref(&self) -> &Self::Target {
27        &self.0
28    }
29}
30
31impl<T> DerefMut for Identity<T> {
32    fn deref_mut(&mut self) -> &mut Self::Target {
33        &mut self.0
34    }
35}
36
37impl<T: Debug> FromOptVec for Identity<T> {
38    type Ref<'a> = &'a T where Self::T: 'a;
39    type Mut<'a> = RefMut<'a, T>;
40    type T = T;
41
42    fn unwrap<'a>(value: OptVec<&'a Self::T>) -> Self::Ref<'a> {
43        match value.as_slice() {
44            [x] => x,
45            _ => panic!(
46                "Container must has only one child <{}>, but has {:?}",
47                type_name::<T>(),
48                value
49            ),
50        }
51    }
52
53    fn unwrap_mut<'a>(value: OptVec<&'a Inaccessible>) -> Self::Mut<'a> {
54        match value.as_slice() {
55            [x] => RefMut::new(x),
56            _ => panic!(
57                "Container must has only one child <{}>, but has {:?}",
58                type_name::<T>(),
59                value
60            ),
61        }
62    }
63}