diff --git a/src/main.rs b/src/main.rs index 8c6a27c..ea3be81 100644 --- a/src/main.rs +++ b/src/main.rs @@ -105,7 +105,7 @@ fn main() { ) .unwrap(); - let storage = store::Store {}; + let mut storage = store::Store::new(); let mut volume = storage.volume().map_or_else( || { diff --git a/src/store.rs b/src/store.rs index 5e16c68..cba0c56 100644 --- a/src/store.rs +++ b/src/store.rs @@ -1,13 +1,48 @@ +use std::{io::Seek, path::PathBuf}; + +#[cfg(not(target_os = "emscripten"))] +pub struct Store { + file: std::fs::File, +} + +#[cfg(target_os = "emscripten")] pub struct Store; #[cfg(not(target_os = "emscripten"))] impl Store { - pub fn volume(&self) -> Option { - None + pub fn new () -> Self { + let path = Store::get_path(); + let file = std::fs::OpenOptions::new() + .read(true) + .write(true) + .create(true) + .open(&path) + .unwrap(); + Store { file } } - pub fn set_volume(&self, volume: u32) { - // Do nothing + fn get_path() -> PathBuf { + use std::env; + let mut path = env::current_exe().unwrap(); + path.pop(); + path.push("volume.txt"); + path + } + + pub fn volume(&mut self) -> Option { + use std::io::Read; + + let mut buffer = String::new(); + self.file.read_to_string(&mut buffer).unwrap(); + buffer.trim().parse::().ok() + } + + pub fn set_volume(&mut self, volume: u32) { + use std::io::Write; + + self.file.set_len(0).unwrap(); + self.file.seek(std::io::SeekFrom::Start(0)).unwrap(); + write!(self.file, "{}", volume).unwrap(); } } @@ -19,6 +54,23 @@ extern "C" { #[cfg(target_os = "emscripten")] impl Store { + pub fn new () -> Self { + Store + } + + pub fn volume(&self) -> Option { + // Use local storage to try and read volume + let script = "localStorage.getItem('volume')"; + let response = Store::run_script_string(&script); + response.parse::().ok() + } + + pub fn set_volume(&self, volume: u32) { + // Use local storage to set volume + let script = format!("localStorage.setItem('volume', '{}')", volume); + Store::run_script_string(&script); + } + fn run_script(script: &str) { use std::ffi::CString; @@ -38,17 +90,4 @@ impl Store { String::from(c_str.to_str().unwrap()) } } - - pub fn volume(&self) -> Option { - // Use local storage to try and read volume - let script = "localStorage.getItem('volume')"; - let response = Store::run_script_string(&script); - response.parse::().ok() - } - - pub fn set_volume(&self, volume: u32) { - // Use local storage to set volume - let script = format!("localStorage.setItem('volume', '{}')", volume); - Store::run_script_string(&script); - } } \ No newline at end of file