reproto_core/
rp_reg.rs

1//! Model for registered types.
2
3use std::fmt;
4use {Flavor, RpName};
5
6/// Marker for the existence of a registered type of the given kind.
7#[derive(Debug, Clone)]
8pub enum RpReg {
9    Type,
10    Tuple,
11    Interface,
12    SubType,
13    Enum,
14    EnumVariant,
15    Service,
16}
17
18impl RpReg {
19    pub fn ident<PackageFn, InnerFn, F: 'static>(
20        &self,
21        name: &RpName<F>,
22        package_fn: PackageFn,
23        inner_fn: InnerFn,
24    ) -> String
25    where
26        PackageFn: Fn(Vec<&str>) -> String,
27        InnerFn: Fn(Vec<&str>) -> String,
28        F: Flavor,
29    {
30        use self::RpReg::*;
31
32        match *self {
33            Type | Interface | Enum | Tuple | Service => {
34                let p = name.parts.iter().map(String::as_str).collect();
35                package_fn(p)
36            }
37            SubType | EnumVariant => {
38                let mut v: Vec<&str> = name.parts.iter().map(String::as_str).collect();
39                let at = v.len().saturating_sub(2);
40                let last = inner_fn(v.split_off(at));
41
42                let mut parts = v.clone();
43                parts.push(last.as_str());
44
45                inner_fn(parts)
46            }
47        }
48    }
49
50    /// Check if registered type is an enum.
51    pub fn is_enum(&self) -> bool {
52        use self::RpReg::*;
53
54        match *self {
55            Enum => true,
56            _ => false,
57        }
58    }
59}
60
61impl fmt::Display for RpReg {
62    fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
63        use self::RpReg::*;
64
65        match *self {
66            Type => write!(fmt, "type"),
67            Interface => write!(fmt, "interface"),
68            Enum => write!(fmt, "enum"),
69            Tuple => write!(fmt, "tuple"),
70            Service => write!(fmt, "service"),
71            SubType => write!(fmt, "subtype"),
72            EnumVariant => write!(fmt, "variant"),
73        }
74    }
75}