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
//! [`BarcodePayloadKind`]: what KIND OF THING a barcode's decoded payload names — ten named members
//! and one escape.

use core::fmt;

use smol_bytes::Utf8Bytes;

use crate::{
  ColumnKind, CursorValue, DefaultMarker, DefaultVecMarker, EnumFilter, EnumMarker,
  column::column_eq,
};

#[cfg(test)]
mod tests;

/// **THE KIND OF THING a barcode's decoded payload names** — ten named kinds, plus an escape for a
/// word this vocabulary does not name.
///
/// ```text
///   GENERIC              url  text
///   STRUCTURED           wifi  contact  email  phone  sms  geo  calendar
///   SYMBOLOGY-DECIDED    product
/// ```
///
/// # It is a VOCABULARY and not a CLASSIFIER
///
/// This type names WHAT a payload is, not how to decide it. Reading `WIFI:S:home;;` off a QR code
/// and turning that string into [`Wifi`](Self::Wifi) is a classifier's job, and it is the app's
/// barcode node's rather than this crate's — [`Symbology`](super::Symbology) says how the bars were
/// read and this type says what the payload MEANS, so classifying one is a function of BOTH: a 1-D
/// product symbology names a [`Product`](Self::Product) whatever its digits say, and a 2-D
/// symbology's payload has to be read to tell a [`Wifi`](Self::Wifi) credential from a bare
/// [`Url`](Self::Url). This crate carries neither reading. It only names where one lands.
///
/// # The conventional prefixes, for the classifier that reads them
///
/// Stated here once, for the caller that has to know them and not for this type, which parses none
/// of them — the door below reads a KIND's own name (`"wifi"`, `"geo"`, …), never a payload:
///
/// | kind | conventional payload prefix |
/// |---|---|
/// | [`Wifi`](Self::Wifi) | `WIFI:` |
/// | [`Contact`](Self::Contact) | `BEGIN:VCARD` or `MECARD:` |
/// | [`Email`](Self::Email) | `mailto:` |
/// | [`Phone`](Self::Phone) | `tel:` |
/// | [`Sms`](Self::Sms) | `sms:` or `SMSTO:` |
/// | [`Geo`](Self::Geo) | `geo:` |
/// | [`Calendar`](Self::Calendar) | `BEGIN:VEVENT` |
/// | [`Url`](Self::Url) | any URL scheme |
/// | [`Product`](Self::Product) | none — the SYMBOLOGY says so: every 1-D product symbology |
/// | [`Text`](Self::Text) | none — the payload matched no structured form above |
///
/// # It is DOMAIN-NEUTRAL, on [`Symbology`](super::Symbology)'s own precedent
///
/// A barcode is read off a photograph, a scanned invoice, a PDF page and a shipping label, and what
/// its payload MEANS does not depend on which of those it was read from — the same argument that
/// sent [`Symbology`] here one member up applies unchanged to what its payload names.
///
/// # OPEN, and the escape is why the wire face is a SCALAR
///
/// The roster is not one vendor's enum — no single specification lists "the" barcode payload kinds —
/// so it is a HAND-CURATED set: the two loosest kinds a payload can be, the seven structured shapes a
/// producer conventionally prefixes, and the one kind a SYMBOLOGY decides rather than a payload. A
/// kind this roster does not name is exactly as survivable as a standard [`Symbology`] does not name:
/// carried through the escape rather than refused. A schema `enum` would promise the members are the
/// whole set; this one cannot, so it publishes a scalar.
///
/// **The words are the framework's own fold**, walked by [`folds_to`](crate::name::folds_to): ASCII
/// case and `_`, `-` and a space are ignored, so `Wi-Fi`, `WIFI` and `wifi` are one value. The escape
/// carries the MATERIALISED fold, so two producers writing `boarding-pass` and `BoardingPass` for a
/// kind nobody here names are one value, compare equal and hash into one bucket.
///
/// # Examples
///
/// ```
/// use ingraph::BarcodePayloadKind;
///
/// assert_eq!(BarcodePayloadKind::new("wifi"), BarcodePayloadKind::Wifi);
/// assert_eq!(BarcodePayloadKind::new("WIFI"), BarcodePayloadKind::Wifi);
/// assert_eq!(BarcodePayloadKind::new("Wi Fi"), BarcodePayloadKind::Wifi);
///
/// // …and a kind this roster does not name is carried rather than refused.
/// let unknown = BarcodePayloadKind::new("Boarding Pass");
/// assert!(unknown.is_other());
/// assert_eq!(unknown.as_str(), "boardingpass");
/// ```
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum BarcodePayloadKind {
  /// A URL — the payload names an address, under any scheme.
  Url,
  /// Free text — a payload matching no structured form below.
  Text,
  /// A Wi-Fi credential — conventionally `WIFI:`.
  Wifi,
  /// A contact card — conventionally `BEGIN:VCARD` or `MECARD:`.
  Contact,
  /// An email address — conventionally `mailto:`.
  Email,
  /// A phone number — conventionally `tel:`.
  Phone,
  /// An SMS message — conventionally `sms:` or `SMSTO:`.
  Sms,
  /// A geographic coordinate — conventionally `geo:`.
  Geo,
  /// A product's article number — what a 1-D product symbology's payload names, whatever its
  /// digits say.
  Product,
  /// A calendar event — conventionally `BEGIN:VEVENT`.
  Calendar,
  /// A kind this roster does not name, carrying its FOLDED word.
  ///
  /// The escape is what makes the vocabulary open: a classifier naming a kind outside the roster
  /// has its word carried through a column, the wire and a filter rather than refused at the door.
  /// It is not a member of [`VARIANTS`](BarcodePayloadKind::VARIANTS) — a roster is the names this
  /// crate KNOWS, and an escape is the promise that not knowing one is survivable.
  Other(Utf8Bytes),
}

