Browse Source

basic bae64 storage

db-refactoring
Coin de Gamma 3 months ago
parent
commit
1b779459f1
  1. 1
      Cargo.toml
  2. 23
      src/db.rs
  3. 3
      src/main.rs

1
Cargo.toml

@ -6,6 +6,7 @@ edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html # See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies] [dependencies]
base64 = "0.22.1"
clap = { version = "4.5.16", features = ["derive"] } clap = { version = "4.5.16", features = ["derive"] }
once_cell = "1.19.0" once_cell = "1.19.0"
tempfile = "3.12.0" tempfile = "3.12.0"

23
src/db.rs

@ -1,3 +1,5 @@
use base64::prelude::*;
use std::collections::HashSet; use std::collections::HashSet;
use std::hash::{Hash, Hasher}; use std::hash::{Hash, Hasher};
@ -55,6 +57,14 @@ impl Ord for Item {
} }
} }
fn decode(line: String) -> Result<String, io::Error> {
let content = BASE64_STANDARD.decode(line).map_err(|e| io::Error::new(io::ErrorKind::InvalidData, e))?;
match String::from_utf8(content) {
Ok(s) => Ok(s),
Err(e) => Err(io::Error::new(io::ErrorKind::InvalidData, e))
}
}
pub struct DB { pub struct DB {
pub items: HashSet::<Item>, pub items: HashSet::<Item>,
path: String path: String
@ -65,11 +75,18 @@ impl DB {
let file = fs::File::open(path)?; let file = fs::File::open(path)?;
let reader = io::BufReader::new(file); let reader = io::BufReader::new(file);
let mut items = HashSet::<Item>::new(); let mut items = HashSet::<Item>::new();
let mut id: Option<String> = None;
for line in reader.lines() { for line in reader.lines() {
match line { match line {
Ok(id) => { Ok(line) => {
// TODO: check content // TODO: check content
items.insert(Item::from_d(id)); if id.is_none() {
id = Some(line);
} else {
let content = decode(line)?;
items.insert(Item::from(id.unwrap(), content));
id = None;
}
}, },
Err(e) => { Err(e) => {
eprintln!("Error reading line, {}", e); eprintln!("Error reading line, {}", e);
@ -97,6 +114,8 @@ impl DB {
for item in self.items.iter() { for item in self.items.iter() {
writeln!(file, "{}", item.id)?; writeln!(file, "{}", item.id)?;
let content = BASE64_STANDARD.encode(item.content.clone());
writeln!(file, "{}", content)?;
} }
Ok(()) Ok(())

3
src/main.rs

@ -77,9 +77,6 @@ fn add(id: &String) -> io::Result<()> {
// TODO: implement encryption // TODO: implement encryption
let content = editor::open_to_edit()?; let content = editor::open_to_edit()?;
println!("Content");
println!("--------");
println!("{}", content);
db.items.insert(Item::from(id.clone(), content)); db.items.insert(Item::from(id.clone(), content));
db.dump()?; db.dump()?;

Loading…
Cancel
Save