airone/database/
write_proxy.rs

1//  ------------------------------------------------------------------
2//  Airone
3//  is a Rust library which provides a simple in-memory,
4//  write-on-update database that is persisted
5//  to an append-only transaction file.
6//
7//  Copyright © 2022,2023,2024 Massimo Gismondi
8//
9//  This file is part of Airone.
10//  Airone is free software: you can redistribute it and/or
11//  modify it under the terms of the GNU Affero General Public License
12//  as published by the Free Software Foundation, either version 3
13//  of the License, or (at your option) any later version.
14//
15//  This program is distributed in the hope that it will be useful,
16//  but WITHOUT ANY WARRANTY; without even the implied warranty of
17//  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18//  GNU General Public License for more details.
19
20//  You should have received a copy of the GNU Affero General Public License
21//  along with this program. If not, see <https://www.gnu.org/licenses/>.
22//  ------------------------------------------------------------------
23
24use crate::error::Error;
25
26use super::settings;
27use super::settings::save_mode::*;
28use super::AironeDb;
29use super::InnerStruct;
30use super::SerializableField;
31
32// WriteProxy
33/// A write proxy
34/// to ensure that calls to `set`
35/// will properly persist changes
36pub struct WriteProxy<'a, T, SaveMode>
37where
38    T: InnerStruct,
39    SaveMode: settings::save_mode::SaveModeExt
40{
41    index: usize,
42    db: &'a mut AironeDb<T, SaveMode>
43}
44impl<'a, T, SaveMode> WriteProxy<'a, T, SaveMode>
45where
46    T: InnerStruct,
47    SaveMode: settings::save_mode::SaveModeExt
48{
49    pub(super) fn new(db: &'a mut AironeDb<T, SaveMode>, index: usize) -> Self
50    {
51        WriteProxy { db, index }
52    }
53
54    #[doc(hidden)]
55    pub fn get<V: SerializableField>(&self, fieldname: &'static str) -> &V
56    {
57        // use crate::serde::InnerStruct;
58        &self.db[self.index].get(fieldname)
59    }
60}
61
62impl<'a, T> WriteProxy<'a, T, AutoSave>
63where
64    T: InnerStruct
65{
66    #[doc(hidden)]
67    pub fn set<V: SerializableField>(
68        &mut self,
69        fieldname: &'static str,
70        value: V
71    ) -> Result<(), Error>
72    {
73        self.db.set(self.index, fieldname, value)?;
74        Ok(())
75    }
76}
77
78impl<'a, T> WriteProxy<'a, T, ManualSave>
79where
80    T: InnerStruct
81{
82    #[doc(hidden)]
83    pub fn set<V: SerializableField>(&mut self, fieldname: &'static str, value: V)
84    {
85        self.db.set(self.index, fieldname, value);
86    }
87}