/// The roster, paired with the canonical slug each member is written as.
///
/// The words are stated ONCE, here, and every door reads them: [`BarcodePayloadKind::new`] walks
/// this table under the fold and [`BarcodePayloadKind::as_str`] indexes it. A slug spelled twice
/// would be a slug free to drift, which is the whole reason the derive that would have generated
/// these keeps one table too.
const ROSTER: &[(BarcodePayloadKind, &str)] = &[
  (BarcodePayloadKind::Url, "url"),
  (BarcodePayloadKind::Text, "text"),
  (BarcodePayloadKind::Wifi, "wifi"),
  (BarcodePayloadKind::Contact, "contact"),
  (BarcodePayloadKind::Email, "email"),
  (BarcodePayloadKind::Phone, "phone"),
  (BarcodePayloadKind::Sms, "sms"),
  (BarcodePayloadKind::Geo, "geo"),
  (BarcodePayloadKind::Product, "product"),
  (BarcodePayloadKind::Calendar, "calendar"),
];

impl BarcodePayloadKind {
  /// The NAMED members, in declaration order — the roster this crate knows, and never the escape.
  ///
  /// It is what a schema's documentation lists and what a client discovers the vocabulary from. The
  /// escape's absence is the point: a caller enumerating this and treating it as exhaustive would be
  /// making exactly the promise an open vocabulary refuses, so the escape is reachable only through
  /// a value that carries a word.
  pub const VARIANTS: &'static [&'static str] = &[
    "url", "text", "wifi", "contact", "email", "phone", "sms", "geo", "product", "calendar",
  ];

  /// Read a payload-kind name, WIDE — any spelling of a named member, or any word at all.
  ///
  /// **The ONE door in**, and it CANNOT FAIL: every string names a payload kind, because the escape
  /// is what an open vocabulary means. `wifi` names a kind this crate knows and `boarding pass`
  /// names one it does not, and both are values — the second in the escape arm, under the fold.
  ///
  /// The walk is linear over the roster and that is the measured shape rather than a placeholder:
  /// the fold is a byte comparison, the roster is ten entries, and a table keyed on a spelling would
  /// have to hold every spelling.
  #[must_use]
  pub fn new(word: impl AsRef<str>) -> Self {
    let word = word.as_ref();

    for (member, canonical) in ROSTER {
      if crate::name::folds_to(word, canonical) {
        return member.clone();
      }
    }

    Self::Other(Utf8Bytes::from(crate::name::folded(word)))
  }

  /// The canonical slug — a named member's own word, or the folded word the escape carries.
  #[must_use]
  pub fn as_str(&self) -> &str {
    match self {
      Self::Other(word) => word.as_str(),
      named => ROSTER
        .iter()
        .find_map(|(member, canonical)| (member == named).then_some(*canonical))
        .expect("every named member of this vocabulary has a row in its own roster"),
    }
  }

  /// Is this a member the roster NAMES?
  ///
  /// The question the absent refusal would have been asking. A caller that wants to log, count or
  /// route the kinds it has never met asks this rather than being handed an error it cannot act on —
  /// the posture every open vocabulary in this crate takes.
  #[must_use]
  pub const fn is_registered(&self) -> bool {
    !self.is_other()
  }

  /// Is this the ESCAPE — a word the roster does not name?
  #[must_use]
  pub const fn is_other(&self) -> bool {
    matches!(self, Self::Other(_))
  }
}

