1use std::io;
2use crate::bucket::EntryId;
3use crate::store::ensure_bucket_exists_locked;
4use crate::store::store;
5use crate::store::validate_key;
6
7pub fn create(content: String, key: &EntryId) -> io::Result<()> {
8 validate_key(&key.name)?;
9
10 let mut st: std::sync::MutexGuard<'_, crate::store::Store> = store().lock().map_err(|_| {
11 io::Error::new(io::ErrorKind::Other, "ram store poisoned")
12 })?;
13
14 ensure_bucket_exists_locked(&st, &key.bucket)?;
15
16 let map: &mut std::collections::HashMap<String, String> = st
17 .entries
18 .get_mut(&key.bucket)
19 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Bucket not found"))?;
20
21 map.insert(key.name.to_string(), content);
22 Ok(())
23}
24
25pub fn read(key: &EntryId) -> io::Result<String> {
26 validate_key(&key.name)?;
27
28 let st: std::sync::MutexGuard<'_, crate::store::Store> = store().lock().map_err(|_| {
29 io::Error::new(io::ErrorKind::Other, "ram store poisoned")
30 })?;
31
32 ensure_bucket_exists_locked(&st, &key.bucket)?;
33
34 let map: &std::collections::HashMap<String, String> = st
35 .entries
36 .get(&key.bucket)
37 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Bucket not found"))?;
38
39 let v: &String = map.get(&key.name).ok_or_else(|| {
40 io::Error::new(io::ErrorKind::NotFound, "Entry not found")
41 })?;
42
43 Ok(v.clone())
44}
45
46pub fn delete(key: &EntryId) -> io::Result<()> {
47 validate_key(&key.name)?;
48
49 let mut st: std::sync::MutexGuard<'_, crate::store::Store> = store().lock().map_err(|_| {
50 io::Error::new(io::ErrorKind::Other, "ram store poisoned")
51 })?;
52
53 ensure_bucket_exists_locked(&st, &key.bucket)?;
54
55 let map: &mut std::collections::HashMap<String, String> = st
56 .entries
57 .get_mut(&key.bucket)
58 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Bucket not found"))?;
59
60 if map.remove(&key.name).is_none() {
61 return Err(io::Error::new(io::ErrorKind::NotFound, "Entry not found"));
62 }
63
64 Ok(())
65}
66
67pub fn exists(key: &EntryId) -> io::Result<bool> {
68 validate_key(&key.name)?;
69
70 let st: std::sync::MutexGuard<'_, crate::store::Store> = store().lock().map_err(|_| {
71 io::Error::new(io::ErrorKind::Other, "ram store poisoned")
72 })?;
73
74 ensure_bucket_exists_locked(&st, &key.bucket)?;
75
76 let map: &std::collections::HashMap<String, String> = st
77 .entries
78 .get(&key.bucket)
79 .ok_or_else(|| io::Error::new(io::ErrorKind::NotFound, "Bucket not found"))?;
80
81 Ok(map.contains_key(&key.name))
82}
83
84#[cfg(test)]
85#[path = "../tests/unit_tests/entry.rs"]
86pub mod tests;