link_cli/storage/
named_links_storage.rs1use std::cell::RefCell;
16
17use crate::error::LinkError;
18use crate::link::Link;
19use crate::named_type_links::NamedTypeLinks;
20use crate::storage::traits::LinksStorage;
21
22pub struct NamedLinksStorage<L: NamedTypeLinks> {
25 links: RefCell<L>,
26}
27
28impl<L: NamedTypeLinks> NamedLinksStorage<L> {
29 pub fn new(links: L) -> Self {
31 Self {
32 links: RefCell::new(links),
33 }
34 }
35
36 pub fn links_mut(&mut self) -> &mut L {
38 self.links.get_mut()
39 }
40
41 pub fn into_inner(self) -> L {
43 self.links.into_inner()
44 }
45}
46
47fn link_error(error: anyhow::Error) -> LinkError {
51 match error.downcast::<LinkError>() {
52 Ok(error) => error,
53 Err(error) => LinkError::StorageError(format!("{error:#}")),
54 }
55}
56
57impl<L: NamedTypeLinks> LinksStorage<u32> for NamedLinksStorage<L> {
58 fn create_link(&mut self, source: u32, target: u32) -> Result<u32, LinkError> {
59 self.links
60 .get_mut()
61 .try_create(source, target)
62 .map_err(link_error)
63 }
64
65 fn ensure_link_created(&mut self, index: u32) -> Result<u32, LinkError> {
66 self.links
67 .get_mut()
68 .try_ensure_created(index)
69 .map_err(link_error)
70 }
71
72 fn get_link(&self, index: u32) -> Option<Link> {
73 self.links.borrow_mut().get_link(index)
74 }
75
76 fn link_exists(&self, index: u32) -> bool {
77 self.links.borrow_mut().exists(index)
78 }
79
80 fn update_link(&mut self, index: u32, source: u32, target: u32) -> Result<Link, LinkError> {
81 self.links
82 .get_mut()
83 .update(index, source, target)
84 .map_err(link_error)
85 }
86
87 fn delete_link(&mut self, index: u32) -> Result<Link, LinkError> {
88 self.links.get_mut().delete(index).map_err(link_error)
89 }
90
91 fn update_link_observed(
92 &mut self,
93 index: u32,
94 source: u32,
95 target: u32,
96 observer: &mut dyn FnMut(Link, Link),
97 ) -> Result<Link, LinkError> {
98 self.links
99 .get_mut()
100 .update_observed(index, source, target, observer)
101 .map_err(link_error)
102 }
103
104 fn delete_link_observed(
105 &mut self,
106 index: u32,
107 observer: &mut dyn FnMut(Link, Link),
108 ) -> Result<Link, LinkError> {
109 self.links
110 .get_mut()
111 .delete_observed(index, observer)
112 .map_err(link_error)
113 }
114
115 fn all_links(&self) -> Vec<Link> {
116 self.links.borrow_mut().all_links()
117 }
118
119 fn query_links(
120 &self,
121 index: Option<u32>,
122 source: Option<u32>,
123 target: Option<u32>,
124 ) -> Vec<Link> {
125 self.links.borrow_mut().query_links(index, source, target)
126 }
127
128 fn search_link(&self, source: u32, target: u32) -> Option<u32> {
129 self.links.borrow_mut().search(source, target)
130 }
131
132 fn get_or_create_link(&mut self, source: u32, target: u32) -> Result<u32, LinkError> {
133 self.links
134 .get_mut()
135 .try_get_or_create(source, target)
136 .map_err(link_error)
137 }
138
139 fn flush(&mut self) -> Result<(), LinkError> {
140 self.links.get_mut().save().map_err(link_error)
141 }
142}