/// The canonical slug, and nothing else — no quotes, no wrapper, no type name.
impl fmt::Display for BarcodePayloadKind {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    f.write_str(self.as_str())
  }
}

/// The slug IN QUOTES, which is what a `Debug` of a one-word vocabulary is FOR: the variant path
/// around it says nothing a reader of a failing assertion wants.
impl fmt::Debug for BarcodePayloadKind {
  #[inline]
  fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
    fmt::Debug::fmt(self.as_str(), f)
  }
}

/// The parse, forwarded to this type's own door — and INFALLIBLE, the open escape being what makes
/// every string a payload kind.
impl core::str::FromStr for BarcodePayloadKind {
  type Err = core::convert::Infallible;

  #[inline]
  fn from_str(word: &str) -> Result<Self, Self::Err> {
    Ok(Self::new(word))
  }
}

impl AsRef<str> for BarcodePayloadKind {
  #[inline]
  fn as_ref(&self) -> &str {
    self.as_str()
  }
}

impl From<BarcodePayloadKind> for String {
  #[inline]
  fn from(kind: BarcodePayloadKind) -> Self {
    Self::from(kind.as_str())
  }
}

/// **ONE column**, which is the default — stated rather than inherited, because the composite in
/// this house that holds one reads its width off this row.
impl ColumnKind for BarcodePayloadKind {}

// The SAMENESS row beside the width — the face an emitted row and an emitted page cursor fold in
// place of the `PartialEq` they used to derive. Two payload kinds are one column value when they
// are one word, which is what an open vocabulary's own `PartialEq` says.
column_eq! { BarcodePayloadKind }

/// **One leaf, and it is the value** — ONE column, so there is no sequence to permute.
impl crate::DeclaredLeaves for BarcodePayloadKind {}

/// **THE STORED WORD is text's**, in every dialect that has one.
///
/// Delegated to [`String`] rather than named, for the reason the bind below is: a payload kind IS
/// its canonical slug, so the column is a text column and the dialect's own word for one is the only
/// answer. The delegation carries the ADMISSION with it — a payload kind is declarable exactly where
/// text is, which is everywhere.
impl<Db> crate::StoredAs<Db> for BarcodePayloadKind
where
  String: crate::StoredAs<Db>,
{
  const WORDS: &'static [&'static str] = <String as crate::StoredAs<Db>>::WORDS;
}

/// **ONE BIND OUT** — the canonical slug, as text.
///
/// An OWNED [`String`] rather than the borrowed `&str` the value already holds, for the reason every
/// text citizen in [`primitives`](crate::primitives) pays at this seat: `push_bind` requires its
/// value to outlive the builder's `'args`, which this trait's signature leaves unrelated to `&self`.
#[cfg(feature = "sqlx")]
impl<Db> crate::Carrier<Db> for BarcodePayloadKind
where
  Db: sqlx::Database,
  String: crate::Carrier<Db>,
{
  #[inline]
  fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
    <String as crate::Carrier<Db>>::push_bind(&String::from(self.as_str()), qb);
  }
}

/// **AND THE WORD BACK IN**, through the door — and it CANNOT FAIL.
///
/// This is where an open vocabulary parts company with [`Label`](super::Label): that type refuses an
/// empty stored word because a label that is nothing is not a label, and this one refuses nothing at
/// all because a kind this crate has never heard of is still a payload kind. A stored word the
/// roster does not name comes back through the escape, CANONICALISED rather than wrapped, so a
/// hand-written `UPDATE` writing `BOARDING-PASS` reads back under its folded word.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for BarcodePayloadKind
where
  String: crate::Assemble<'a, R>,
{
  fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
    let stored: String = <String as crate::Assemble<'a, R>>::assemble(row, under)?;

    Ok(Self::new(&stored))
  }
}

