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
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
//! [`Symbology`]: which barcode standard a payload was read under — twenty-four 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 type name every `VNBarcodeObservation` writes in front of the word — what
/// [`Symbology::from_vision`] removes and the plain door does not.
const VISION_PREFIX: &str = "VNBarcodeSymbology";

/// **THE BARCODE STANDARD a payload was encoded in** — twenty-four named symbologies, plus an
/// escape for a word this vocabulary does not name.
///
/// ```text
///   2D        aztec  data_matrix  pdf417  micro_pdf417  qr  micro_qr
///   RETAIL    ean8  ean13  upce  gs1_data_bar  …_expanded  …_limited
///   LINEAR    codabar  code39 (+3 variants)  code93  code93i  code128
///             i2of5  i2of5_checksum  itf14  msi_plessey
/// ```
///
/// # It is a VOCABULARY and not a payload format
///
/// A symbology says how the bars were READ, not what the payload MEANS. A QR code carrying a URL
/// and one carrying a Wi-Fi credential are both `qr`; what separates them is the text, which is
/// [`BarcodeDetection`](super::BarcodeDetection)'s own field.
///
/// # It is DOMAIN-NEUTRAL, which is why it is here at all
///
/// A barcode is read off a photograph, a scanned invoice, a PDF page and a shipping label, and none
/// of those is a camera's business more than another's. That is the same sentence
/// [`Label`](super::Label) makes one file over, and it is the ruling that sent this cluster
/// upstream: the vision-flavoured payloads — poses, masks, landmark contours — stayed downstream,
/// and the ones a document graph would declare came here.
///
/// # OPEN, and the escape is why the wire face is a SCALAR
///
/// The roster is Apple's Vision list, hand-stated: [`VNBarcodeSymbology`] publishes exactly these
/// twenty-four. It was read out of a documentation page rather than out of a machine-readable
/// registry, so a decoder this crate has not met reads a standard this crate has not named — and
/// carrying that word is better than refusing the detection that carried it. 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 `dataMatrix`, `DATA_MATRIX` and `data matrix` are
/// one value. The escape carries the MATERIALISED fold, so two producers writing `foo-bar` and
/// `FooBar` for a standard nobody here names are one value, compare equal and hash into one bucket.
///
/// # Apple's TYPE PREFIX is [`from_vision`](Self::from_vision)'s business and not the door's
///
/// A producer of barcodes hands over `VNBarcodeSymbologyQR`, and the plain door CARRIES that whole
/// string rather than reading `qr` out of it. Removing the prefix is one adapter's job and it has
/// its own entry, because the fold is a rule about SPELLINGS and a vendor namespace is not one: the
/// fold is the framework's, shared by every open vocabulary in the workspace, and a strip word there
/// would be a second rule that only one house ever used.
///
/// # The roster's own shape
///
/// **The CHECKSUM variants are separate members and not a flag**, which is the source's own shape
/// and the right one: `code39` and `code39_checksum` are two ways a decoder was configured, and a
/// row recording only `code39` would lose whether the check digit was verified.
///
/// **`code93i` is not a typo.** It is Code 93i, the extended variant, and Vision spells it with the
/// lower-case letter attached.
///
/// # Examples
///
/// ```
/// use ingraph::Symbology;
///
/// assert_eq!(Symbology::new("qr"), Symbology::Qr);
/// assert_eq!(Symbology::new("DATA_MATRIX"), Symbology::DataMatrix);
/// assert_eq!(Symbology::new("data matrix"), Symbology::DataMatrix);
///
/// // …and a standard this roster does not name is carried rather than refused.
/// let unknown = Symbology::new("Han Xin");
/// assert!(unknown.is_other());
/// assert_eq!(unknown.as_str(), "hanxin");
/// ```
///
/// [`VNBarcodeSymbology`]: https://developer.apple.com/documentation/vision/vnbarcodesymbology
#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub enum Symbology {
  /// Aztec Code — a 2D matrix with a bullseye at its centre.
  Aztec,
  /// Codabar — a linear code used on blood bags and library cards.
  Codabar,
  /// Code 39, without a check digit.
  Code39,
  /// Code 39, with its check digit verified.
  Code39Checksum,
  /// Code 39 Full ASCII, without a check digit.
  Code39FullAscii,
  /// Code 39 Full ASCII, with its check digit verified.
  Code39FullAsciiChecksum,
  /// Code 93.
  Code93,
  /// Code 93i, the extended variant.
  Code93i,
  /// Code 128.
  Code128,
  /// Data Matrix — a 2D matrix with an L-shaped finder.
  DataMatrix,
  /// EAN-8, the short retail article number.
  Ean8,
  /// EAN-13, the retail article number on almost every product.
  Ean13,
  /// GS1 DataBar.
  Gs1DataBar,
  /// GS1 DataBar Expanded.
  Gs1DataBarExpanded,
  /// GS1 DataBar Limited.
  Gs1DataBarLimited,
  /// Interleaved 2 of 5, without a check digit.
  I2of5,
  /// Interleaved 2 of 5, with its check digit verified.
  I2of5Checksum,
  /// ITF-14, the shipping-container form of Interleaved 2 of 5.
  Itf14,
  /// MicroPDF417 — PDF417's compact form.
  MicroPdf417,
  /// Micro QR — QR's compact form.
  MicroQr,
  /// MSI Plessey — a linear code used on shelf labels.
  MsiPlessey,
  /// PDF417 — a stacked linear code, common on boarding passes and identity documents.
  Pdf417,
  /// QR Code.
  Qr,
  /// UPC-E, the compressed Universal Product Code.
  Upce,
  /// A symbology this roster does not name, carrying its FOLDED word.
  ///
  /// The escape is what makes the vocabulary open: a decoder emitting a standard 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`](Symbology::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: [`Symbology::new`] walks this table
