From c9ea18f9ec7cb3d8ec5f8091cffcf7fb697a2104 Mon Sep 17 00:00:00 2001 From: phoenix Date: Fri, 24 Oct 2025 12:37:18 -0400 Subject: [PATCH] tsk-76: Adding function to simplify getting path of Song --- src/constants.rs | 6 ++++++ src/song.rs | 10 ++++++++-- src/util/mod.rs | 13 +++++++++++++ 3 files changed, 27 insertions(+), 2 deletions(-) create mode 100644 src/util/mod.rs diff --git a/src/constants.rs b/src/constants.rs index 4a982b1..4432a85 100644 --- a/src/constants.rs +++ b/src/constants.rs @@ -12,3 +12,9 @@ pub mod file_extensions { pub const PNGEXTENSION: &str = ".png"; } } + +pub mod error { + pub const DIRECTORY_NOT_INITIALIZED: &str = "Directory has not been initialized"; + pub const FILENAME_NOT_INITIALIZED: &str = "Filename has not bee initialized"; + pub const LAST_CHARACTER_IN_DIRECTORY: &str = "Could not access last character of directory"; +} diff --git a/src/song.rs b/src/song.rs index 5d5f35d..5254c83 100644 --- a/src/song.rs +++ b/src/song.rs @@ -71,14 +71,15 @@ impl Song { pub fn song_path(&self) -> Result { if self.directory.is_empty() { - return Err(std::io::Error::other("Directory has not been initialized")); + return Err(std::io::Error::other(crate::constants::error::DIRECTORY_NOT_INITIALIZED)); } else if self.filename.is_empty() { - return Err(std::io::Error::other("Filename has not bee initialized")); + return Err(std::io::Error::other(crate::constants::error::FILENAME_NOT_INITIALIZED)); } let directory = &self.directory; let last_index = directory.len() - 1; + /* if let Some(character) = directory.chars().nth(last_index) { let buffer: String = if character != '/' { directory.clone() + "/" @@ -92,6 +93,11 @@ impl Song { "Could not access last character of directory", )) } + */ + match crate::util::concatenate_path(&directory, &self.filename, last_index) { + Ok(path) => Ok(path), + Err(err) => Err(err) + } } /// Saves the song to the filesystem using the song's data diff --git a/src/util/mod.rs b/src/util/mod.rs new file mode 100644 index 0000000..8543f65 --- /dev/null +++ b/src/util/mod.rs @@ -0,0 +1,13 @@ +pub fn concatenate_path(directory: &str, filename: &str, last_index: usize) -> Result { + if let Some(character) = directory.chars().nth(last_index) { + let buffer: String = if character != '/' { + format!("{directory}/") + } else { + String::from(directory) + }; + + Ok(format!("{buffer}{filename}")) + } else { + Err(std::io::Error::other(crate::constants::error::LAST_CHARACTER_IN_DIRECTORY)) + } +}