partialy implement Query, also add date

This commit is contained in:
2019-05-07 17:36:32 +02:00
parent cfc2ff5886
commit cb2b8339a6
4 changed files with 162 additions and 16 deletions

View File

@ -0,0 +1,89 @@
use serde::de::Error;
use serde::Serialize;
use serde::{Deserialize, Deserializer, Serializer};
#[derive(Clone, Debug, Eq, PartialEq, Hash, Ord, PartialOrd)]
pub struct Date {
pub year: u16,
pub month: u8,
pub day: u8,
}
impl Date {
#[cfg(test)]
pub fn new(year: u16, month: u8, day: u8) -> Self {
Date { year, month, day }
}
pub fn from_str(input: &str) -> Option<Self> {
let mut parts = input.splitn(3, "-");
let year = parts.next()?.parse::<u16>().ok()?;
let month = parts.next()?.parse::<u8>().ok()?;
let day = parts.next()?.parse::<u8>().ok()?;
if month > 12 {
return None;
}
if day > 31 {
return None;
}
Some(Date { year, month, day })
}
}
impl Serialize for Date {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_str(&format!(
"{:04}-{:02}-{:02}",
self.year, self.month, self.day
))
}
}
impl<'de> Deserialize<'de> for Date {
fn deserialize<D>(deserializer: D) -> Result<Date, D::Error>
where
D: Deserializer<'de>,
{
let data = String::deserialize(deserializer)?;
match Date::from_str(&data) {
Some(date) => Ok(date),
None => Err(D::Error::custom(
"Expected a String in this format: YYYY-MM-DD.",
)),
}
}
}
#[cfg(test)]
mod test {
use super::*;
#[test]
fn order() {
// Other Test not needed, since the Ord is derived.
assert!(Date::new(2019, 10, 10) > Date::new(2018, 10, 10));
assert!(Date::new(2018, 11, 10) > Date::new(2018, 10, 10));
assert!(Date::new(2018, 10, 11) > Date::new(2018, 10, 10));
}
#[test]
fn from_str() {
assert_eq!(Some(Date::new(2019, 10, 10)), Date::from_str("2019-10-10"));
assert_eq!(Some(Date::new(2019, 1, 1)), Date::from_str("2019-1-1"));
assert_eq!(None, Date::from_str("2019-1-1-444"));
assert_eq!(
Some(Date::new(2019, 1, 1)),
Date::from_str("2019-0000000000001-00000001")
);
assert_eq!(None, Date::from_str("400-400-400"));
}
}

View File

@ -8,6 +8,9 @@ use std::io;
mod sha256;
pub use sha256::Sha256;
mod date;
pub use date::Date;
mod texture_format;
pub use texture_format::TextureFormat;
@ -17,7 +20,8 @@ pub struct Texture {
pub name: String,
pub tags: Vec<String>,
pub format: TextureFormat,
pub resolution: (usize, usize),
pub added_on: Date,
pub resolution: (u64, u64),
pub texture_hash: Sha256,
}