From ef9f6f5f1bf3e94824d72205b005abf1ead236be Mon Sep 17 00:00:00 2001 From: Coin de Gamma Date: Fri, 6 Sep 2024 12:28:06 +0000 Subject: [PATCH] once_cell and contants --- Cargo.toml | 1 + src/main.rs | 16 ++++++++++------ 2 files changed, 11 insertions(+), 6 deletions(-) diff --git a/Cargo.toml b/Cargo.toml index 5ace58e..fab0594 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -7,3 +7,4 @@ edition = "2021" [dependencies] clap = { version = "4.5.16", features = ["derive"] } +once_cell = "1.19.0" diff --git a/src/main.rs b/src/main.rs index f4d1430..d958211 100644 --- a/src/main.rs +++ b/src/main.rs @@ -3,6 +3,8 @@ mod db; use db::{DB, Item}; +use once_cell::sync::Lazy; + use clap::{Parser, Subcommand}; use std::fs; @@ -10,8 +12,10 @@ use std::io::{self, Write}; use std::path::Path; -const STORAGE_FOLDER: &str = "storage"; -const STORAGE_PATH: &str = "storage/db.mps"; // TODO: concat from STORAGE_FOLDER +static STORAGE_FOLDER: &str = "storage"; +static STORAGE_PATH: Lazy = Lazy::new(|| { + format!("{}/db.mps", STORAGE_FOLDER) +}); #[derive(Parser)] @@ -51,7 +55,7 @@ fn init() -> io::Result<()> { fs::create_dir(STORAGE_FOLDER)?; println!("Storage folder created"); - fs::File::create(STORAGE_PATH)?; + fs::File::create(&*STORAGE_PATH)?; println!("Storage db created."); println!("Initialization complete."); println!(""); @@ -61,7 +65,7 @@ fn init() -> io::Result<()> { } fn add(id: &String) -> io::Result<()> { - let mut db = DB::new(STORAGE_PATH)?; + let mut db = DB::new(&*STORAGE_PATH)?; if db.contains(id) { // TODO: ask to edit existing in outer function which invoked this one return Err(io::Error::new( @@ -71,13 +75,13 @@ fn add(id: &String) -> io::Result<()> { } db.items.insert(Item::from(id.clone())); - db.dump(STORAGE_PATH)?; + db.dump(&*STORAGE_PATH)?; Ok(()) } fn list() -> io:: Result<()> { - let db = DB::new(STORAGE_PATH)?; + let db = DB::new(&STORAGE_PATH)?; let mut vec: Vec<_> = db.items.iter().collect(); vec.sort(); for item in &vec {