/// **THE KEYSET POSITION**: the canonical slug's UTF-8 bytes, which is what a `TEXT` column orders
/// by and what the [`Ord`] above walks.
///
/// The read CANONICALISES rather than validating — a cursor is a string a CLIENT hands back, and
/// this vocabulary has no spelling to refuse it for. What it can still refuse is bytes that are not
/// UTF-8 at all, which is the one way a forged position fails here.
impl CursorValue for BarcodePayloadKind {
  #[inline]
  fn write_cursor(&self, out: &mut Vec<u8>) {
    out.extend_from_slice(self.as_str().as_bytes());
  }

  #[inline]
  fn read_cursor(bytes: &[u8]) -> Option<Self> {
    Some(Self::new(core::str::from_utf8(bytes).ok()?))
  }
}

/// **THE ADMISSION** — a payload kind is one element of one.
///
/// `Vec<BarcodePayloadKind>` is what a page carrying several codes classified under several kinds
/// holds, once a caller wants the kinds without the payloads.
impl crate::CollectionElement for BarcodePayloadKind {}

/// **THE DOCUMENT'S FORM: a BSON `String` holding the canonical slug** — the same text the `TEXT`
/// column above binds.
///
/// As with every other row of its kind here, this is the FILTER OPERAND's form and not a serde row.
#[cfg(feature = "mongo")]
impl crate::MongoCarrier for BarcodePayloadKind {
  #[inline]
  fn to_bson(&self) -> bson::Bson {
    bson::Bson::String(String::from(self.as_str()))
  }
}

/// **THE READ: the same slug, back through the door** — [`MongoCarrier`](crate::MongoCarrier)'s
/// mirror.
///
/// It carries NO range refusal, and the absence is this vocabulary's openness: a document holding a
/// `string` naming no member of the roster is an escape rather than an error. What survives is the
/// TYPE refusal — a document holding a number where a payload kind belongs is still wrong, and still
/// says which BSON type arrived.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for BarcodePayloadKind {
  const BSON: &'static str = "string";

  fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
    match value {
      Some(bson::Bson::String(text)) => Ok(Self::new(text)),
      Some(other) => Err(crate::query::mongo::MongoTypeError::wrong_type(
        Self::BSON,
        crate::query::mongo::alias(other),
      )),
      None => Err(crate::query::mongo::MongoTypeError::Absent),
    }
  }
}

/// **THE VOCABULARY READING** — `eq`, `ne`, `in` and `notIn`, and nothing else.
///
/// It is the ENUM filter and not the text one, and the difference is what the word IS. A
/// [`Label`](super::Label) is free text from a model's own roster, so `contains: "retriever"` is a
/// real question about a real family of words. A payload kind is a CLASSIFICATION, so the affix
/// family would answer a question about SPELLING rather than about which kind a payload was read
/// as — the same reasoning [`Symbology`](super::Symbology) makes for its own roster.
///
/// The ORDERING slots go with them, and for the same reason: alphabetical order over
/// `calendar < contact < …` is an order over the words rather than over the kinds, and no caller asks
/// for the payloads between two spellings.
///
/// **`in` is where the escape earns its keep.** A client asking about every structured payload writes
/// `{ in: ["wifi", "contact", "email", "phone", "sms", "geo", "calendar"] }`, and a client routing the
/// kinds it has never met writes `{ notIn: [ … the roster … ] }` — which is a question no closed enum
/// could express, there being nothing outside it.
impl crate::EnumFilterMarker for BarcodePayloadKind {
  type Filter = EnumFilter<BarcodePayloadKind>;
}

/// The interpretation a [`BarcodePayloadKind`] field is read under — the ENUM family's, which is
/// what puts `Option<BarcodePayloadKind>` on the `isNull` road.
impl DefaultMarker for BarcodePayloadKind {
  type Marker = EnumMarker<BarcodePayloadKind>;
}

/// **A COLLECTION of payload kinds is asked as a LIST** — the vocabulary's own operators lifted,
/// which is what an unordered set of words earns where a scored finding does not.
impl DefaultVecMarker for BarcodePayloadKind {
  type Marker = crate::ListMarker<Vec<BarcodePayloadKind>, EnumMarker<BarcodePayloadKind>>;
}