use core::fmt::Display;
use super::*;
use crate::graphql::scalar::{F32, F64};
#[cfg(test)]
mod tests;
#[derive(Clone, PartialEq)]
pub struct ConfidenceOperand(Reading);
#[derive(Clone, PartialEq)]
enum Reading {
Number(f64),
Text(Box<str>),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ConfidenceOperandError {
Spelling,
Interval,
}
impl Display for ConfidenceOperandError {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match self {
Self::Spelling => f.write_str(
"a decimal confidence is written as plain base ten — digits, optionally a point and more \
digits, with no exponent and no sign",
),
Self::Interval => {
f.write_str("a confidence is a number in the closed unit interval `[0.0, 1.0]`")
}
}
}
}
impl core::error::Error for ConfidenceOperandError {}
impl ConfidenceOperand {
pub fn number(value: f64) -> Result<Self, ConfidenceOperandError> {
if value.is_nan() || !(0.0..=1.0).contains(&value) {
return Err(ConfidenceOperandError::Interval);
}
Ok(Self(Reading::Number(value + 0.0)))
}
pub fn decimal(text: &str) -> Result<Self, ConfidenceOperandError> {
let (negated, digits) = match text.strip_prefix('-') {
Some(rest) => (true, rest),
None => (false, text),
};
let (whole, fraction) = match digits.split_once('.') {
Some((whole, fraction)) => (whole, fraction),
None => (digits, ""),
};
let spelled = !whole.is_empty()
&& whole.bytes().all(|byte| byte.is_ascii_digit())
&& (digits.find('.').is_none() || (!fraction.is_empty()))
&& fraction.bytes().all(|byte| byte.is_ascii_digit());
if !spelled {
return Err(ConfidenceOperandError::Spelling);
}
let zeros = |part: &str| part.bytes().all(|byte| byte == b'0');
let whole_is = whole.trim_start_matches('0');
let inside = if whole_is.is_empty() {
true
} else {
whole_is == "1" && zeros(fraction)
};
if !inside || (negated && !(zeros(whole) && zeros(fraction))) {
return Err(ConfidenceOperandError::Interval);
}
Ok(Self(Reading::Text(Box::from(digits))))
}
#[inline]
#[must_use]
pub fn as_decimal(&self) -> Option<&str> {
match &self.0 {
Reading::Text(literal) => Some(literal),
Reading::Number(_) => None,
}
}
#[inline]
#[must_use]
pub fn as_double(&self) -> f64 {
match &self.0 {
Reading::Number(double) => *double,
Reading::Text(literal) => literal
.parse()
.expect("a confidence operand's text is a plain decimal literal inside [0.0, 1.0]"),
}
}
}
impl Display for ConfidenceOperand {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match &self.0 {
Reading::Number(double) => write!(f, "{double}"),
Reading::Text(literal) => f.write_str(literal),
}
}
}
impl core::fmt::Debug for ConfidenceOperand {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
match &self.0 {
Reading::Number(double) => write!(f, "ConfidenceOperand({double})"),
Reading::Text(literal) => write!(f, "ConfidenceOperand({literal:?})"),
}
}
}
pub trait ConfidenceWire: crate::ConfidenceCarrier {
type Carrier: From<Self> + Into<Self>;
const WIDTH: &'static str;
fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>>;
}
macro_rules! ieee_wire {
($( $ty:ty => $carrier:ty : $width:literal, narrow = $narrow:expr ),+ $(,)?) => {
$(
impl ConfidenceWire for $ty {
type Carrier = $carrier;
const WIDTH: &'static str = $width;
#[inline]
fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
#[allow(clippy::redundant_closure_call)]
Confidence::new($narrow(operand.as_double()))
}
}
)+
};
}
ieee_wire!(
f32 => F32 : "f32", narrow = (|wide: f64| wide as f32),
f64 => F64 : "f64", narrow = core::convert::identity,
);
#[cfg(feature = "half")]
impl ConfidenceWire for half::f16 {
type Carrier = crate::graphql::scalar::F16;
const WIDTH: &'static str = "f16";
#[inline]
fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
Confidence::new(half::f16::from_f64(operand.as_double()))
}
}
#[cfg(feature = "rust_decimal")]
impl ConfidenceWire for rust_decimal::Decimal {
type Carrier = crate::graphql::scalar::F128;
const WIDTH: &'static str = "f128";
fn read(operand: &ConfidenceOperand) -> Option<Confidence<Self>> {
let decimal = match operand.as_decimal() {
Some(literal) => rust_decimal::Decimal::from_str_exact(literal).ok()?,
None => rust_decimal::Decimal::from_f64_retain(operand.as_double())?,
};
Confidence::new(decimal)
}
}
#[diagnostic::on_unimplemented(
message = "`{Self}` is not a SCORE — nothing says what one confidence threshold means for it",
label = "not a score",
note = "a `ConfidenceFilter`'s operands are widthless (`ingraph::ConfidenceOperand`), so a type \
reaches that filter only by saying how one operand crosses into it: write \
`impl ingraph::ScoreKind for {Self}`, giving its `Error` and `from_operand`. \
`ingraph::Confidence<S>` answers it at every width it measures in",
note = "if `{Self}` is a STORAGE type standing in for a confidence column, the row belongs on the \
storage type rather than on the column's: a crossing lands in the type the database \
holds, and a declared converter (`<db>(into = …)`) is the other road — it \
supplies the conversion at the call site and asks this trait for nothing"
)]
pub trait ScoreKind: Sized {
type Error: Display;
fn from_operand(operand: &ConfidenceOperand) -> Result<Self, Self::Error>;
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct UnrepresentableConfidence {
width: &'static str,
operand: Box<str>,
}
impl UnrepresentableConfidence {
#[inline]
#[must_use]
pub const fn width(&self) -> &'static str {
self.width
}
#[inline]
#[must_use]
pub fn operand(&self) -> &str {
&self.operand
}
}
impl Display for UnrepresentableConfidence {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
write!(
f,
"`{}` is not a confidence this column can hold — it measures in `{}`, which cannot carry that \
operand exactly",
self.operand, self.width,
)
}
}
impl core::error::Error for UnrepresentableConfidence {}
impl<S: ConfidenceWire> ScoreKind for Confidence<S> {
type Error = UnrepresentableConfidence;
#[inline]
fn from_operand(operand: &ConfidenceOperand) -> Result<Self, UnrepresentableConfidence> {
S::read(operand).ok_or_else(|| UnrepresentableConfidence {
width: S::WIDTH,
operand: Box::from(operand.to_string()),
})
}
}
#[derive(Debug, Clone, PartialEq, Default)]
pub struct ConfidenceFilter {
pub(crate) eq: Option<ConfidenceOperand>,
pub(crate) ne: Option<ConfidenceOperand>,
pub(crate) gt: Option<ConfidenceOperand>,
pub(crate) gte: Option<ConfidenceOperand>,
pub(crate) lt: Option<ConfidenceOperand>,
pub(crate) lte: Option<ConfidenceOperand>,
}
impl ConfidenceFilter {
#[inline]
pub const fn new() -> Self {
Self {
eq: None,
ne: None,
gt: None,
gte: None,
lt: None,
lte: None,
}
}
#[inline]
pub const fn is_empty(&self) -> bool {
self.eq.is_none()
&& self.ne.is_none()
&& self.gt.is_none()
&& self.gte.is_none()
&& self.lt.is_none()
&& self.lte.is_none()
}
opt_accessor!(eq: ConfidenceOperand => with_eq, set_eq, maybe_eq, update_eq);
opt_accessor!(ne: ConfidenceOperand => with_ne, set_ne, maybe_ne, update_ne);
opt_accessor!(gt: ConfidenceOperand => with_gt, set_gt, maybe_gt, update_gt);
opt_accessor!(gte: ConfidenceOperand => with_gte, set_gte, maybe_gte, update_gte);
opt_accessor!(lt: ConfidenceOperand => with_lt, set_lt, maybe_lt, update_lt);
opt_accessor!(lte: ConfidenceOperand => with_lte, set_lte, maybe_lte, update_lte);
pub fn try_map<U, E, F>(self, mut f: F) -> Result<ScalarFilter<U>, E>
where
F: FnMut(ConfidenceOperand) -> Result<U, E>,
{
let mut crossed = |slot: Option<ConfidenceOperand>| match slot {
Some(operand) => f(operand).map(Some),
None => Ok(None),
};
Ok(
ScalarFilter::new()
.maybe_eq(crossed(self.eq)?)
.maybe_ne(crossed(self.ne)?)
.maybe_gt(crossed(self.gt)?)
.maybe_gte(crossed(self.gte)?)
.maybe_lt(crossed(self.lt)?)
.maybe_lte(crossed(self.lte)?),
)
}
}
impl<U> TryMapFilter<ConfidenceOperand, U> for ConfidenceFilter {
type Mapped = ScalarFilter<U>;
#[inline]
fn try_map_filter<E, F>(self, f: F) -> Result<Self::Mapped, E>
where
F: FnMut(ConfidenceOperand) -> Result<U, E>,
{
self.try_map(f)
}
}
impl GraphqlFilter for ConfidenceFilter {
#[inline]
fn is_empty(&self) -> bool {
Self::is_empty(self)
}
}
impl EqualsFilter<ConfidenceOperand> for ConfidenceFilter {
#[inline]
fn equals(value: ConfidenceOperand) -> Self {
Self::new().with_eq(value)
}
}
#[cfg(feature = "async-graphql")]
#[async_graphql::Scalar(name = "ConfidenceOperand")]
impl async_graphql::ScalarType for ConfidenceOperand {
fn parse(value: async_graphql::Value) -> async_graphql::InputValueResult<Self> {
match &value {
async_graphql::Value::String(text) => {
Self::decimal(text).map_err(async_graphql::InputValueError::custom)
}
async_graphql::Value::Number(number) => match number.as_f64() {
Some(wide) => Self::number(wide).map_err(async_graphql::InputValueError::custom),
None => Err(async_graphql::InputValueError::custom(
ConfidenceOperandError::Interval,
)),
},
_ => Err(async_graphql::InputValueError::expected_type(value)),
}
}
#[inline]
fn is_valid(value: &async_graphql::Value) -> bool {
match value {
async_graphql::Value::String(text) => Self::decimal(text).is_ok(),
async_graphql::Value::Number(number) => number
.as_f64()
.is_some_and(|wide| Self::number(wide).is_ok()),
_ => false,
}
}
fn to_value(&self) -> async_graphql::Value {
match &self.0 {
Reading::Number(double) => async_graphql::Value::Number(
async_graphql::Number::from_f64(*double).expect("a confidence operand is finite"),
),
Reading::Text(literal) => async_graphql::Value::String(literal.to_string()),
}
}
}
#[cfg(feature = "async-graphql")]
filter_input_object!(ConfidenceFilter : "ConfidenceFilter" {
bare eq: ::core::option::Option<ConfidenceOperand> => "eq",
ne: ::core::option::Option<ConfidenceOperand> => "ne",
gt: ::core::option::Option<ConfidenceOperand> => "gt",
gte: ::core::option::Option<ConfidenceOperand> => "gte",
lt: ::core::option::Option<ConfidenceOperand> => "lt",
lte: ::core::option::Option<ConfidenceOperand> => "lte",
});