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
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
use crate::{IntoOwned, MaybeOwned, MaybeOwnedIndex};

/// Prefix is the sender of a message

pub struct Prefix<'a> {
    pub(crate) data: &'a MaybeOwned<'a>,
    pub(crate) index: PrefixIndex,
}

impl<'a> std::fmt::Debug for Prefix<'a> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        self.data[self.index.as_index()].fmt(f)
    }
}

impl<'a> Prefix<'a> {
    /// Was this message from the server?

    pub fn is_server(&self) -> bool {
        !self.is_user()
    }

    /// Was this message from a user?

    pub fn is_user(&self) -> bool {
        matches!(self.index, PrefixIndex::User{ .. })
    }

    /// Get the full, raw string

    pub fn get_raw_prefix(&self) -> &'a str {
        &self.data[self.index.as_index()]
    }

    /// Get the nickname of this prefix, if it was sent by a user

    pub fn get_nick(&self) -> Option<&'a str> {
        self.index.nick_index().map(|index| &self.data[index])
    }
}

/// Prefix is the sender of a message

#[derive(Debug, Copy, Clone, Ord, PartialOrd, Eq, PartialEq, Hash)]
pub enum PrefixIndex {
    /// A user prefix

    User {
        /// Index of the nickname

        nick: MaybeOwnedIndex,
    },
    /// A server prefix

    Server {
        /// Index of the hostname

        host: MaybeOwnedIndex,
    },
}

impl PrefixIndex {
    /// Was this message from the server?

    pub fn is_server(&self) -> bool {
        !self.is_nick()
    }

    /// Was this message from a user?

    pub fn is_nick(&self) -> bool {
        matches!(self, Self::User{ .. })
    }

    /// Get the index of the nickname

    pub fn nick_index(self) -> Option<MaybeOwnedIndex> {
        match self {
            Self::User { nick } => Some(nick),
            Self::Server { .. } => None,
        }
    }

    /// Get the index of the hostname

    pub fn host_index(self) -> Option<MaybeOwnedIndex> {
        match self {
            Self::Server { host } => Some(host),
            Self::User { .. } => None,
        }
    }

    /// Consumes this returning the index

    pub fn as_index(self) -> MaybeOwnedIndex {
        match self {
            Self::User { nick } => nick,
            Self::Server { host } => host,
        }
    }
}

impl IntoOwned<'static> for PrefixIndex {
    type Output = Self;
    fn into_owned(self) -> Self::Output {
        self
    }
}