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 From<IconId> for Icon {
19    fn from(icon_id: IconId) -> Self {
20        Icon::BuiltIn(icon_id)
21    }
22}
23
24impl From<Uuid> for Icon {
25    fn from(uuid: Uuid) -> Self {
26        Icon::Custom(uuid)
27    }
28}
29
30impl TryFrom<Icon> for IconId {
31    type Error = std::io::Error;
32    fn try_from(icon: Icon) -> Result<Self, Self::Error> {
33        match icon {
34            Icon::BuiltIn(icon_id) => Ok(icon_id),
35            Icon::Custom(_) => Err(std::io::Error::other("Custom icon cannot be converted to IconId")),
36        }
37    }
38}
39
40impl TryFrom<Icon> for Uuid {
41    type Error = std::io::Error;
42    fn try_from(icon: Icon) -> Result<Self, Self::Error> {
43        match icon {
44            Icon::BuiltIn(_) => Err(std::io::Error::other("Built-in icon cannot be converted to Uuid")),
45            Icon::Custom(uuid) => Ok(uuid),
46        }
47    }
48}
49
50/// A custom icon stored in the database, containing raw image data.
51#[derive(Debug, Clone, PartialEq, Eq)]
52#[cfg_attr(feature = "serialization", derive(serde::Serialize))]
53pub struct CustomIcon {
54    pub(crate) id: Uuid,
55
56    /// Filename for the icon
57    pub name: Option<String>,
58
59    /// Last modification timestamp
60    pub last_modification_time: Option<NaiveDateTime>,
61
62    /// The raw image data
63    pub data: Vec<u8>,
64}
65
66impl CustomIcon {
67    /// Get the ID of this custom icon
68    pub fn id(&self) -> Uuid {
69        self.id
70    }
71
72    pub fn name(&self) -> Option<&str> {
73        self.name.as_deref()
74    }
75
76    pub fn new(id: Uuid, name: Option<String>, last_modification_time: Option<NaiveDateTime>, data: Vec<u8>) -> Self {
77        Self {
78            id,
79            name,
80            last_modification_time,
81            data,
82        }
83    }
84}
85
86impl Deref for CustomIcon {
87    type Target = Vec<u8>;
88    fn deref(&self) -> &Self::Target {
89        &self.data
90    }
91}
92
93impl DerefMut for CustomIcon {
94    fn deref_mut(&mut self) -> &mut Self::Target {
95        &mut self.data
96    }
97}