ingraph 0.1.0

A declaration-driven indexing framework: records and nodes are written as Rust types, and the storage rows, the dataflow between them and the GraphQL query surface are emitted from the declaration.
Documentation
//! [`Point2<T>`](Point2): a position in a plane, and the two-column citizen the other holders are
//! built out of.

use crate::{
  ColumnEq, ColumnKind, ColumnName, ColumnShape, CompositeFilterMarker, CompositeMarker,
  CursorValue, DefaultMarker, DefaultVecMarker, FieldName, PayloadFilter, QuantifiedMarker, shape,
};

use super::NormCoord;

/// **One leaf, and it is the value** — Point2<T> means its columns in the sequence it declares them, so
/// no term over one ever expands and the word is the whole row.
impl<T> crate::DeclaredLeaves for Point2<T> {}

#[cfg(test)]
mod tests;

/// **A POSITION IN A PLANE** — two components, in whatever `T` the declaration measures in.
///
/// TOP-LEFT ORIGIN, so `y` grows DOWNWARD: this is the family's convention and the note in
/// [`geometry`](super) carries the argument. A landmark on a face, a joint in a 2-D pose, a corner
/// of a page and a click are four callers with one pair between them.
///
/// # A DUMB GENERIC HOLDER, exactly as [`BoundingBox`](super::BoundingBox) is
///
/// [`new`](Self::new) is total and `const`, and checks nothing. What a point can be wrong ABOUT is
/// a property of one number — finite, in range — and that is the component's to refuse, at
/// [`NormCoord::new`] for the normalized world and at whatever constructor a caller's own component
/// has. **There is no unit-square rule for a point**, and the absence is the family's arrangement
/// rather than an omission: a rectangle can leave a frame its corners are each inside, because the
/// SUM of a corner and an extent is a third number; a point IS its two components and has no sum to
/// check. So this type has no `try_unit` twin, and needs none.
///
/// # NO `Ord`
///
/// Two positions have no order. A lexicographic one on `(x, y)` is an order over the STORAGE that
/// reads like *above and to the left*, which it is not — `(0.9, 0.0)` precedes `(0.1, 0.5)` under it
/// and is neither above nor to the left of it. The component orderings are genuine and are kept at
/// the filter, where `x` and `y` each take their own.
///
/// # Examples
///
/// ```
/// use ingraph::{NormCoord, Point2};
///
/// let pixels = Point2::new(120_u32, 48);
/// assert_eq!(pixels.x(), 120);
///
/// let corner = Point2::new(NormCoord::new(0.25).unwrap(), NormCoord::new(0.75).unwrap());
/// assert_eq!(corner.y().get(), 0.75);
/// ```
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Point2<T> {
  pub(super) x: T,
  pub(super) y: T,
}

impl<T> Point2<T> {
  /// The position at `(x, y)`.
  ///
  /// TOTAL and `const`: see the type's note, where the absence of a check is the ruling.
  #[inline]
  #[must_use]
  pub const fn new(x: T, y: T) -> Self {
    Self { x, y }
  }

  /// The horizontal component, growing to the RIGHT.
  #[inline]
  pub const fn x(&self) -> T
  where
    T: Copy,
  {
    self.x
  }

  /// The vertical component, growing DOWNWARD.
  #[inline]
  pub const fn y(&self) -> T
  where
    T: Copy,
  {
    self.y
  }

  /// The same position with both components carried through `f`.
  ///
  /// [`BoundingBox::map`](super::BoundingBox::map)'s row at this arity, and it does no arithmetic of
  /// its own for that row's reason: `f` is the caller's, applied twice in field order.
  #[inline]
  pub fn map<U, F: FnMut(T) -> U>(self, mut f: F) -> Point2<U> {
    Point2 {
      x: f(self.x),
      y: f(self.y),
    }
  }
}

