strval 0.5.0

Parse strings into values
Documentation
use std::{fmt, marker::PhantomData, str::FromStr};

#[cfg(feature = "rusqlite")]
use rusqlite::{
  ToSql,
  types::{FromSql, FromSqlError, FromSqlResult, ToSqlOutput, ValueRef}
};

use crate::{Controller, StrVal, err::Error};


#[derive(Clone, Default)]
pub struct AnyStr;

impl Controller for AnyStr {
  type Type = String;

  fn def() -> String {
    String::new()
  }

  fn validate(_val: &Self::Type) -> Result<(), Error> {
    Ok(())
  }
}


/// A plain text string.
#[derive(Debug, Default, Clone)]
pub struct Str<C = AnyStr> {
  val: String,
  _marker: PhantomData<C>
}

impl<C> StrVal for Str<C>
where
  C: Controller<Type = String>
{
  type Type = String;

  fn set(&mut self, val: &str) -> Result<Self::Type, Error> {
    let s = val.to_string();

    C::validate(&s)?;

    self.val = s;
    Ok(val.to_string())
  }

  fn get(&self) -> Self::Type {
    self.val.clone()
  }

  fn val_str(&self) -> Option<String> {
    None
  }

  fn get_str_vals(&self) -> (String, Option<String>) {
    (self.val.clone(), None)
  }
}

impl<C> AsRef<str> for Str<C> {
  fn as_ref(&self) -> &str {
    &self.val
  }
}

impl<C> fmt::Display for Str<C> {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.val)
  }
}

impl<C> FromStr for Str<C>
where
  C: Controller<Type = String>
{
  type Err = Error;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    let s = s.to_string();

    C::validate(&s)?;

    Ok(Self {
      val: s,
      _marker: PhantomData
    })
  }
}


#[cfg(feature = "rusqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusqlite")))]
impl<C> ToSql for Str<C> {
  fn to_sql(&self) -> Result<ToSqlOutput<'_>, rusqlite::Error> {
    self.val.to_sql()
  }
}

#[cfg(feature = "rusqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusqlite")))]
impl<C> FromSql for Str<C>
where
  C: Controller<Type = String>
{
  #[inline]
  fn column_result(value: ValueRef<'_>) -> FromSqlResult<Self> {
    let s = String::column_result(value)?;
    s.parse::<Self>()
      .map_err(|e| FromSqlError::Other(Box::new(e)))
  }
}


#[cfg(test)]
mod tests {
  use super::*;

  #[cfg(feature = "rusqlite")]
  use rusqlite::{Connection, params};

  #[derive(Default)]
  pub struct NoFlynn;

  impl Controller for NoFlynn {
    type Type = String;

    fn def() -> String {
      String::new()
    }

    fn validate(val: &Self::Type) -> Result<(), Error> {
      if val == "flynn" {
        Err(Error::invalid("flynn not allowed"))
      } else {
        Ok(())
      }
    }
  }

  #[test]
  fn set_get() {
    let mut s = Str::<AnyStr>::default();
    s.set("elena fisher").unwrap();
    assert_eq!(s.as_ref(), "elena fisher");
  }

  #[test]
  #[should_panic(expected = "Invalid(\"flynn not allowed\")")]
  fn invalid() {
    let mut s = Str::<NoFlynn>::default();
    s.set("nathan drake").unwrap();
    s.set("flynn").unwrap();
  }

  #[cfg(feature = "rusqlite")]
  fn memdb() -> Result<Connection, rusqlite::Error> {
    let conn = Connection::open_in_memory()?;
    conn.execute_batch(
      "CREATE TABLE tbl (id INTEGER PRIMARY KEY, txtval TEXT)"
    )?;
    Ok(conn)
  }

  #[cfg(feature = "rusqlite")]
  #[test]
  fn insert_query() {
    let conn = memdb().unwrap();

    let s = Str::<AnyStr>::from_str("chloe frazer").unwrap();
    conn
      .execute("INSERT INTO tbl (id, txtval) VALUES (?, ?);", params![1, s])
      .unwrap();

    let mut stmt = conn.prepare("SELECT txtval FROM tbl WHERE id=?;").unwrap();

    let s: Str = stmt.query_one([1], |row| row.get(0)).unwrap();
    assert_eq!(s.get(), "chloe frazer");
  }

  #[cfg(feature = "rusqlite")]
  #[test]
  #[should_panic(expected = "FromSqlConversionFailure(0, Text, \
                             Invalid(\"flynn not allowed\"))")]
  fn bad_query() {
    let conn = memdb().unwrap();

    conn
      .execute(
        "INSERT INTO tbl (id, txtval) VALUES (?, ?);",
        params![1, "flynn"]
      )
      .unwrap();

    let mut stmt = conn.prepare("SELECT txtval FROM tbl WHERE id=?;").unwrap();

    let _s: Str<NoFlynn> = stmt.query_one([1], |row| row.get(0)).unwrap();
  }
}

// vim: set ft=rust et sw=2 ts=2 sts=2 cinoptions=2 tw=79 :