/// under the fold and [`Symbology::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: &[(Symbology, &str)] = &[
  (Symbology::Aztec, "aztec"),
  (Symbology::Codabar, "codabar"),
  (Symbology::Code39, "code39"),
  (Symbology::Code39Checksum, "code39_checksum"),
  (Symbology::Code39FullAscii, "code39_full_ascii"),
  (
    Symbology::Code39FullAsciiChecksum,
    "code39_full_ascii_checksum",
  ),
  (Symbology::Code93, "code93"),
  (Symbology::Code93i, "code93i"),
  (Symbology::Code128, "code128"),
  (Symbology::DataMatrix, "data_matrix"),
  (Symbology::Ean8, "ean8"),
  (Symbology::Ean13, "ean13"),
  (Symbology::Gs1DataBar, "gs1_data_bar"),
  (Symbology::Gs1DataBarExpanded, "gs1_data_bar_expanded"),
  (Symbology::Gs1DataBarLimited, "gs1_data_bar_limited"),
  (Symbology::I2of5, "i2of5"),
  (Symbology::I2of5Checksum, "i2of5_checksum"),
  (Symbology::Itf14, "itf14"),
  (Symbology::MicroPdf417, "micro_pdf417"),
  (Symbology::MicroQr, "micro_qr"),
  (Symbology::MsiPlessey, "msi_plessey"),
  (Symbology::Pdf417, "pdf417"),
  (Symbology::Qr, "qr"),
  (Symbology::Upce, "upce"),
];

impl Symbology {
  /// 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] = &[
    "aztec",
    "codabar",
    "code39",
    "code39_checksum",
    "code39_full_ascii",
    "code39_full_ascii_checksum",
    "code93",
    "code93i",
    "code128",
    "data_matrix",
    "ean8",
    "ean13",
    "gs1_data_bar",
    "gs1_data_bar_expanded",
    "gs1_data_bar_limited",
    "i2of5",
    "i2of5_checksum",
    "itf14",
    "micro_pdf417",
    "micro_qr",
    "msi_plessey",
    "pdf417",
    "qr",
    "upce",
  ];

  /// Read a symbology 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 symbology, because the escape is
  /// what an open vocabulary means. `qr` names a standard this crate knows and `Han Xin` 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 twenty-four 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)))
  }

  /// Read the raw constant Apple's Vision framework hands over — `"VNBarcodeSymbologyQR"` and its
  /// twenty-three siblings — by removing the TYPE NAME in front of the word and then walking the
  /// ordinary door.
  ///
  /// This is an INTEROP entry and not a second parse. What it removes is a NAMESPACE, which makes
  /// `VNBarcodeSymbologyQR` and `qr` one word spelled two ways; two different words somebody decided
  /// meant the same thing would be a claim, and no function in this crate makes one.
  ///
  /// The prefix is matched under the door's own relation — ASCII case ignored, `_`, `-` and a space
  /// skipped — so `VNBarcodeSymbologyQR`, `vn_barcode_symbology_qr` and `VNBARCODESYMBOLOGY-QR` all
  /// leave `QR` behind. A string that is NOTHING BUT the prefix is left alone: stripping it would
  /// leave an empty word, which names nothing and would ride the escape carrying nothing.
  ///
  /// A word with no prefix on it reaches the same member either way, so an adapter that is not sure
  /// what its producer wrote can call this one unconditionally.
  ///
  /// # Examples
  ///
  /// ```
  /// use ingraph::Symbology;
  ///
  /// assert_eq!(Symbology::from_vision("VNBarcodeSymbologyQR"), Symbology::Qr);
  /// assert_eq!(Symbology::from_vision("qr"), Symbology::Qr);
  ///
  /// // The PLAIN door does not do this, which is the whole reason this entry exists.
  /// assert!(Symbology::new("VNBarcodeSymbologyQR").is_other());
  /// ```
  #[must_use]
  pub fn from_vision(raw: &str) -> Self {
    Self::new(without_vision_prefix(raw))
  }

  /// 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 standards 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 remainder of `raw` after [`VISION_PREFIX`], under the door's own fold — or `raw` itself where
