keepass/db/types/
group.rs1use std::ops::{Deref, DerefMut};
2
3use indexmap::IndexSet;
4use thiserror::Error;
5use uuid::Uuid;
6
7use crate::{
8 Database,
9 db::{Entry, EntryId, EntryMut, EntryRef},
10};
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
14pub struct GroupId(Uuid);
15
16impl Default for GroupId {
17 fn default() -> Self {
18 Self::new()
19 }
20}
21
22impl GroupId {
23 pub fn new() -> Self {
25 Self(Uuid::new_v4())
26 }
27
28 pub const fn from_uuid(uuid: Uuid) -> Self {
34 Self(uuid)
35 }
36
37 pub fn uuid(&self) -> Uuid {
39 self.0
40 }
41}
42
43impl From<Uuid> for GroupId {
44 fn from(uuid: Uuid) -> Self {
45 Self::from_uuid(uuid)
46 }
47}
48
49impl std::fmt::Display for GroupId {
50 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
51 write!(f, "{}", self.0)
52 }
53}
54
55#[derive(Debug, Eq, PartialEq, Clone)]
57pub struct Group {
58 pub(crate) id: GroupId,
60
61 pub(crate) parent: Option<GroupId>,
63
64 pub name: String,
66
67 pub(crate) groups: IndexSet<GroupId>,
69
70 pub(crate) entries: IndexSet<EntryId>,
72}
73
74impl Group {
75 pub fn id(&self) -> GroupId {
77 self.id
78 }
79
80 pub(crate) fn with_id(id: GroupId, parent: Option<GroupId>) -> Group {
81 Group { id, parent, name: String::new(), groups: IndexSet::new(), entries: IndexSet::new() }
82 }
83
84 pub fn group_ids(&self) -> impl Iterator<Item = GroupId> + '_ {
86 self.groups.iter().cloned()
87 }
88
89 pub fn entry_ids(&self) -> impl Iterator<Item = EntryId> + '_ {
91 self.entries.iter().cloned()
92 }
93}
94
95#[derive(Clone)]
97pub struct GroupRef<'a> {
98 database: &'a crate::db::Database,
99 id: GroupId,
100}
101
102impl GroupRef<'_> {
103 pub(crate) fn new(database: &Database, id: GroupId) -> GroupRef<'_> {
104 GroupRef { database, id }
105 }
106
107 pub fn group(&self, id: GroupId) -> Option<GroupRef<'_>> {
109 self.groups.contains(&id).then(move || GroupRef::new(self.database, id))
110 }
111
112 pub fn entry(&self, id: EntryId) -> Option<EntryRef<'_>> {
114 self.entries.contains(&id).then(move || EntryRef::new(self.database, id))
115 }
116
117 pub fn groups(&self) -> impl Iterator<Item = GroupRef<'_>> + '_ {
119 self.groups.iter().map(move |id| GroupRef::new(self.database, *id))
120 }
121
122 pub fn entries(&self) -> impl Iterator<Item = EntryRef<'_>> + '_ {
124 self.entries.iter().map(move |id| EntryRef::new(self.database, *id))
125 }
126}
127
128impl Deref for GroupRef<'_> {
129 type Target = Group;
130
131 #[allow(clippy::expect_used, clippy::missing_panics_doc)] fn deref(&self) -> &Self::Target {
133 self.database.groups.get(&self.id).expect("GroupRef points to a non-existing group")
134 }
135}
136
137pub struct GroupMut<'a> {
139 database: &'a mut crate::db::Database,
140 id: GroupId,
141}
142
143impl GroupMut<'_> {
144 pub(crate) fn new(database: &mut Database, id: GroupId) -> GroupMut<'_> {
145 GroupMut { database, id }
146 }
147
148 pub fn group_mut(&mut self, id: GroupId) -> Option<GroupMut<'_>> {
150 self.groups.contains(&id).then(move || GroupMut::new(self.database, id))
151 }
152
153 pub fn entry_mut(&mut self, id: EntryId) -> Option<EntryMut<'_>> {
155 self.entries.contains(&id).then(move || EntryMut::new(self.database, id))
156 }
157
158 pub fn edit(&mut self, f: impl FnOnce(&mut GroupMut<'_>)) -> &mut Self {
160 f(self);
161 self
162 }
163
164 #[allow(clippy::missing_panics_doc)]
166 pub fn add_group(&mut self) -> GroupMut<'_> {
167 #[allow(clippy::expect_used)]
168 self.add_group_with_id(GroupId::new()).expect("fresh v4 UUID cannot collide with an existing group identifier")
169 }
170
171 #[allow(clippy::missing_panics_doc)]
173 pub fn add_entry(&mut self) -> EntryMut<'_> {
174 #[allow(clippy::expect_used)]
175 self.add_entry_with_id(EntryId::new()).expect("fresh v4 UUID cannot collide with an existing entry identifier")
176 }
177 pub fn add_entry_with_id(&mut self, id: EntryId) -> Result<EntryMut<'_>, DuplicateEntryIdError> {
195 if self.database.entries.contains_key(&id) {
196 return Err(DuplicateEntryIdError(id));
197 }
198
199 let new_entry = Entry::with_id(id, self.id);
200 self.entries.insert(id);
201 self.database.entries.insert(id, new_entry);
202
203 Ok(EntryMut::new(self.database, id))
204 }
205
206 pub fn add_group_with_id(&mut self, id: GroupId) -> Result<GroupMut<'_>, DuplicateGroupIdError> {
226 if self.database.groups.contains_key(&id) {
227 return Err(DuplicateGroupIdError(id));
228 }
229
230 let new_group = Group::with_id(id, Some(self.id));
231 self.groups.insert(id);
232 self.database.groups.insert(id, new_group);
233
234 Ok(GroupMut::new(self.database, id))
235 }
236}
237
238#[derive(Debug, Error)]
240#[error("a group with ID {0} already exists in the database")]
241pub struct DuplicateGroupIdError(pub GroupId);
242
243#[derive(Debug, Error)]
245#[error("an entry with ID {0} already exists in the database")]
246pub struct DuplicateEntryIdError(pub EntryId);
247
248impl Deref for GroupMut<'_> {
249 type Target = Group;
250
251 #[allow(clippy::expect_used, clippy::missing_panics_doc)] fn deref(&self) -> &Self::Target {
253 self.database.groups.get(&self.id).expect("GroupMut points to a non-existing group")
254 }
255}
256
257impl DerefMut for GroupMut<'_> {
258 #[allow(clippy::expect_used, clippy::missing_panics_doc)] fn deref_mut(&mut self) -> &mut Self::Target {
260 self.database.groups.get_mut(&self.id).expect("GroupMut points to a non-existing group")
261 }
262}
263
264#[cfg(test)]
265#[allow(clippy::unwrap_used)]
266mod group_tests {
267 use crate::Database;
268 use crate::db::fields;
269
270 #[test]
271 fn get() {
272 let mut db = Database::new();
273
274 let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();
275 let sample_entry_id = {
276 let mut group = db.group_mut(general_group_id).unwrap();
277 let mut entry = group.add_entry();
278 entry.set_unprotected(fields::TITLE, "Sample Entry #2");
279 entry.id()
280 };
281
282 assert_eq!(db.entry(sample_entry_id).unwrap().get(fields::TITLE), Some("Sample Entry #2"));
283
284 let root = db.root();
285
286 assert!(root.group(general_group_id).is_some());
287 assert!(db.group(general_group_id).unwrap().entry(sample_entry_id).is_some());
288 }
289
290 #[test]
291 fn get_mut() {
292 let mut db = Database::new();
293
294 let general_group_id = db.root_mut().add_group().edit(|g| g.name = "General".into()).id();
295
296 let sample_entry_id = {
297 let mut group = db.group_mut(general_group_id).unwrap();
298 let mut entry = group.add_entry();
299 entry.set_unprotected(fields::TITLE, "Sample Entry #2");
300 entry.id()
301 };
302
303 assert_eq!(db.entry_mut(sample_entry_id).unwrap().get(fields::TITLE), Some("Sample Entry #2"));
304
305 assert!(db.root_mut().group_mut(general_group_id).is_some());
306
307 assert!(db.group_mut(general_group_id).unwrap().entry_mut(sample_entry_id).is_some());
308 }
309
310 #[test]
311 fn add_entry_with_id_uses_supplied_uuid() {
312 use crate::db::EntryId;
313 use uuid::uuid;
314
315 let mut db = Database::new();
316 let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000aa");
317 let pinned: EntryId = pinned_uuid.into();
318 let inserted_id = {
319 let mut root = db.root_mut();
320 let mut entry = root.add_entry_with_id(pinned).unwrap();
321 entry.set_unprotected(fields::TITLE, "pinned");
322 entry.id()
323 };
324 assert_eq!(inserted_id, pinned);
325 assert_eq!(inserted_id.uuid(), pinned_uuid);
326 assert_eq!(db.entry(pinned).unwrap().get(fields::TITLE), Some("pinned"),);
327 }
328
329 #[test]
330 fn add_entry_with_id_duplicate_returns_error() {
331 use crate::db::{DuplicateEntryIdError, EntryId};
332 use uuid::uuid;
333
334 let mut db = Database::new();
335 let pinned: EntryId = uuid!("00000000-0000-0000-0000-0000000000ab").into();
336
337 db.root_mut().add_entry_with_id(pinned).unwrap();
338
339 assert!(matches!(
340 db.root_mut().add_entry_with_id(pinned),
341 Err(DuplicateEntryIdError(eid)) if eid == pinned
342 ));
343 }
344
345 #[test]
346 fn add_group_with_id_uses_supplied_uuid() {
347 use crate::db::GroupId;
348 use uuid::uuid;
349
350 let mut db = Database::new();
351 let pinned_uuid = uuid!("00000000-0000-0000-0000-0000000000ba");
352 let pinned: GroupId = pinned_uuid.into();
353
354 let inserted_id = db.root_mut().add_group_with_id(pinned).unwrap().edit(|g| g.name = "pinned".into()).id();
355
356 assert_eq!(inserted_id, pinned);
357 assert_eq!(inserted_id.uuid(), pinned_uuid);
358 assert_eq!(db.group(pinned).unwrap().name, "pinned");
359 }
360
361 #[test]
362 fn add_group_with_id_duplicate_returns_error() {
363 use crate::db::{DuplicateGroupIdError, GroupId};
364 use uuid::uuid;
365
366 let mut db = Database::new();
367 let pinned: GroupId = uuid!("00000000-0000-0000-0000-0000000000bb").into();
368
369 db.root_mut().add_group_with_id(pinned).unwrap();
370
371 assert!(matches!(
372 db.root_mut().add_group_with_id(pinned),
373 Err(DuplicateGroupIdError(gid)) if gid == pinned
374 ));
375 }
376
377 #[test]
378 fn group_id_new_generates_distinct_ids() {
379 use crate::db::GroupId;
380
381 assert_ne!(GroupId::new(), GroupId::new());
382 }
383
384 #[test]
385 fn from_uuid_impls_match_constructors() {
386 use crate::db::{EntryId, GroupId};
387 use uuid::uuid;
388
389 let raw = uuid!("00000000-0000-0000-0000-0000000000cc");
390 let from_entry: EntryId = raw.into();
391 let from_entry_ctor = EntryId::from_uuid(raw);
392 assert_eq!(from_entry, from_entry_ctor);
393 assert_eq!(from_entry.uuid(), raw);
394
395 let from_group: GroupId = raw.into();
396 let from_group_ctor = GroupId::from_uuid(raw);
397 assert_eq!(from_group, from_group_ctor);
398 assert_eq!(from_group.uuid(), raw);
399 }
400}