Skip to main content

surfer_translation_types/
scope_ref.rs

1use serde::{Deserialize, Serialize};
2use std::fmt::{Display, Formatter};
3use std::hash::{Hash, Hasher};
4
5#[derive(Clone, Debug, Eq, Serialize, Deserialize, Default)]
6pub struct ScopeRef<ScopeId> {
7    pub strs: Vec<String>,
8    /// Backend specific numeric ID.
9    ///
10    /// Performance optimization.
11    pub id: ScopeId,
12}
13
14impl<ScopeId1> ScopeRef<ScopeId1> {
15    pub fn map_id<ScopeId2>(
16        self,
17        mut scope_fn: impl FnMut(ScopeId1) -> ScopeId2,
18    ) -> ScopeRef<ScopeId2> {
19        ScopeRef {
20            strs: self.strs,
21            id: scope_fn(self.id),
22        }
23    }
24}
25
26impl<ScopeId> AsRef<ScopeRef<ScopeId>> for ScopeRef<ScopeId> {
27    fn as_ref(&self) -> &ScopeRef<ScopeId> {
28        self
29    }
30}
31
32impl<ScopeId> Hash for ScopeRef<ScopeId> {
33    fn hash<H: Hasher>(&self, state: &mut H) {
34        // id is intentionally not hashed, since it is only a performance hint
35        self.strs.hash(state);
36    }
37}
38
39impl<ScopeId> PartialEq for ScopeRef<ScopeId> {
40    fn eq(&self, other: &Self) -> bool {
41        // id is intentionally not compared, since it is only a performance hint
42        self.strs.eq(&other.strs)
43    }
44}
45
46impl<ScopeId> Display for ScopeRef<ScopeId> {
47    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
48        write!(f, "{}", self.strs.join("."))
49    }
50}