impl Point2<NormCoord> {
  /// **The unit frame's constructor** — the two numbers, each through the component's own refusal.
  ///
  /// It adds NO rule of its own, and that is the point of writing it: the convenience is reading
  /// two floats without spelling [`NormCoord::new`] twice, and the refusal it hands back is the
  /// component's unchanged. Compare [`BoundingBox::try_unit`](super::BoundingBox::try_unit), which
  /// has two rules of its own and a vocabulary to say which one refused.
  ///
  /// # Errors
  ///
  /// [`OutsideTheUnitInterval`](super::OutsideTheUnitInterval) where either number is not a
  /// coordinate — `NaN`, an infinity, or outside `[0.0, 1.0]`.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::Point2;
  ///
  /// assert!(Point2::try_unit(0.5, 0.5).is_ok());
  /// assert!(Point2::try_unit(0.5, 1.5).is_err());
  /// ```
  pub fn try_unit(x: f32, y: f32) -> Result<Self, super::OutsideTheUnitInterval> {
    let coord = |value| NormCoord::new(value).ok_or(super::OutsideTheUnitInterval);

    Ok(Self::new(coord(x)?, coord(y)?))
  }
}

/// The horizontal component's segment.
pub(super) const X: &FieldName = FieldName::new("x");

/// The vertical component's segment.
pub(super) const Y: &FieldName = FieldName::new("y");

/// **The TWO columns a position spans.**
///
/// The LEAF GUARD is [`BoundingBox`](super::BoundingBox)'s, at this arity and for its reason: it is
/// what keeps the [`StoredAs`](crate::StoredAs) row's fixed length TRUE, since stable Rust cannot
/// write `2 * <T as StoredAs<Db>>::WORDS.len()` in a length position.
///
/// ```compile_fail,E0080
/// use ingraph::{ColumnKind, Point2, TimeRange};
///
/// const _: usize = <Point2<TimeRange> as ColumnKind>::SEGMENTS.len();
/// ```
impl<T: ColumnKind> ColumnKind for Point2<T> {
  const SEGMENTS: &'static [ColumnShape] = {
    assert!(
      T::SEGMENTS.is_empty(),
      "a point's component spans ONE column: a composite component would make the point's own width \
       depend on it, and a fixed-arity row cannot state that"
    );
    &[shape::<T>(ColumnName::of(X)), shape::<T>(ColumnName::of(Y))]
  };
}

/// A position is one column value when both its components are.
impl<T: ColumnEq> ColumnEq for Point2<T> {
  #[inline]
  fn column_eq(&self, other: &Self) -> bool {
    self.x.column_eq(&other.x) && self.y.column_eq(&other.y)
  }
}

/// **The DECLARED half — TWO words**, the component's own, twice.
impl<Db, T> crate::StoredAs<Db> for Point2<T>
where
  T: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = &[
    <T as crate::StoredAs<Db>>::WORDS[0],
    <T as crate::StoredAs<Db>>::WORDS[0],
  ];
}

/// **THE ADMISSION**, delegating to the component exactly as the rectangle's row does.
///
/// `Vec<Point2<NormCoord>>` is a polyline, a landmark set, a pose's joints — the shape a list of
/// positions actually takes, and the row an edge table of them needs.
impl<T: crate::CollectionElement> crate::CollectionElement for Point2<T> {}

/// **TWO BINDS OUT**, with the comma between them.
#[cfg(feature = "sqlx")]
impl<T, Db> crate::Carrier<Db> for Point2<T>
where
  Db: sqlx::Database,
  T: crate::Carrier<Db>,
{
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <T as crate::Carrier<Db>>::push_bind(&self.x, qb);
    qb.push(", ");
    <T as crate::Carrier<Db>>::push_bind(&self.y, qb);
  }
}

/// **AND THE TWO BACK IN**, by name. It states no invariant of its own, having none: a point's whole
/// promise is its components', and each is refused at its own column.
#[cfg(feature = "sqlx")]
impl<'a, R, T> crate::Assemble<'a, R> for Point2<T>
where
  R: sqlx::Row,
  T: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let x: T = crate::assembled(row, X, under)?;
    let y: T = crate::assembled(row, Y, under)?;

    Ok(Self::new(x, y))
  }
}

/// **THE KEYSET POSITION** — the two components in segment order.
///
/// A STORAGE order, for [`BoundingBox`](super::BoundingBox)'s reason: this type publishes no
/// [`Ord`], and a page's need for *an* order is not a claim about *the* order.
impl<T: CursorValue> CursorValue for Point2<T> {
  fn write_cursor(&self, out: &mut Vec<u8>) {
    CursorValue::write_cursor(&self.x, out);
    CursorValue::write_cursor(&self.y, out);
  }

  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    let width = bytes.len() / 2;
    if width == 0 || width * 2 != bytes.len() {
      return None;
    }

