strval 0.5.0

Parse strings into values
Documentation
//! Relative or absolute limit.

use std::{fmt, str::FromStr};

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

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


/// Specify a percentage, converted to a `f32` betwwen `0.0` and `1.0`.
#[derive(Debug, Clone)]
pub struct Percent {
  sval: String,
  val: f32
}

impl Default for Percent {
  fn default() -> Self {
    Self {
      sval: "0%".into(),
      val: 0.0
    }
  }
}

impl StrVal for Percent {
  type Type = f32;

  fn set(&mut self, sval: &str) -> Result<Self::Type, Error> {
    let dv = sval.parse::<Self>()?;

    self.sval = sval.to_string();
    self.val = dv.val;
    Ok(dv.val)
  }

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

  fn val_str(&self) -> Option<String> {
    Some(format!("{}%", self.val * 100.0))
  }

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

impl AsRef<str> for Percent {
  fn as_ref(&self) -> &str {
    &self.sval
  }
}

impl fmt::Display for Percent {
  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
    write!(f, "{}", self.sval)
  }
}

impl FromStr for Percent {
  type Err = Error;

  fn from_str(s: &str) -> Result<Self, Self::Err> {
    if let Some(s) = s.strip_suffix("%") {
      let val = s.parse::<f32>().unwrap();
      let val = val / 100.0;
      Ok(Self {
        sval: s.to_string(),
        val
      })
    } else {
      let val = s
        .parse::<f32>()
        .map_err(|e| Error::Invalid(e.to_string()))?;
      let val = val / 100.0;
      Ok(Self {
        sval: s.to_string(),
        val
      })
    }
  }
}

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

#[cfg(feature = "rusqlite")]
#[cfg_attr(docsrs, doc(cfg(feature = "rusqlite")))]
impl FromSql for Percent {
  #[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};

  #[test]
  #[allow(clippy::float_cmp)]
  fn lims() {
    let v = "0%".parse::<Percent>().unwrap();
    assert_eq!(v.get(), 0.0);

    let v = "100%".parse::<Percent>().unwrap();
    assert_eq!(v.get(), 1.0);

    let v = "0".parse::<Percent>().unwrap();
    assert_eq!(v.get(), 0.0);

    let v = "100".parse::<Percent>().unwrap();
    assert_eq!(v.get(), 1.0);
  }

  #[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]
  #[allow(clippy::float_cmp)]
  fn insert_query() {
    let conn = memdb().unwrap();

    let v = "0%".parse::<Percent>().unwrap();
    conn
      .execute("INSERT INTO tbl (id, txtval) VALUES (?, ?);", params![1, v])
      .unwrap();

    let v = "100%".parse::<Percent>().unwrap();
    conn
      .execute("INSERT INTO tbl (id, txtval) VALUES (?, ?);", params![2, v])
      .unwrap();

    let v = "0".parse::<Percent>().unwrap();
    conn
      .execute("INSERT INTO tbl (id, txtval) VALUES (?, ?);", params![3, v])
      .unwrap();

    let v = "100".parse::<Percent>().unwrap();
    conn
      .execute("INSERT INTO tbl (id, txtval) VALUES (?, ?);", params![4, v])
      .unwrap();

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

    let v: Percent = stmt.query_one([1], |row| row.get(0)).unwrap();
    assert_eq!(v.get(), 0.0);

    let v: Percent = stmt.query_one([2], |row| row.get(0)).unwrap();
    assert_eq!(v.get(), 1.0);

    let v: Percent = stmt.query_one([3], |row| row.get(0)).unwrap();
    assert_eq!(v.get(), 0.0);

    let v: Percent = stmt.query_one([4], |row| row.get(0)).unwrap();
    assert_eq!(v.get(), 1.0);
  }


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

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

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

    let _v: Percent = stmt.query_one([1], |row| row.get(0)).unwrap();
  }
}

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