Add FileHash type, custom type for an ID

This commit is contained in:
Matthias Beyer 2015-12-08 17:50:13 +01:00
parent dd7b412976
commit 8a7d4b8aaf
2 changed files with 78 additions and 8 deletions

68
src/storage/file/hash.rs Normal file
View file

@ -0,0 +1,68 @@
use std::convert::{From, Into};
use std::error::Error;
use std::fmt::{Debug, Display, Formatter};
use std::fmt;
use uuid::Uuid;
#[derive(Clone)]
#[derive(Debug)]
#[derive(PartialEq)]
#[derive(Eq)]
pub struct FileHash {
hash: String,
}
impl FileHash {
pub fn invalid() -> FileHash {
FileHash { hash: String::from("") }
}
}
impl From<String> for FileHash {
fn from(s: String) -> FileHash {
FileHash { hash: s }
}
}
impl<'a> From<&'a String> for FileHash {
fn from(s: &'a String) -> FileHash {
FileHash::from(s.clone())
}
}
impl From<Uuid> for FileHash {
fn from(u: Uuid) -> FileHash {
FileHash::from(u.to_hyphenated_string())
}
}
impl<'a> From<&'a str> for FileHash {
fn from(s: &str) -> FileHash {
FileHash::from(String::from(s))
}
}
impl Into<String> for FileHash {
fn into(self) -> String {
self.hash
}
}
impl Display for FileHash {
fn fmt(&self, fmt: &mut Formatter) -> fmt::Result {
write!(fmt, "{}", self.hash);
Ok(())
}
}

View file

@ -7,6 +7,8 @@ use std::result::Result;
use regex::Regex;
use storage::file::hash::FileHash;
#[derive(Debug)]
#[derive(Clone)]
#[derive(PartialEq)]
@ -51,13 +53,13 @@ impl From<String> for FileIDType {
#[derive(Clone)]
pub struct FileID {
id: Option<String>,
id: Option<FileHash>,
id_type: FileIDType,
}
impl FileID {
pub fn new(id_type: FileIDType, id: String) -> FileID {
pub fn new(id_type: FileIDType, id: FileHash) -> FileID {
FileID {
id: Some(id),
id_type: id_type,
@ -68,7 +70,7 @@ impl FileID {
self.id_type.clone()
}
pub fn get_id(&self) -> Option<String> {
pub fn get_id(&self) -> Option<FileHash> {
self.id.clone()
}
@ -96,13 +98,13 @@ impl Display for FileID {
}
impl Into<String> for FileID {
impl Into<FileHash> for FileID {
fn into(self) -> String {
fn into(self) -> FileHash {
if let Some(id) = self.id {
id.clone()
} else {
String::from("INVALID")
FileHash::invalid()
}
}
@ -156,13 +158,13 @@ impl<'a> From<&'a String> for FileID {
_ => {},
}
Some(FileID::new(idtype, String::from(hash)))
Some(FileID::new(idtype, FileHash::from(hash)))
}).unwrap_or({
debug!("Did not match");
debug!("It is no path, actually. So we assume it is an ID already");
FileID {
id_type: FileIDType::NONE,
id: Some(string.clone()),
id: Some(FileHash::from(string)),
}
})
}