morethantext-web/src/morethantext/fieldtype/mod.rs

90 lines
2.2 KiB
Rust

mod static_string;
use crate::morethantext::error::MTTError;
use static_string::StaticString;
use std::fmt;
pub enum FieldType {
StaticString(StaticString),
}
impl FieldType {
fn new(ftype: &str, data: &str) -> Result<Self, MTTError> {
let field = match ftype {
"StaticString" => StaticString::new(data),
_ => Err(MTTError::new(format!(
"field type {} does not exist",
ftype
))),
};
match field {
Ok(fld) => Ok(fld.into()),
Err(e) => Err(e),
}
}
}
impl fmt::Display for FieldType {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
FieldType::StaticString(data) => write!(f, "{}", data),
}
}
}
impl From<StaticString> for FieldType {
fn from(data: StaticString) -> Self {
FieldType::StaticString(data)
}
}
#[cfg(test)]
mod converstion {
use super::*;
#[test]
fn from_static_string() {
let data = "a static string";
let field = StaticString::new(data).unwrap();
let ftype: FieldType = field.into();
assert!(
ftype.to_string() == data,
"\n\nGot: {}\nWant: {}",
ftype.to_string(),
data
);
}
#[test]
fn bad_field_type() -> Result<(), String> {
let field_type = "dragon";
let err_msg = format!("field type {} does not exist", field_type);
match FieldType::new(field_type, "marmalade") {
Ok(_) => Err("Should have returned an error.".to_string()),
Err(err) => {
if err.to_string() == err_msg {
Ok(())
} else {
Err(format!(
"Error message is incorrect: Got: '{}' Want: '{}'",
err.to_string(),
err_msg
))
}
}
}
}
#[test]
fn new_static_string() {
let data = "This is a test.";
let field = FieldType::new("StaticString", data).unwrap();
assert!(
field.to_string() == data,
"\n\nGot: {}\nWant: {}\n\n",
field.to_string(),
data
);
}
}