1use crate::serializer::Serializer;
2use hashbrown::HashMap;
3use prettytable::{row, Table};
4use std::fmt::{Display, Formatter};
5use std::rc::Rc;
6
7#[derive(Default)]
9pub struct Classes {
10 pub(crate) classes_vec: Vec<Rc<Class>>,
11 pub(crate) classes_by_name: HashMap<Box<str>, Rc<Class>>,
12 pub(crate) class_id_size: u32,
13}
14
15#[derive(thiserror::Error, Debug)]
16pub enum ClassError {
17 #[error("Class not found for the given id {0}")]
18 ClassNotFoundById(i32),
19
20 #[error("Class not found for the given name {0}")]
21 ClassNotFoundByName(String),
22}
23
24impl Classes {
25 pub(crate) fn get_by_id_rc(&self, id: usize) -> &Rc<Class> {
26 &self.classes_vec[id]
27 }
28
29 pub fn iter(&self) -> impl Iterator<Item = &Class> {
31 self.classes_vec.iter().map(|class| class.as_ref())
32 }
33
34 pub fn get_by_id(&self, id: usize) -> Result<&Class, ClassError> {
36 self.classes_vec
37 .get(id)
38 .ok_or(ClassError::ClassNotFoundById(id as i32))
39 .map(|class| class.as_ref())
40 }
41
42 pub fn get_by_name(&self, name: &str) -> Result<&Class, ClassError> {
44 self.classes_by_name
45 .get(name)
46 .ok_or_else(|| ClassError::ClassNotFoundByName(name.to_string()))
47 .map(|class| class.as_ref())
48 }
49}
50
51#[derive(Clone)]
53pub struct Class {
54 pub(crate) id: i32,
55 pub(crate) name: Box<str>,
56 pub(crate) serializer: Rc<Serializer>,
57}
58
59impl Class {
60 pub(crate) fn new(id: i32, name: Box<str>, serializer: Rc<Serializer>) -> Self {
61 Class {
62 id,
63 name,
64 serializer,
65 }
66 }
67
68 pub fn name(&self) -> &str {
71 self.name.as_ref()
72 }
73
74 pub fn id(&self) -> i32 {
77 self.id
78 }
79}
80
81impl Display for Classes {
82 fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
83 let mut table = Table::new();
84 table.add_row(row!["id", "name"]);
85 for class in self.classes_vec.iter() {
86 table.add_row(row![class.id().to_string(), class.name]);
87 }
88 write!(f, "{}", table)
89 }
90}