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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
use core::fmt;
use core::ops::Deref;
use core::str::FromStr;

use prost::Message;

pub trait Pack: Default + Message + Sized {
    const COLLECTION: Collection;

    fn pack(&self) -> Vec<u8> {
        self.encode_to_vec()
    }

    fn set_id(&mut self, id: Vec<u8>);

    fn id(&self) -> &[u8];
}

#[derive(Debug, Copy, Clone, PartialEq)]
pub enum Collection {
    Accounts,
    AccountSets,
    RoleBindings,
    Roles,
    Banks,
}

impl Deref for Collection {
    type Target = str;

    fn deref(&self) -> &Self::Target {
        match self {
            Collection::Accounts => "accounts",
            Collection::AccountSets => "account-sets",
            Collection::RoleBindings => "role-bindings",
            Collection::Roles => "roles",
            Collection::Banks => "banks",
        }
    }
}

impl fmt::Display for Collection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&**self)
    }
}

impl From<Collection> for String {
    fn from(collection: Collection) -> Self {
        collection.to_string()
    }
}

impl FromStr for Collection {
    type Err = UnsupportedCollection;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "accounts" => Ok(Collection::Accounts),
            "account-sets" => Ok(Collection::AccountSets),
            "role-bindings" => Ok(Collection::RoleBindings),
            "roles" => Ok(Collection::Roles),
            "banks" => Ok(Collection::Banks),
            _unsupported => Err(UnsupportedCollection()),
        }
    }
}

#[derive(Debug)]
pub struct UnsupportedCollection();

impl fmt::Display for UnsupportedCollection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str("unsupported collection")
    }
}

impl std::error::Error for UnsupportedCollection {}