    let x = <T as CursorValue>::read_cursor(&bytes[..width])?;
    let y = <T as CursorValue>::read_cursor(&bytes[width..])?;

    Some(Self::new(x, y))
  }
}

/// The COMPOSITE reading, on [`BoundingBox`](super::BoundingBox)'s terms: the value occupies columns
/// of its own and both can be absent together.
impl<T: DefaultMarker> DefaultMarker for Point2<T> {
  type Marker = CompositeMarker<Point2<T>>;
}

/// **A COLLECTION of positions is asked through the QUANTIFIERS alone** — the wide kind's
/// lexicographic operators being questions a list of unordered values cannot answer.
impl<T: DefaultMarker> DefaultVecMarker for Point2<T> {
  type Marker = QuantifiedMarker<Vec<Point2<T>>>;
}

/// What guards a [`Point2<T>`] column — its own filter at both seats, framework-open through
/// [`PayloadFilter<T>`](crate::PayloadFilter) for the rectangle's reason.
impl<T> CompositeFilterMarker for Point2<T>
where
  T: DefaultMarker,
{
  type Filter = Point2Filter<PayloadFilter<T>>;
  type ColumnFilter = Point2Filter<PayloadFilter<T>>;
}

/// **TWO COMPONENT FACETS, and no whole-point operator.**
///
/// ```text
/// input Point2F32Filter { x: F32Filter  y: F32Filter }
/// ```
///
/// The leaf-tuple EQUALITY is the conjunction of the two facets — `{ x: { eq: … }, y: { eq: … } }`
/// lowers to `x = ? AND y = ?` — and whole-point ordering is refused STRUCTURALLY, no slot taking a
/// point-shaped bound. Both arguments are written out at
/// [`BoundingBoxFilter`](super::BoundingBoxFilter), which is where this family's filter posture is
/// argued; they hold here unchanged at one arity less.
///
/// The SPATIAL door this type leaves open is `near` — *within a radius of this position* — which
/// needs a distance METRIC, and a metric is a fact about the frame rather than about the pair. It is
/// not invented ahead of a caller who can say which frame they are in.
pub struct Point2Filter<CF> {
  pub(super) x: Option<CF>,
  pub(super) y: Option<CF>,
}

impl<CF> Point2Filter<CF> {
  /// The empty filter — neither facet set, so a column guarded by it is unconstrained.
  #[inline]
  #[must_use]
  pub const fn new() -> Self {
    Self { x: None, y: None }
  }

  crate::graphql::filter::opt_accessor!(x: CF => with_x, set_x, maybe_x, update_x);
  crate::graphql::filter::opt_accessor!(y: CF => with_y, set_y, maybe_y, update_y);
}

impl<CF: crate::GraphqlFilter> Point2Filter<CF> {
  /// True while NO operator slot is set on either facet.
  ///
  /// The bound is on this ONE method rather than on the type, for the arrangement every generic
  /// filter kind here takes.
  pub fn is_empty(&self) -> bool {
    self.x.as_ref().is_none_or(crate::GraphqlFilter::is_empty)
      && self.y.as_ref().is_none_or(crate::GraphqlFilter::is_empty)
  }
}

impl<CF: crate::GraphqlFilter> crate::GraphqlFilter for Point2Filter<CF> {
  #[inline]
  fn is_empty(&self) -> bool {
    Self::is_empty(self)
  }
}

impl<CF> Default for Point2Filter<CF> {
  #[inline]
  fn default() -> Self {
    Self::new()
  }
}

impl<CF: core::fmt::Debug> core::fmt::Debug for Point2Filter<CF> {
  fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
    f.debug_struct("Point2Filter")
      .field("x", &self.x)
      .field("y", &self.y)
      .finish()
  }
}

impl<CF: Clone> Clone for Point2Filter<CF> {
  fn clone(&self) -> Self {
    Self {
      x: self.x.clone(),
      y: self.y.clone(),
    }
  }
}

impl<CF: PartialEq> PartialEq for Point2Filter<CF> {
  fn eq(&self, other: &Self) -> bool {
    self.x == other.x && self.y == other.y
  }
}