cock_lib/
user.rs

1use crate::{FromString, GetVariants};
2
3/// Represents the data to be stored within the [User] enum.
4/// It contains the username and discord name of the user being
5/// analyzed.
6/// `name` field is the name of the user.
7/// `discord_name` field is the discord name of the user.
8#[derive(Debug, PartialEq, Clone, serde::Deserialize)]
9pub struct InnerUser {
10    pub name: String,
11    pub discord_name: String,
12}
13
14/// Represents a unique identifier for a user, their [ID].
15/// Variants include an anonymous identifier or a specific user.
16#[derive(Debug, PartialEq, Clone, serde::Deserialize)]
17pub enum ID {
18    Anonymous,
19    User(InnerUser),
20}
21
22/// Implementing [GetVariants] for [ID] enum to provide the different variant options for [ID].
23impl GetVariants for ID {
24    fn get_variants() -> Vec<String> {
25        vec![String::from("Anonymous"), String::from("User")]
26    }
27}
28
29/// Implementing [FromString] for [ID] enum to create an [ID] instance from a string.
30impl FromString for ID {
31    fn from_string(id: &str) -> ID {
32        match id {
33            "Anonymous" => ID::Anonymous,
34            "User" => ID::User(InnerUser {
35                name: String::from(""),
36                discord_name: String::from(""),
37            }),
38            _ => panic!("Invalid ID"),
39        }
40    }
41}
42
43/// Implementing [std::fmt::Display] trait for [ID] for formatted print.
44impl std::fmt::Display for ID {
45    /// Returnis a string representation of the [ID] variant.
46    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47        match self {
48            ID::Anonymous => write!(f, "Anonymous User"),
49            ID::User(user) => write!(
50                f,
51                "Username: {}\nDiscord name: {}",
52                user.name, user.discord_name
53            ),
54        }
55    }
56}
57
58/// Tests for the [User] and [ID] structs
59#[cfg(test)]
60mod tests {
61    use super::*;
62
63    #[test]
64    fn test_user() {
65        let user = InnerUser {
66            name: String::from("S"),
67            discord_name: String::from("test"),
68        };
69
70        assert_eq!(user.name, "S");
71        assert_eq!(user.discord_name, String::from("test"));
72    }
73
74    #[test]
75    fn test_id() {
76        let user = InnerUser {
77            name: String::from("S"),
78            discord_name: String::from("test"),
79        };
80
81        let id = ID::User(user);
82
83        match id {
84            ID::User(user) => {
85                assert_eq!(user.name, "S");
86                assert_eq!(user.discord_name, String::from("test"));
87            }
88            _ => panic!("Expected ID::User"),
89        }
90    }
91}