use std::fmt;
use crate::decimal::Decimal;
use crate::types::ScreenColumn;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum Op {
Gte,
Lte,
Gt,
Lt,
}
impl Op {
pub fn as_str(self) -> &'static str {
match self {
Op::Gte => "gte",
Op::Lte => "lte",
Op::Gt => "gt",
Op::Lt => "lt",
}
}
}
pub trait ClauseValue {
fn plain_decimal(&self) -> String;
}
macro_rules! whole {
($($t:ty),*) => { $(impl ClauseValue for $t { fn plain_decimal(&self) -> String { self.to_string() } })* };
}
whole!(
i8, i16, i32, i64, i128, isize, u8, u16, u32, u64, u128, usize
);
impl ClauseValue for f64 {
fn plain_decimal(&self) -> String {
format!("{self}")
}
}
impl ClauseValue for f32 {
fn plain_decimal(&self) -> String {
format!("{self}")
}
}
impl ClauseValue for Decimal {
fn plain_decimal(&self) -> String {
self.as_str().to_string()
}
}
impl ClauseValue for &str {
fn plain_decimal(&self) -> String {
self.trim().to_string()
}
}
impl ClauseValue for String {
fn plain_decimal(&self) -> String {
self.trim().to_string()
}
}
#[cfg(feature = "rust_decimal")]
impl ClauseValue for rust_decimal::Decimal {
fn plain_decimal(&self) -> String {
self.normalize().to_string()
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Clause {
column: ScreenColumn,
op: Op,
value: String,
}
impl Clause {
pub fn new(column: ScreenColumn, op: Op, value: impl ClauseValue) -> Self {
Clause {
column,
op,
value: value.plain_decimal(),
}
}
}
impl fmt::Display for Clause {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(
f,
"{}:{}:{}",
self.column.as_str(),
self.op.as_str(),
self.value
)
}
}
impl From<Clause> for String {
fn from(clause: Clause) -> Self {
clause.to_string()
}
}
pub(crate) fn refused(clause: &str) -> Option<String> {
let mut parts = clause.splitn(3, ':');
let (Some(column), Some(op), Some(value)) = (parts.next(), parts.next(), parts.next()) else {
return Some(format!(
"the clause `{clause}` is not column:op:value, such as revenue:gte:1000000000"
));
};
if column.trim().is_empty() {
return Some(format!("the clause `{clause}` names no column"));
}
if !matches!(op.trim(), "gte" | "lte" | "gt" | "lt") {
return Some(format!(
"the clause `{clause}` has the operator `{}`; it is gte, lte, gt or lt",
op.trim()
));
}
let value = value.trim();
if value.chars().count() > 32 {
return Some(format!(
"the clause `{clause}` has a value of more than 32 characters"
));
}
if !is_plain_decimal(value) {
return Some(format!(
"the clause `{clause}` has the value `{value}`; it is a plain decimal, never with an exponent"
));
}
None
}
fn is_plain_decimal(value: &str) -> bool {
let digits = value
.strip_prefix('-')
.or_else(|| value.strip_prefix('+'))
.unwrap_or(value);
let (whole, fraction) = match digits.split_once('.') {
Some((whole, fraction)) => (whole, Some(fraction)),
None => (digits, None),
};
let all_digits = |part: &str| part.bytes().all(|b| b.is_ascii_digit());
let some_digit = !whole.is_empty() || fraction.is_some_and(|f| !f.is_empty());
some_digit && all_digits(whole) && fraction.is_none_or(all_digits)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_clause_the_api_would_refuse_is_named() {
for clause in [
"revenue:gte:1000000000",
"net_margin:gt:0.2",
"net_income:lt:-58000000",
"fcf_margin:lte:.5",
"fcf_margin:lte:+5",
"fcf_margin:lte:5.",
" revenue : gte : 1 ",
] {
assert_eq!(refused(clause), None, "{clause}");
}
for clause in [
"revenue",
"revenue:gte",
":gte:1",
"revenue:>=:1",
"revenue:gte:1e9",
"revenue:gte:5,000",
"revenue:gte:",
"revenue:gte:NaN",
"revenue:gte:inf",
"revenue:gte:123456789012345678901234567890123",
] {
assert!(refused(clause).is_some(), "{clause}");
}
assert!(
Clause::new(ScreenColumn::Revenue, Op::Gte, f64::NAN)
.to_string()
.contains("NaN")
);
assert!(
refused(&Clause::new(ScreenColumn::Revenue, Op::Gte, f64::NAN).to_string()).is_some()
);
}
#[test]
fn clauses_are_written_as_the_api_takes_them() {
assert_eq!(
Clause::new(ScreenColumn::Revenue, Op::Gte, 1_000_000_000_i64).to_string(),
"revenue:gte:1000000000"
);
assert_eq!(
Clause::new(ScreenColumn::MarketCap, Op::Gte, 1e21).to_string(),
"market_cap:gte:1000000000000000000000"
);
assert_eq!(
Clause::new(ScreenColumn::FcfMargin, Op::Lte, 0.15).to_string(),
"fcf_margin:lte:0.15"
);
assert_eq!(
Clause::new(ScreenColumn::Pe, Op::Lt, 1e-7).to_string(),
"pe:lt:0.0000001"
);
assert_eq!(
Clause::new(
ScreenColumn::NetIncome,
Op::Gt,
"-58000000".parse::<Decimal>().unwrap()
)
.to_string(),
"net_income:gt:-58000000"
);
assert_eq!(
Clause::new(ScreenColumn::Roe, Op::Gt, " 0.2 ").to_string(),
"roe:gt:0.2"
);
let text: String = Clause::new(ScreenColumn::Ps, Op::Lte, 4_u8).into();
assert_eq!(text, "ps:lte:4");
}
}