Some code improvements

This commit is contained in:
Wojciech Kozlowski 2023-03-29 14:56:23 +09:00
parent e2332f79ec
commit cadc799495
2 changed files with 33 additions and 22 deletions

View File

@ -1,5 +1,6 @@
use std::fs::File;
use std::io::{Read, Write};
use std::path::Path;
use serde::de::DeserializeOwned;
use serde::Serialize;
@ -13,10 +14,16 @@ pub struct DatabaseJson {
}
impl DatabaseJson {
pub fn new(file: File) -> Self {
Self {
database_file: file,
}
pub fn reader(path: &Path) -> Result<Self, std::io::Error> {
Ok(Self {
database_file: File::open(path)?,
})
}
pub fn writer(path: &Path) -> Result<Self, std::io::Error> {
Ok(Self {
database_file: File::create(path)?,
})
}
}
@ -41,7 +48,8 @@ impl DatabaseWrite for DatabaseJson {
S: Serialize,
{
let serialized = serde_json::to_string(&collection)?;
self.database_file.write_all(serialized.as_bytes())
self.database_file.write_all(serialized.as_bytes())?;
Ok(())
}
}
@ -134,35 +142,36 @@ mod tests {
#[test]
fn write() {
let data = test_data();
let write_data = test_data();
let temp_file = NamedTempFile::new().unwrap();
DatabaseJson::new(File::create(temp_file.path()).unwrap())
.write(&data)
DatabaseJson::writer(temp_file.path())
.unwrap()
.write(&write_data)
.unwrap();
// Compare files.
let mut data_str = String::new();
let mut write_data_str = String::new();
File::open(temp_file.path())
.unwrap()
.read_to_string(&mut data_str)
.read_to_string(&mut write_data_str)
.unwrap();
let mut test_str = String::new();
let mut test_data_str = String::new();
File::open(TEST_FILENAME)
.unwrap()
.read_to_string(&mut test_str)
.read_to_string(&mut test_data_str)
.unwrap();
assert_eq!(data_str, test_str);
assert_eq!(write_data_str, test_data_str);
}
#[test]
fn read() {
let mut data: Vec<ReleaseGroup> = vec![];
DatabaseJson::new(File::open(Path::new(TEST_FILENAME)).unwrap())
.read(&mut data)
let mut read_data: Vec<ReleaseGroup> = vec![];
DatabaseJson::reader(Path::new(TEST_FILENAME))
.unwrap()
.read(&mut read_data)
.unwrap();
assert_eq!(data, test_data());
assert_eq!(read_data, test_data());
}
#[test]
@ -172,10 +181,12 @@ mod tests {
let temp_file = NamedTempFile::new().unwrap();
DatabaseJson::new(File::create(temp_file.path()).unwrap())
DatabaseJson::writer(temp_file.path())
.unwrap()
.write(&write_data)
.unwrap();
DatabaseJson::new(File::open(temp_file.path()).unwrap())
DatabaseJson::reader(temp_file.path())
.unwrap()
.read(&mut read_data)
.unwrap();

View File

@ -1,12 +1,12 @@
//! MusicHoard - a music collection manager.
use serde::{Deserialize, Serialize};
use uuid;
use uuid::Uuid;
mod database;
/// [MusicBrainz Identifier](https://musicbrainz.org/doc/MusicBrainz_Identifier) (MBID).
pub type Mbid = uuid::Uuid;
pub type Mbid = Uuid;
/// [Artist](https://musicbrainz.org/doc/Artist).
#[derive(Debug, Deserialize, Serialize, PartialEq)]