From 939761c2d06142b0a2bb5be5b0fb4480d059c6ea Mon Sep 17 00:00:00 2001
From: Hadi Chokr <158838697+silverhadch@users.noreply.github.com>
Date: Thu, 24 Oct 2024 00:02:36 +0200
Subject: [PATCH] Adding the helper function in the GUI Version (too). (#29)

---
 plastic_ui/src/main.rs | 31 ++++++++++++++-----------------
 1 file changed, 14 insertions(+), 17 deletions(-)

diff --git a/plastic_ui/src/main.rs b/plastic_ui/src/main.rs
index f6c1d51..b865020 100644
--- a/plastic_ui/src/main.rs
+++ b/plastic_ui/src/main.rs
@@ -89,31 +89,28 @@ impl App {
     }
 
     fn save_state(&mut self, slot: u8) {
-        if self.nes.is_empty() {
-            return;
+        if let Some(path) = self.get_save_state_path(slot) {
+            let file = fs::File::create(&path).unwrap();
+            self.nes.save_state(&file).unwrap();
         }
-
-        let base_saved_states_dir = base_save_state_folder().unwrap();
-        let filename = self.nes.save_state_file_name(slot).unwrap();
-        let path = base_saved_states_dir.join(&filename);
-
-        let file = fs::File::create(&path).unwrap();
-
-        self.nes.save_state(&file).unwrap();
     }
 
     fn load_state(&mut self, slot: u8) {
-        if self.nes.is_empty() {
-            return;
+        if let Some(path) = self.get_save_state_path(slot) {
+            let file = fs::File::open(&path).unwrap();
+            self.nes.load_state(&file).unwrap();
         }
+    }
 
-        let base_saved_states_dir = base_save_state_folder().unwrap();
-        let filename = self.nes.save_state_file_name(slot).unwrap();
-        let path = base_saved_states_dir.join(&filename);
+    fn get_save_state_path(&self, slot: u8) -> Option<std::path::PathBuf> {
+        if self.nes.is_empty() {
+            return None;
+        }
 
-        let file = fs::File::open(&path).unwrap();
+        let base_saved_states_dir = base_save_state_folder()?;
+        let filename = self.nes.save_state_file_name(slot)?;
 
-        self.nes.load_state(&file).unwrap();
+        Some(base_saved_states_dir.join(filename))
     }
 
     fn handle_input(&mut self, ctx: &egui::Context) {