├── .gitignore ├── CHANGELOG.md ├── Cargo.toml ├── LICENSE-APACHE ├── LICENSE-MIT ├── README.md └── src ├── file_store.rs ├── json_store.rs ├── lib.rs └── memory_store.rs /.gitignore: -------------------------------------------------------------------------------- 1 | target 2 | Cargo.lock 3 | *.swp 4 | -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | ## v0.9.0 (2023-03-13) 2 | 3 | - use `parking_lot` 4 | - use `tempfile` 5 | 6 | ## v0.8.0 (2022-11-16) 7 | 8 | - Update `uuid` to v1.x 9 | 10 | ## v0.7.1 (2022-03-13) 11 | 12 | - Fix Access denied issue on windows 13 | - Derive debug trait for public structs 14 | 15 | ## v0.7.0 (2021-10-25) 16 | 17 | - Change License to MIT/Apache 2.0 18 | - Use `uuid` v0.8.x 19 | - Switch to 2021 edition 20 | - Use `usize` for `indent` configuration 21 | 22 | ## v0.6.2 (2019-09-01) 23 | 24 | - Use RwLock to allow multithreaded access 25 | 26 | ## v0.6.1 (2019-08-30) 27 | 28 | - add in-memory support 29 | 30 | ## v0.6.0 (2019-08-06) 31 | 32 | - create temporary files within the same directory like the target file 33 | - switched to Rust edition 2018 34 | - use uuid v0.7.x 35 | 36 | ## v0.5.0 (2018-04-27) 37 | 38 | - use uuid v0.6.x 39 | - add method `path()` to access storage location 40 | - generify constructors path argument 41 | 42 | ## v0.4.0 (2017-05-31) 43 | 44 | - use serde v1.x 45 | - use uuid v0.5.x 46 | 47 | ## v0.3.0 (2017-02-04) 48 | 49 | - BREAKING changes: 50 | - renamed `get_all()` to `all()` 51 | - dropped `rustc_serialize` support 52 | - use serde v0.9.x 53 | 54 | ## v0.2.2 (2016-09-24) 55 | 56 | - derive `Clone` for `Store` 57 | 58 | ## v0.2.1 (2016-07-19) 59 | 60 | - new: support serde v0.7.x 61 | 62 | ## v0.2.0 (2016-07-12) 63 | 64 | - new: lock files during write 65 | - fix: don't return an error if a directory already exists 66 | 67 | ## v0.1.1 (2016-07-12) 68 | 69 | - make configuration fields (`pretty`, `indent`, `single`) public 70 | 71 | ## v0.1.0 (2016-07-03) 72 | 73 | - Initial release 74 | -------------------------------------------------------------------------------- /Cargo.toml: -------------------------------------------------------------------------------- 1 | [package] 2 | name = "jfs" 3 | version = "0.9.0" 4 | authors = ["Markus Kohlhase "] 5 | license = "MIT/Apache-2.0" 6 | homepage = "https://github.com/flosse/rust-json-file-store" 7 | repository = "https://github.com/flosse/rust-json-file-store" 8 | documentation = "https://docs.rs/crate/jfs/" 9 | description = "A JSON file store" 10 | readme = "README.md" 11 | keywords = ["json", "file", "store", "db", "database"] 12 | categories = ["database"] 13 | edition = "2021" 14 | 15 | [dependencies] 16 | fs2 = "0.4" 17 | log = "0.4" 18 | parking_lot = "0.12" 19 | serde = "1.0" 20 | serde_json = "1.0" 21 | uuid = { version = "1.11", features = ["v4"] } 22 | 23 | [dev-dependencies] 24 | serde = { version = "1.0", features = ["derive"] } 25 | serde_derive = { version = "1.0" } 26 | tempfile = "3.15" 27 | 28 | [lints.clippy] 29 | pedantic = { level = "warn", priority = -1 } 30 | 31 | # The error types returned should be self-explanatory. 32 | missing_errors_doc = "allow" 33 | -------------------------------------------------------------------------------- /LICENSE-APACHE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright [yyyy] [name of copyright owner] 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /LICENSE-MIT: -------------------------------------------------------------------------------- 1 | Copyright (c) 2016 - 2023 Markus Kohlhase 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 4 | 5 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 6 | 7 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 8 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | [![Crates.io](https://img.shields.io/crates/v/jfs.svg)](https://crates.io/crates/jfs) 2 | [![Docs.rs](https://docs.rs/jfs/badge.svg)](https://docs.rs/jfs/) 3 | [![Dependency status](https://deps.rs/repo/github/flosse/rust-json-file-store/status.svg)](https://deps.rs/repo/github/flosse/rust-json-file-store) 4 | ![License](https://img.shields.io/crates/l/jfs.svg) 5 | 6 | # jfs 7 | 8 | A simple JSON file store written in Rust. 9 | This is a port of the Node.js library 10 | [json-file-store](https://github.com/flosse/json-file-store/). 11 | 12 | **WARNING**: 13 | Don't use it if you want to persist a large amount of objects. 14 | Use a real DB instead. 15 | 16 | ## Documentation 17 | 18 | See [docs.rs/jfs](https://docs.rs/jfs/). 19 | 20 | ## License 21 | 22 | Copyright (c) 2016 - 2025 Markus Kohlhase 23 | 24 | This library is licensed under either of 25 | 26 | - Apache License, Version 2.0 27 | ([LICENSE-APACHE](https://github.com/flosse/rust-json-file-store/blob/master/LICENSE-APACHE) 28 | or 29 | [apache.org/licenses/LICENSE-2.0](https://apache.org/licenses/LICENSE-2.0)) 30 | - MIT license 31 | ([LICENSE-MIT](https://github.com/flosse/rust-json-file-store/blob/master/LICENSE-MIT) 32 | or 33 | [opensource.org/licenses/MIT](https://opensource.org/licenses/MIT)) 34 | 35 | at your option. 36 | -------------------------------------------------------------------------------- /src/file_store.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::BTreeMap, 3 | fs::{create_dir_all, metadata, read_dir, remove_file, rename, OpenOptions}, 4 | io::{ 5 | Read, Write, {Error, ErrorKind, Result}, 6 | }, 7 | path::{Path, PathBuf}, 8 | }; 9 | 10 | use fs2::FileExt; 11 | use serde::{Deserialize, Serialize}; 12 | use serde_json::{ 13 | ser::{PrettyFormatter, Serializer}, 14 | value::Map, 15 | Value, 16 | }; 17 | use uuid::Uuid; 18 | 19 | use crate::json_store::JsonStore; 20 | 21 | type Object = Map; 22 | 23 | #[derive(Debug, Clone, Copy)] 24 | pub struct Config { 25 | pub pretty: bool, 26 | pub indent: usize, 27 | pub single: bool, 28 | } 29 | 30 | impl Default for Config { 31 | fn default() -> Self { 32 | Self { 33 | indent: 2, 34 | pretty: false, 35 | single: false, 36 | } 37 | } 38 | } 39 | 40 | #[derive(Debug, Clone)] 41 | pub struct FileStore { 42 | path: PathBuf, 43 | cfg: Config, 44 | } 45 | 46 | impl JsonStore for FileStore { 47 | fn save(&self, obj: &T) -> Result 48 | where 49 | for<'de> T: Serialize + Deserialize<'de>, 50 | { 51 | let id = Uuid::new_v4().to_string(); 52 | self.save_with_id(obj, &id) 53 | } 54 | 55 | fn save_with_id(&self, obj: &T, id: &str) -> Result 56 | where 57 | for<'de> T: Serialize + Deserialize<'de>, 58 | { 59 | if self.cfg.single { 60 | let json = get_json_from_file(&self.path)?; 61 | let object = get_object_from_json(&json)?; 62 | let mut x = object.clone(); 63 | let json = 64 | serde_json::to_value(obj).map_err(|err| Error::new(ErrorKind::Other, err))?; 65 | x.insert(id.to_owned(), json); 66 | self.save_object_to_file(&x, &self.path)?; 67 | } else { 68 | self.save_object_to_file(obj, &self.id_to_path(id))?; 69 | } 70 | Ok(id.to_owned()) 71 | } 72 | 73 | fn get(&self, id: &str) -> Result 74 | where 75 | for<'de> T: Deserialize<'de>, 76 | { 77 | let json = get_json_from_file(&self.id_to_path(id))?; 78 | let object = if self.cfg.single { 79 | let x = json 80 | .get(id) 81 | .ok_or_else(|| Error::new(ErrorKind::NotFound, "no such object"))?; 82 | x.clone() 83 | } else { 84 | json 85 | }; 86 | decode(object) 87 | } 88 | 89 | fn all(&self) -> Result> 90 | where 91 | for<'de> T: Deserialize<'de>, 92 | { 93 | if self.cfg.single { 94 | let json = get_json_from_file(&self.id_to_path(""))?; 95 | let object = get_object_from_json(&json)?; 96 | let mut result = BTreeMap::new(); 97 | for x in object { 98 | let (key, value) = x; 99 | if let Ok(r) = decode(value.clone()) { 100 | result.insert(key.clone(), r); 101 | } 102 | } 103 | return Ok(result); 104 | } 105 | 106 | if !metadata(&self.path)?.is_dir() { 107 | return Err(Error::new(ErrorKind::NotFound, "invalid path")); 108 | } 109 | 110 | let entries = read_dir(&self.path)? 111 | .filter_map(|e| { 112 | e.and_then(|x| { 113 | x.metadata().and_then(|m| { 114 | if m.is_file() { 115 | path_buf_to_id(&x.path()) 116 | } else { 117 | Err(Error::new(ErrorKind::Other, "not a file")) 118 | } 119 | }) 120 | }) 121 | .ok() 122 | }) 123 | .filter_map(|id| { 124 | self.get(&id) 125 | .map_or_else(|_| None, |x| Some((id.clone(), x))) 126 | }) 127 | .collect::>(); 128 | 129 | Ok(entries) 130 | } 131 | 132 | fn delete(&self, id: &str) -> Result<()> { 133 | if self.cfg.single { 134 | let json = get_json_from_file(&self.path)?; 135 | let object = get_object_from_json(&json)?; 136 | let mut x = object.clone(); 137 | if x.contains_key(id) { 138 | x.remove(id); 139 | } else { 140 | return Err(Error::new(ErrorKind::NotFound, "no such object")); 141 | } 142 | self.save_object_to_file(&x, &self.path) 143 | } else { 144 | remove_file(self.id_to_path(id)) 145 | } 146 | } 147 | } 148 | 149 | impl FileStore { 150 | fn id_to_path(&self, id: &str) -> PathBuf { 151 | if self.cfg.single { 152 | self.path.clone() 153 | } else { 154 | self.path.join(id).with_extension("json") 155 | } 156 | } 157 | 158 | fn to_writer_pretty(&self, writer: &mut W, value: &T) -> Result<()> { 159 | let indent = vec![' '; self.cfg.indent]; 160 | let b = indent.into_iter().collect::().into_bytes(); 161 | let mut s = Serializer::with_formatter(writer, PrettyFormatter::with_indent(&b)); 162 | value 163 | .serialize(&mut s) 164 | .map_err(|err| Error::new(ErrorKind::InvalidData, err))?; 165 | Ok(()) 166 | } 167 | 168 | fn to_vec_pretty(&self, value: &T) -> Result> { 169 | let mut writer: Vec = vec![]; 170 | self.to_writer_pretty(&mut writer, value)?; 171 | Ok(writer) 172 | } 173 | 174 | fn object_to_string(&self, obj: &T) -> Result { 175 | if self.cfg.pretty { 176 | let vec = self.to_vec_pretty(obj)?; 177 | String::from_utf8(vec).map_err(|err| Error::new(ErrorKind::Other, err)) 178 | } else { 179 | serde_json::to_string(obj).map_err(|err| Error::new(ErrorKind::Other, err)) 180 | } 181 | } 182 | 183 | fn save_object_to_file(&self, obj: &T, file_name: &Path) -> Result<()> { 184 | let json_string = self.object_to_string(obj)?; 185 | let mut tmp_filename = file_name.to_path_buf(); 186 | tmp_filename.set_file_name(Uuid::new_v4().to_string()); 187 | tmp_filename.set_extension("tmp"); 188 | let file = OpenOptions::new() 189 | .write(true) 190 | .create(true) 191 | .truncate(false) 192 | .open(file_name)?; 193 | let mut tmp_file = OpenOptions::new() 194 | .write(true) 195 | .create(true) 196 | .truncate(true) 197 | .open(&tmp_filename)?; 198 | file.lock_exclusive()?; 199 | tmp_file.lock_exclusive()?; 200 | 201 | if let Err(err) = Write::write_all(&mut tmp_file, json_string.as_bytes()) { 202 | Err(err) 203 | } else { 204 | FileExt::unlock(&tmp_file)?; 205 | FileExt::unlock(&file)?; 206 | drop(file); 207 | drop(tmp_file); 208 | rename(tmp_filename, file_name) 209 | } 210 | } 211 | 212 | #[cfg(test)] 213 | fn new>(path: P) -> Result { 214 | FileStore::new_with_cfg(path, Config::default()) 215 | } 216 | 217 | pub fn new_with_cfg>(path: P, cfg: Config) -> Result { 218 | let mut s = Self { 219 | path: path.as_ref().to_path_buf(), // TODO: probably change this to take an owned PathBuf parameter 220 | cfg, 221 | }; 222 | 223 | if cfg.single { 224 | s.path = s.path.with_extension("json"); 225 | if !s.path.exists() { 226 | let o = Object::new(); 227 | s.save_object_to_file(&o, &s.path)?; 228 | } 229 | return Ok(s); 230 | } 231 | if let Err(err) = create_dir_all(&s.path) { 232 | if err.kind() != ErrorKind::AlreadyExists { 233 | return Err(err); 234 | } 235 | } 236 | Ok(s) 237 | } 238 | 239 | /// Returns the storage path for the backing JSON store. 240 | /// 241 | /// In single-file-mode this will be the JSON file location, otherwise it's 242 | /// the directory in which all JSON objects are stored. 243 | pub fn path(&self) -> &Path { 244 | &self.path 245 | } 246 | } 247 | 248 | fn decode(o: Value) -> Result 249 | where 250 | for<'de> T: Deserialize<'de>, 251 | { 252 | serde_json::from_value(o).map_err(|err| Error::new(ErrorKind::Other, err)) 253 | } 254 | 255 | fn get_string_from_file(file_name: &Path) -> Result { 256 | let mut f = OpenOptions::new() 257 | .read(true) 258 | .write(false) 259 | .create(false) 260 | .open(file_name)?; 261 | let mut buffer = String::new(); 262 | FileExt::lock_shared(&f)?; 263 | f.read_to_string(&mut buffer)?; 264 | FileExt::unlock(&f)?; 265 | Ok(buffer) 266 | } 267 | 268 | fn get_json_from_file(file_name: &Path) -> Result { 269 | let s = get_string_from_file(file_name)?; 270 | serde_json::from_str(&s).map_err(|err| Error::new(ErrorKind::Other, err)) 271 | } 272 | 273 | fn get_object_from_json(json: &Value) -> Result<&Object> { 274 | json.as_object() 275 | .ok_or_else(|| Error::new(ErrorKind::InvalidData, "invalid file content")) 276 | } 277 | 278 | fn path_buf_to_id(p: &Path) -> Result { 279 | p.file_stem() 280 | .and_then(|n| n.to_os_string().into_string().ok()) 281 | .ok_or_else(|| Error::new(ErrorKind::Other, "invalid id")) 282 | } 283 | 284 | #[cfg(test)] 285 | mod tests { 286 | use super::*; 287 | use serde_derive::{Deserialize, Serialize}; 288 | use std::{collections::BTreeMap, fs::File, io::ErrorKind, path::Path, thread}; 289 | use tempfile::tempdir; 290 | 291 | #[derive(Serialize, Deserialize)] 292 | struct X { 293 | x: u32, 294 | } 295 | 296 | #[derive(Serialize, Deserialize)] 297 | struct Y { 298 | y: i32, 299 | } 300 | 301 | #[derive(Serialize, Deserialize)] 302 | struct Empty {} 303 | 304 | #[derive(Serialize, Deserialize)] 305 | struct Z { 306 | z: f32, 307 | } 308 | 309 | fn write_to_test_file(name: &Path, content: &str) { 310 | let mut file = File::create(&name).unwrap(); 311 | Write::write_all(&mut file, content.as_bytes()).unwrap(); 312 | } 313 | 314 | fn read_from_test_file(name: &Path) -> String { 315 | let mut f = File::open(name).unwrap(); 316 | let mut buffer = String::new(); 317 | f.read_to_string(&mut buffer).unwrap(); 318 | buffer 319 | } 320 | 321 | mod json_store { 322 | 323 | use super::*; 324 | 325 | #[test] 326 | fn new_multi_threaded() { 327 | let mut threads: Vec> = vec![]; 328 | let dir = tempdir().unwrap(); 329 | let path = dir.path().to_path_buf(); 330 | for _ in 0..20 { 331 | let d = path.clone(); 332 | threads.push(thread::spawn(move || { 333 | assert!(FileStore::new(&d).is_ok()); 334 | })); 335 | } 336 | for c in threads { 337 | c.join().unwrap(); 338 | } 339 | } 340 | 341 | #[test] 342 | fn save() { 343 | let dir = tempdir().unwrap(); 344 | let db = FileStore::new(&dir).unwrap(); 345 | let data = X { x: 56 }; 346 | let id = db.save(&data).unwrap(); 347 | let mut f = File::open(dir.path().join(id).with_extension("json")).unwrap(); 348 | let mut buffer = String::new(); 349 | f.read_to_string(&mut buffer).unwrap(); 350 | assert_eq!(buffer, "{\"x\":56}"); 351 | } 352 | 353 | #[test] 354 | fn save_and_read_multi_threaded() { 355 | let dir = tempdir().unwrap().path().to_path_buf(); 356 | let db = FileStore::new(&dir).unwrap(); 357 | let mut threads: Vec> = vec![]; 358 | let x = X { x: 56 }; 359 | db.save_with_id(&x, "bla").unwrap(); 360 | for i in 0..20 { 361 | let d = dir.clone(); 362 | let x = X { x: i }; 363 | threads.push(thread::spawn(move || { 364 | let db = FileStore::new(&d).unwrap(); 365 | db.save_with_id(&x, "bla").unwrap(); 366 | })); 367 | } 368 | for _ in 0..20 { 369 | let d = dir.clone(); 370 | threads.push(thread::spawn(move || { 371 | let db = FileStore::new(&d).unwrap(); 372 | db.get::("bla").unwrap(); 373 | })); 374 | } 375 | for c in threads { 376 | c.join().unwrap(); 377 | } 378 | } 379 | 380 | #[test] 381 | fn save_empty_obj() { 382 | let dir = tempdir().unwrap().path().to_path_buf(); 383 | let db = FileStore::new(&dir).unwrap(); 384 | let id = db.save(&Empty {}).unwrap(); 385 | let mut f = File::open(dir.join(id).with_extension("json")).unwrap(); 386 | let mut buffer = String::new(); 387 | f.read_to_string(&mut buffer).unwrap(); 388 | assert_eq!(buffer, "{}"); 389 | } 390 | 391 | #[test] 392 | fn save_with_id() { 393 | let dir = tempdir().unwrap().path().to_path_buf(); 394 | let db = FileStore::new(&dir).unwrap(); 395 | let data = Y { y: -7 }; 396 | db.save_with_id(&data, "foo").unwrap(); 397 | let mut f = File::open(dir.join("foo.json")).unwrap(); 398 | let mut buffer = String::new(); 399 | f.read_to_string(&mut buffer).unwrap(); 400 | assert_eq!(buffer, "{\"y\":-7}"); 401 | } 402 | 403 | #[test] 404 | fn pretty_print_file_content() { 405 | let dir = tempdir().unwrap().path().to_path_buf(); 406 | let mut cfg = Config::default(); 407 | cfg.pretty = true; 408 | let db = FileStore::new_with_cfg(&dir, cfg).unwrap(); 409 | 410 | #[derive(Deserialize, Serialize)] 411 | struct SubStruct { 412 | c: u32, 413 | } 414 | 415 | #[derive(Deserialize, Serialize)] 416 | struct MyData { 417 | a: String, 418 | b: SubStruct, 419 | } 420 | 421 | let data = MyData { 422 | a: "foo".to_string(), 423 | b: SubStruct { c: 33 }, 424 | }; 425 | 426 | let id = db.save(&data).unwrap(); 427 | let mut f = File::open(dir.join(id).with_extension("json")).unwrap(); 428 | let mut buffer = String::new(); 429 | f.read_to_string(&mut buffer).unwrap(); 430 | let expected = "{\n \"a\": \"foo\",\n \"b\": {\n \"c\": 33\n }\n}"; 431 | assert_eq!(buffer, expected); 432 | } 433 | 434 | #[test] 435 | fn get() { 436 | let dir = tempdir().unwrap().path().to_path_buf(); 437 | let db = FileStore::new(&dir).unwrap(); 438 | let mut file = File::create(dir.join("foo.json")).unwrap(); 439 | Write::write_all(&mut file, b"{\"z\":9.9}").unwrap(); 440 | let obj: Z = db.get("foo").unwrap(); 441 | assert_eq!(obj.z, 9.9); 442 | } 443 | 444 | #[test] 445 | fn get_non_existent() { 446 | let dir = tempdir().unwrap().path().to_path_buf(); 447 | let db = FileStore::new(&dir).unwrap(); 448 | let res = db.get::("foobarobject"); 449 | assert!(res.is_err()); 450 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 451 | } 452 | 453 | #[test] 454 | fn all() { 455 | let dir = tempdir().unwrap().path().to_path_buf(); 456 | let db = FileStore::new(&dir).unwrap(); 457 | 458 | #[derive(Deserialize, Serialize)] 459 | struct X { 460 | x: u32, 461 | y: u32, 462 | } 463 | 464 | let mut file = File::create(dir.join("foo.json")).unwrap(); 465 | Write::write_all(&mut file, b"{\"x\":1, \"y\":0}").unwrap(); 466 | 467 | let mut file = File::create(dir.join("bar.json")).unwrap(); 468 | Write::write_all(&mut file, b"{\"y\":2}").unwrap(); 469 | 470 | let all_x: BTreeMap = db.all().unwrap(); 471 | let all_y: BTreeMap = db.all().unwrap(); 472 | assert_eq!(all_x.get("foo").unwrap().x, 1); 473 | assert!(all_x.get("bar").is_none()); 474 | assert_eq!(all_y.get("bar").unwrap().y, 2); 475 | } 476 | 477 | #[test] 478 | fn delete() { 479 | let dir = tempdir().unwrap(); 480 | let db = FileStore::new(&dir).unwrap(); 481 | let data = Y { y: 88 }; 482 | let id = db.save(&data).unwrap(); 483 | let f_name = dir.path().join(&id).with_extension("json"); 484 | db.get::(&id).unwrap(); 485 | assert_eq!(Path::new(&f_name).exists(), true); 486 | db.delete(&id).unwrap(); 487 | assert_eq!(Path::new(&f_name).exists(), false); 488 | assert!(db.get::(&id).is_err()); 489 | assert!(db.delete(&id).is_err()); 490 | } 491 | 492 | #[test] 493 | fn delete_non_existent() { 494 | let dir = tempdir().unwrap().path().to_path_buf(); 495 | let db = FileStore::new(&dir).unwrap(); 496 | let res = db.delete("blabla"); 497 | assert!(res.is_err()); 498 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 499 | } 500 | 501 | #[test] 502 | fn single_new_multi_threaded() { 503 | let dir = tempdir().unwrap(); 504 | let file_name = dir.path().join("test.json"); 505 | let mut cfg = Config::default(); 506 | cfg.single = true; 507 | let mut threads: Vec> = vec![]; 508 | for _ in 0..20 { 509 | let n = file_name.clone(); 510 | let c = thread::spawn(move || { 511 | assert!(FileStore::new_with_cfg(&n, cfg).is_ok()); 512 | }); 513 | threads.push(c); 514 | } 515 | for c in threads { 516 | c.join().unwrap(); 517 | } 518 | } 519 | 520 | #[test] 521 | fn single_save() { 522 | let dir = tempdir().unwrap(); 523 | let file_name = dir.path().join("test.json"); 524 | let mut cfg = Config::default(); 525 | cfg.single = true; 526 | let db = FileStore::new_with_cfg(&file_name, cfg).unwrap(); 527 | assert_eq!(read_from_test_file(&file_name), "{}"); 528 | let x = X { x: 3 }; 529 | let y = Y { y: 4 }; 530 | db.save_with_id(&x, "x").unwrap(); 531 | db.save_with_id(&y, "y").unwrap(); 532 | assert_eq!( 533 | read_from_test_file(&file_name), 534 | "{\"x\":{\"x\":3},\"y\":{\"y\":4}}" 535 | ); 536 | } 537 | 538 | #[test] 539 | fn single_save_and_read_multi_threaded() { 540 | let dir = tempdir().unwrap(); 541 | let file_name = dir.path().join("test.json"); 542 | let mut cfg = Config::default(); 543 | cfg.single = true; 544 | let db = FileStore::new_with_cfg(file_name.clone(), cfg).unwrap(); 545 | let x = X { x: 0 }; 546 | db.save_with_id(&x, "foo").unwrap(); 547 | let mut threads: Vec> = vec![]; 548 | for i in 1..20 { 549 | let n = file_name.clone(); 550 | let c = thread::spawn(move || { 551 | let x = X { x: i }; 552 | let db = FileStore::new_with_cfg(&n, cfg).unwrap(); 553 | db.save_with_id(&x, "foo").unwrap(); 554 | }); 555 | threads.push(c); 556 | } 557 | for _ in 1..20 { 558 | let n = file_name.clone(); 559 | let c = thread::spawn(move || { 560 | let db = FileStore::new_with_cfg(&n, cfg).unwrap(); 561 | db.get::("foo").unwrap(); 562 | }); 563 | threads.push(c); 564 | } 565 | for c in threads { 566 | c.join().unwrap(); 567 | } 568 | } 569 | 570 | #[test] 571 | fn single_save_without_file_name_ext() { 572 | let dir = tempdir().unwrap(); 573 | let subdir = dir.path().join("test"); 574 | let mut cfg = Config::default(); 575 | cfg.single = true; 576 | FileStore::new_with_cfg(&subdir, cfg).unwrap(); 577 | assert!(Path::new(&format!("{}.json", subdir.to_str().unwrap())).exists()); 578 | } 579 | 580 | #[test] 581 | fn single_get() { 582 | let dir = tempdir().unwrap(); 583 | let file_name = dir.path().join("test.json"); 584 | let mut cfg = Config::default(); 585 | cfg.single = true; 586 | let db = FileStore::new_with_cfg(&file_name, cfg).unwrap(); 587 | write_to_test_file(&file_name, "{\"x\":{\"x\":8},\"y\":{\"y\":9}}"); 588 | let y = db.get::("y").unwrap(); 589 | assert_eq!(y.y, 9); 590 | } 591 | 592 | #[test] 593 | fn single_get_non_existent() { 594 | let dir = tempdir().unwrap(); 595 | let file_name = dir.path().join("test.json"); 596 | let mut cfg = Config::default(); 597 | cfg.single = true; 598 | let db = FileStore::new_with_cfg(&file_name, cfg).unwrap(); 599 | let res = db.get::("foobarobject"); 600 | assert!(res.is_err()); 601 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 602 | } 603 | 604 | #[test] 605 | fn single_all() { 606 | let dir = tempdir().unwrap(); 607 | let file_name = dir.path().join("test.json"); 608 | let mut cfg = Config::default(); 609 | cfg.single = true; 610 | let db = FileStore::new_with_cfg(&file_name, cfg).unwrap(); 611 | write_to_test_file(&file_name, "{\"foo\":{\"x\":8},\"bar\":{\"x\":9}}"); 612 | let all: BTreeMap = db.all().unwrap(); 613 | assert_eq!(all.get("foo").unwrap().x, 8); 614 | assert_eq!(all.get("bar").unwrap().x, 9); 615 | } 616 | 617 | #[test] 618 | fn single_delete() { 619 | let dir = tempdir().unwrap(); 620 | let file_name = dir.path().join("test.json"); 621 | let mut cfg = Config::default(); 622 | cfg.single = true; 623 | let db = FileStore::new_with_cfg(file_name.clone(), cfg).unwrap(); 624 | write_to_test_file(&file_name, "{\"foo\":{\"x\":8},\"bar\":{\"x\":9}}"); 625 | db.delete("bar").unwrap(); 626 | assert_eq!(read_from_test_file(&file_name), "{\"foo\":{\"x\":8}}"); 627 | db.delete("foo").unwrap(); 628 | assert_eq!(read_from_test_file(&file_name), "{}"); 629 | } 630 | 631 | #[test] 632 | fn single_delete_non_existent() { 633 | let dir = tempdir().unwrap(); 634 | let file_name = dir.path().join("test.json"); 635 | let mut cfg = Config::default(); 636 | cfg.single = true; 637 | let db = FileStore::new_with_cfg(&file_name, cfg).unwrap(); 638 | let res = db.delete("blabla"); 639 | assert!(res.is_err()); 640 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 641 | } 642 | } 643 | } 644 | -------------------------------------------------------------------------------- /src/json_store.rs: -------------------------------------------------------------------------------- 1 | use std::{collections::BTreeMap, io::Result}; 2 | 3 | use serde::{Deserialize, Serialize}; 4 | 5 | pub trait JsonStore: Send + Sync { 6 | fn save(&self, obj: &T) -> Result 7 | where 8 | for<'de> T: Serialize + Deserialize<'de>; 9 | fn save_with_id(&self, obj: &T, id: &str) -> Result 10 | where 11 | for<'de> T: Serialize + Deserialize<'de>; 12 | fn get(&self, id: &str) -> Result 13 | where 14 | for<'de> T: Deserialize<'de>; 15 | fn all(&self) -> Result> 16 | where 17 | for<'de> T: Deserialize<'de>; 18 | fn delete(&self, id: &str) -> Result<()>; 19 | } 20 | -------------------------------------------------------------------------------- /src/lib.rs: -------------------------------------------------------------------------------- 1 | //! A simple JSON file store written in Rust. 2 | //! This is a port of the Node.js library 3 | //! [json-file-store](https://github.com/flosse/json-file-store/). 4 | //! 5 | //! **WARNING**: 6 | //! Don't use it if you want to persist a large amount of objects. 7 | //! Use a real DB instead. 8 | //! 9 | //! # Example 10 | //! 11 | //! ```rust,no_run 12 | //! use serde::{Serialize,Deserialize}; 13 | //! use jfs::Store; 14 | //! 15 | //! #[derive(Serialize,Deserialize)] 16 | //! struct Foo { 17 | //! foo: String 18 | //! } 19 | //! 20 | //! let db = Store::new("data").unwrap(); 21 | //! let f = Foo { foo: "bar".to_owned() }; 22 | //! let id = db.save(&f).unwrap(); 23 | //! let obj = db.get::(&id).unwrap(); 24 | //! db.delete(&id).unwrap(); 25 | //! ``` 26 | //! 27 | //! You can also store all data in one single JSON-File: 28 | //! 29 | //! ```rust,no_run 30 | //! let mut cfg = jfs::Config::default(); 31 | //! cfg.single = true; // false is default 32 | //! let db = jfs::Store::new_with_cfg("data",cfg); 33 | //! ``` 34 | //! 35 | //! If you like to pretty print the file content, set `pretty` to `true` 36 | //! and choose a number of whitespaces for the indention: 37 | //! 38 | //! ```rust,no_run 39 | //! let mut cfg = jfs::Config::default(); 40 | //! cfg.pretty = true; // false is default 41 | //! cfg.indent = 4; // 2 is default 42 | //! ``` 43 | //! 44 | //! Creating a store instance that is living in the memory can be done like this: 45 | //! 46 | //! ```rust,no_run 47 | //! let db = jfs::Store::new(jfs::IN_MEMORY).unwrap(); 48 | //! ``` 49 | 50 | use std::{ 51 | collections::BTreeMap, 52 | io::Result, 53 | path::{Path, PathBuf}, 54 | sync::Arc, 55 | }; 56 | 57 | use parking_lot::RwLock; 58 | use serde::{Deserialize, Serialize}; 59 | 60 | mod file_store; 61 | mod json_store; 62 | mod memory_store; 63 | 64 | use self::{file_store::FileStore, json_store::JsonStore, memory_store::MemoryStore}; 65 | 66 | pub use self::file_store::Config; 67 | 68 | #[derive(Debug, Clone)] 69 | pub struct Store(StoreType); 70 | 71 | #[derive(Debug, Clone)] 72 | enum StoreType { 73 | File(Arc>, PathBuf), 74 | Memory(MemoryStore), 75 | } 76 | 77 | pub const IN_MEMORY: &str = "::memory::"; 78 | 79 | impl Store { 80 | /// Opens a `Store` against the specified path. 81 | /// 82 | /// See `new_with_cfg(..)` for more details 83 | /// 84 | /// # Arguments 85 | /// 86 | /// * `path` - path to the db directory of JSON documents 87 | pub fn new>(path: P) -> Result { 88 | Self::new_with_cfg(path, Config::default()) 89 | } 90 | 91 | /// Opens a `Store` against the specified path with the given configuration 92 | /// 93 | /// If the `Store` already exists, it will be opened, otherwise this has the side-effect of creating the new `Store` 94 | /// and the backing directories and files. 95 | /// 96 | /// # Arguments 97 | /// 98 | /// * `path` - path to the db directory of JSON documents, if configured for single db mode then `.json` will be used as the extension (replacing any existing extension) 99 | /// * `cfg` - configuration for the DB instance 100 | pub fn new_with_cfg>(path: P, cfg: Config) -> Result { 101 | if path.as_ref() == Path::new(IN_MEMORY) { 102 | Ok(Self(StoreType::Memory(MemoryStore::default()))) 103 | } else { 104 | let s = FileStore::new_with_cfg(path, cfg)?; 105 | let p = s.path().to_path_buf(); 106 | Ok(Self(StoreType::File(Arc::new(RwLock::new(s)), p))) 107 | } 108 | } 109 | 110 | /// Returns the storage path for the backing JSON store. 111 | /// 112 | /// In single-file-mode this will be the JSON file location, 113 | /// otherwise it's the directory in which all JSON objects are stored. 114 | #[must_use] 115 | pub fn path(&self) -> &Path { 116 | match &self.0 { 117 | StoreType::File(_, p) => p, 118 | StoreType::Memory(_) => Path::new(IN_MEMORY), 119 | } 120 | } 121 | 122 | pub fn save(&self, obj: &T) -> Result 123 | where 124 | for<'de> T: Serialize + Deserialize<'de>, 125 | { 126 | match &self.0 { 127 | StoreType::File(f, _) => f.write().save(obj), 128 | StoreType::Memory(m) => m.save(obj), 129 | } 130 | } 131 | 132 | pub fn save_with_id(&self, obj: &T, id: &str) -> Result 133 | where 134 | for<'de> T: Serialize + Deserialize<'de>, 135 | { 136 | match &self.0 { 137 | StoreType::File(f, _) => f.write().save_with_id(obj, id), 138 | StoreType::Memory(m) => m.save_with_id(obj, id), 139 | } 140 | } 141 | 142 | pub fn get(&self, id: &str) -> Result 143 | where 144 | for<'de> T: Deserialize<'de>, 145 | { 146 | match &self.0 { 147 | StoreType::File(f, _) => f.read().get(id), 148 | StoreType::Memory(m) => m.get(id), 149 | } 150 | } 151 | 152 | pub fn all(&self) -> Result> 153 | where 154 | for<'de> T: Deserialize<'de>, 155 | { 156 | match &self.0 { 157 | StoreType::File(f, _) => f.read().all(), 158 | StoreType::Memory(m) => m.all(), 159 | } 160 | } 161 | 162 | pub fn delete(&self, id: &str) -> Result<()> { 163 | match &self.0 { 164 | StoreType::File(f, _) => f.write().delete(id), 165 | StoreType::Memory(m) => m.delete(id), 166 | } 167 | } 168 | } 169 | 170 | #[cfg(test)] 171 | mod tests { 172 | 173 | use super::*; 174 | use serde_derive::{Deserialize, Serialize}; 175 | use std::thread; 176 | use tempfile::tempdir; 177 | 178 | #[derive(Serialize, Deserialize)] 179 | struct Data { 180 | x: i32, 181 | } 182 | 183 | fn multi_threaded_write(store: Store) { 184 | let mut threads: Vec> = vec![]; 185 | for i in 0..20 { 186 | let db = store.clone(); 187 | let x = Data { x: i }; 188 | threads.push(thread::spawn(move || { 189 | db.save_with_id(&x, &i.to_string()).unwrap(); 190 | })); 191 | } 192 | for t in threads { 193 | t.join().unwrap(); 194 | } 195 | let all = store.all::().unwrap(); 196 | assert_eq!(all.len(), 20); 197 | for (id, data) in all { 198 | assert_eq!(data.x.to_string(), id); 199 | } 200 | } 201 | 202 | #[test] 203 | fn multi_threaded_write_with_single_file() { 204 | let dir = tempdir().expect("Could not create temporary directory"); 205 | let file = dir.path().join("db.json"); 206 | let mut cfg = Config::default(); 207 | cfg.single = true; 208 | let store = Store::new_with_cfg(file, cfg).unwrap(); 209 | multi_threaded_write(store); 210 | } 211 | 212 | #[test] 213 | fn multi_threaded_write_with_dir() { 214 | #[derive(Serialize, Deserialize)] 215 | struct Data { 216 | x: i32, 217 | } 218 | let dir = tempdir().expect("Could not create temporary directory"); 219 | let mut cfg = Config::default(); 220 | cfg.single = false; 221 | let store = Store::new_with_cfg(dir.path(), cfg).unwrap(); 222 | multi_threaded_write(store); 223 | } 224 | 225 | #[test] 226 | fn multi_threaded_write_in_memory() { 227 | #[derive(Serialize, Deserialize)] 228 | struct Data { 229 | x: i32, 230 | } 231 | let store = Store::new(IN_MEMORY).unwrap(); 232 | multi_threaded_write(store); 233 | } 234 | } 235 | -------------------------------------------------------------------------------- /src/memory_store.rs: -------------------------------------------------------------------------------- 1 | use std::{ 2 | collections::{BTreeMap, HashMap}, 3 | io::{Error, ErrorKind, Result}, 4 | sync::Arc, 5 | }; 6 | 7 | use uuid::Uuid; 8 | use parking_lot::{Mutex, RwLock}; 9 | use serde::{Deserialize, Serialize}; 10 | 11 | use crate::json_store::JsonStore; 12 | 13 | #[derive(Debug, Clone, Default)] 14 | pub struct MemoryStore { 15 | mem: Arc>>>, 16 | } 17 | 18 | impl JsonStore for MemoryStore { 19 | fn save(&self, obj: &T) -> Result 20 | where 21 | for<'de> T: Serialize + Deserialize<'de>, 22 | { 23 | self.save_with_id(obj, &Uuid::new_v4().to_string()) 24 | } 25 | 26 | fn save_with_id(&self, obj: &T, id: &str) -> Result 27 | where 28 | for<'de> T: Serialize + Deserialize<'de>, 29 | { 30 | let json = serde_json::to_string(&obj).map_err(|err| Error::new(ErrorKind::Other, err))?; 31 | let map = self.mem.read(); 32 | if let Some(val) = map.get(id) { 33 | let mut value_guard = val.lock(); 34 | *value_guard = json; 35 | return Ok(id.to_owned()); 36 | } 37 | drop(map); 38 | let mut map = self.mem.write(); 39 | map.insert(id.to_owned(), Mutex::new(json)); 40 | Ok(id.to_owned()) 41 | } 42 | 43 | fn get(&self, id: &str) -> Result 44 | where 45 | for<'de> T: Deserialize<'de>, 46 | { 47 | let map = self.mem.read(); 48 | let value = map 49 | .get(id) 50 | .ok_or_else(|| Error::new(ErrorKind::NotFound, "no such object"))?; 51 | let value_guard = value.lock(); 52 | serde_json::from_str(&value_guard).map_err(|err| Error::new(ErrorKind::Other, err)) 53 | } 54 | 55 | fn all(&self) -> Result> 56 | where 57 | for<'de> T: Deserialize<'de>, 58 | { 59 | let mut result = BTreeMap::new(); 60 | let map = self.mem.read(); 61 | for x in map.iter() { 62 | let (k, v) = x; 63 | let value_guard = v.lock(); 64 | if let Ok(r) = serde_json::from_str(&value_guard) { 65 | result.insert(k.clone(), r); 66 | } 67 | } 68 | Ok(result) 69 | } 70 | 71 | fn delete(&self, id: &str) -> Result<()> { 72 | let mut map = self.mem.write(); 73 | if map.contains_key(id) { 74 | map.remove(id); 75 | } else { 76 | return Err(Error::new(ErrorKind::NotFound, "no such object")); 77 | } 78 | Ok(()) 79 | } 80 | } 81 | 82 | #[cfg(test)] 83 | mod tests { 84 | use super::*; 85 | use serde_derive::{Deserialize, Serialize}; 86 | use std::thread; 87 | 88 | #[derive(Serialize, Deserialize)] 89 | struct X { 90 | x: u32, 91 | } 92 | 93 | #[derive(Serialize, Deserialize)] 94 | struct Y { 95 | y: i32, 96 | } 97 | 98 | #[derive(Serialize, Deserialize)] 99 | struct Empty {} 100 | 101 | #[derive(Serialize, Deserialize)] 102 | struct Z { 103 | z: f32, 104 | } 105 | 106 | #[test] 107 | fn save() { 108 | let db = MemoryStore::default(); 109 | let data = X { x: 56 }; 110 | let id = db.save(&data).unwrap(); 111 | assert_eq!(db.mem.read().len(), 1); 112 | let json = db.mem.read().get(&id).unwrap().lock().clone(); 113 | assert_eq!(json, "{\"x\":56}"); 114 | } 115 | 116 | #[test] 117 | fn update() { 118 | let db = MemoryStore::default(); 119 | let mut data = X { x: 56 }; 120 | let id = db.save(&data).unwrap(); 121 | let json = db.mem.read().get(&id).unwrap().lock().clone(); 122 | assert_eq!(json, "{\"x\":56}"); 123 | data.x += 1; 124 | db.save_with_id(&data, &id).unwrap(); 125 | let json = db.mem.read().get(&id).unwrap().lock().clone(); 126 | assert_eq!(json, "{\"x\":57}"); 127 | } 128 | 129 | #[test] 130 | fn save_and_read_multi_threaded() { 131 | let db = MemoryStore::default(); 132 | let mut threads: Vec> = vec![]; 133 | let x = X { x: 56 }; 134 | db.save_with_id(&x, "bla").unwrap(); 135 | for i in 0..20 { 136 | let x = X { x: i }; 137 | let db_clone = db.clone(); 138 | threads.push(thread::spawn(move || { 139 | db_clone.save_with_id(&x, "bla").unwrap(); 140 | })); 141 | } 142 | for _ in 0..20 { 143 | let db_clone = db.clone(); 144 | threads.push(thread::spawn(move || { 145 | db_clone.get::("bla").unwrap(); 146 | })); 147 | } 148 | for c in threads { 149 | c.join().unwrap(); 150 | } 151 | } 152 | 153 | #[test] 154 | fn save_empty_obj() { 155 | let db = MemoryStore::default(); 156 | let id = db.save(&Empty {}).unwrap(); 157 | let json = db.mem.read().get(&id).unwrap().lock().clone(); 158 | assert_eq!(json, "{}"); 159 | } 160 | 161 | #[test] 162 | fn save_with_id() { 163 | let db = MemoryStore::default(); 164 | let data = Y { y: -7 }; 165 | db.save_with_id(&data, "foo").unwrap(); 166 | let json = db.mem.read().get("foo").unwrap().lock().clone(); 167 | assert_eq!(json, "{\"y\":-7}"); 168 | } 169 | 170 | #[test] 171 | fn get() { 172 | let db = MemoryStore::default(); 173 | db.mem 174 | .write() 175 | .insert("foo".to_string(), Mutex::new("{\"z\":9.9}".to_string())); 176 | let obj: Z = db.get("foo").unwrap(); 177 | assert_eq!(obj.z, 9.9); 178 | } 179 | 180 | #[test] 181 | fn get_non_existent() { 182 | let db = MemoryStore::default(); 183 | let res = db.get::("foobarobject"); 184 | assert!(res.is_err()); 185 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 186 | } 187 | 188 | #[test] 189 | fn all() { 190 | let db = MemoryStore::default(); 191 | 192 | #[derive(Deserialize, Serialize)] 193 | struct X { 194 | x: u32, 195 | y: u32, 196 | } 197 | db.mem.write().insert( 198 | "foo".to_string(), 199 | Mutex::new("{\"x\":1,\"y\":0}".to_string()), 200 | ); 201 | db.mem 202 | .write() 203 | .insert("bar".to_string(), Mutex::new("{\"y\":2}".to_string())); 204 | 205 | let all_x: BTreeMap = db.all().unwrap(); 206 | let all_y: BTreeMap = db.all().unwrap(); 207 | assert_eq!(all_x.get("foo").unwrap().x, 1); 208 | assert!(all_x.get("bar").is_none()); 209 | assert_eq!(all_y.get("bar").unwrap().y, 2); 210 | } 211 | 212 | #[test] 213 | fn delete() { 214 | let db = MemoryStore::default(); 215 | let data = Y { y: 88 }; 216 | let id = db.save(&data).unwrap(); 217 | db.get::(&id).unwrap(); 218 | assert_eq!(db.mem.read().len(), 1); 219 | db.delete(&id).unwrap(); 220 | assert_eq!(db.mem.read().len(), 0); 221 | assert!(db.get::(&id).is_err()); 222 | assert!(db.delete(&id).is_err()); 223 | } 224 | 225 | #[test] 226 | fn delete_non_existent() { 227 | let db = MemoryStore::default(); 228 | let res = db.delete("blabla"); 229 | assert!(res.is_err()); 230 | assert_eq!(res.err().unwrap().kind(), ErrorKind::NotFound); 231 | } 232 | } 233 | --------------------------------------------------------------------------------