Skip to main content

keepass_ng/db/types/
icon.rs

1use chrono::NaiveDateTime;
2use std::ops::{Deref, DerefMut};
3use uuid::Uuid;
4
5use crate::db::IconId;
6
7/// Icon specification for an [Entry][crate::db::Entry] or [Group][crate::db::Group].
8#[derive(Debug, Eq, PartialEq, Clone, Copy)]
9#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
10pub enum Icon {
11    /// The icon is a built-in icon specified by an index
12    BuiltIn(IconId),
13
14    /// The icon is a custom icon specified by a UUID
15    Custom(Uuid),
16}
17
18impl std::fmt::Display for Icon {
19    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
20        match self {
21            Icon::BuiltIn(icon_id) => write!(f, "{}", icon_id),
22            Icon::Custom(uuid) => write!(f, "{}", uuid),
23        }
24    }
25}
26
27impl From<IconId> for Icon {
28    fn from(icon_id: IconId) -> Self {
29        Icon::BuiltIn(icon_id)
30    }
31}
32
33impl From<Uuid> for Icon {
34    fn from(uuid: Uuid) -> Self {
35        Icon::Custom(uuid)
36    }
37}
38
39impl TryFrom<Icon> for IconId {
40    type Error = std::io::Error;
41    fn try_from(icon: Icon) -> Result<Self, Self::Error> {
42        match icon {
43            Icon::BuiltIn(icon_id) => Ok(icon_id),
44            Icon::Custom(_) => Err(std::io::Error::other("Custom icon cannot be converted to IconId")),
45        }
46    }
47}
48
49impl TryFrom<Icon> for Uuid {
50    type Error = std::io::Error;
51    fn try_from(icon: Icon) -> Result<Self, Self::Error> {
52        match icon {
53            Icon::BuiltIn(_) => Err(std::io::Error::other("Built-in icon cannot be converted to Uuid")),
54            Icon::Custom(uuid) => Ok(uuid),
55        }
56    }
57}
58
59/// A custom icon stored in the database, containing raw image data.
60#[derive(Debug, Clone, PartialEq, Eq)]
61#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
62pub struct CustomIcon {
63    pub(crate) id: Uuid,
64
65    /// Filename for the icon
66    pub name: Option<String>,
67
68    /// Last modification timestamp
69    pub last_modification_time: Option<NaiveDateTime>,
70
71    /// The raw image data
72    pub data: Vec<u8>,
73}
74
75impl CustomIcon {
76    /// Get the ID of this custom icon
77    pub fn id(&self) -> Uuid {
78        self.id
79    }
80
81    pub fn name(&self) -> Option<&str> {
82        self.name.as_deref()
83    }
84
85    pub fn new(id: Uuid, name: Option<String>, last_modification_time: Option<NaiveDateTime>, data: Vec<u8>) -> Self {
86        Self {
87            id,
88            name,
89            last_modification_time,
90            data,
91        }
92    }
93}
94
95impl Deref for CustomIcon {
96    type Target = Vec<u8>;
97    fn deref(&self) -> &Self::Target {
98        &self.data
99    }
100}
101
102impl DerefMut for CustomIcon {
103    fn deref_mut(&mut self) -> &mut Self::Target {
104        &mut self.data
105    }
106}