/// it does not begin with one, or is nothing but one.
///
/// The returned index sits immediately after an ASCII byte the prefix matched, so it is always a
/// character boundary; `get` is used rather than an index anyway, because a boundary this function
/// establishes is a claim and not a proof.
fn without_vision_prefix(raw: &str) -> &str {
  let separator = |byte: u8| matches!(byte, b'_' | b'-' | b' ');

  let mut wanted = VISION_PREFIX.bytes().filter(|byte| !separator(*byte));
  let bytes = raw.as_bytes();
  let mut at = 0;

  loop {
    let Some(want) = wanted.next() else {
      return match raw.get(at..) {
        Some(rest) if !rest.is_empty() => rest,
        _ => raw,
      };
    };

    loop {
      let Some(byte) = bytes.get(at).copied() else {
        return raw;
      };
      at += 1;

      if separator(byte) {
        continue;
      }

      if !byte.eq_ignore_ascii_case(&want) {
        return raw;
      }

      break;
    }
  }
}

/// The canonical slug, and nothing else — no quotes, no wrapper, no type name.
impl fmt::Display for Symbology {
  #[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 Symbology {
  #[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 symbology.
impl core::str::FromStr for Symbology {
  type Err = core::convert::Infallible;

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

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

impl From<Symbology> for String {
  #[inline]
  fn from(symbology: Symbology) -> Self {
    Self::from(symbology.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 Symbology {}

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

// A symbology is the same as a symbology when its canonical slug is — the escape's word is
// materialised and folded at construction, so two producers spelling one standard differently
// already compare equal here.
column_eq! { Symbology }

/// **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 symbology 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 symbology is declarable exactly where
/// text is, which is everywhere.
impl<Db> crate::StoredAs<Db> for Symbology
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 Symbology
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) one file over: 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 symbology this crate has never heard of is still a symbology.
/// A stored word the roster does not name comes back through the escape, CANONICALISED rather than
/// wrapped, so a hand-written `UPDATE` writing `DATA-MATRIX` reads back as the named member.
#[cfg(feature = "sqlx")]
impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for Symbology
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 Symbology {
  #[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 symbology is one element of one.
///
/// `Vec<Symbology>` is what a frame carrying several codes read under several standards holds, once
/// a caller wants the standards without the payloads.
impl crate::CollectionElement for Symbology {}

/// **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 Symbology {
  #[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 symbology belongs is still wrong, and still
/// says which BSON type arrived.
#[cfg(feature = "mongo")]
impl crate::query::mongo::MongoExtract for Symbology {
  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 symbology is a STANDARD, so the affix family would
/// answer questions about SPELLING: `contains: "qr"` matches `micro_qr`, which is true of the two
/// slugs and false of the two standards.
///
/// The ORDERING slots go with them, and for the same reason: alphabetical order over
/// `aztec < code128 < qr` is an order over the words rather than over the standards, and no caller
/// asks for the barcodes between two spellings. That is the ONE place this house's open vocabulary
/// parts company with the codec citizens, which take the wide scalar kind because a codec column IS
/// paged over.
///
/// **`in` is where the escape earns its keep.** A client asking about every 2D matrix writes
/// `{ in: ["qr", "micro_qr", "aztec", "data_matrix"] }`, and a client routing the standards 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 Symbology {
  type Filter = EnumFilter<Symbology>;
}

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

/// **A COLLECTION of symbologies 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 Symbology {
  type Marker = crate::ListMarker<Vec<Symbology>, EnumMarker<Symbology>>;
}