ingraph/primitives/detect/label.rs
1//! [`Label`]: the WORD a classifier put on something, validated for the one thing a word cannot be.
2
3use core::{fmt, str::FromStr};
4
5use smol_bytes::Utf8Bytes;
6
7use crate::{
8 ColumnKind, CursorValue, DefaultMarker, StringFilterMarker, StringMarker, TextFilter, TextWire,
9 column::column_eq,
10};
11
12#[cfg(test)]
13mod tests;
14
15/// **A CLASSIFICATION'S WORD** — what a detector, a classifier or a tagger says a thing IS.
16///
17/// A [`Utf8Bytes`] underneath, and a different type for the reason every newtype in
18/// [`primitives`](crate::primitives) is one: it carries an INVARIANT its representation cannot
19/// state. A label is a word somebody said, and *nothing at all* is not one — so [`new`](Self::new)
20/// is the only way in and it refuses the empty case.
21///
22/// # THE ENGINE OWNS NORMALISATION, AND THIS TYPE OWNS EXISTENCE
23///
24/// **This type does not fold case, and it never will.** The division is the producer's, stated in
25/// `avanalyze`'s own contract: *the engine lowercases and trims image-classification labels but
26/// passes animal labels through verbatim, and uses the literal `"person"` for human subjects — the
27/// label vocabulary is Apple's, not this crate's*. One producer therefore emits `cat` and `Golden
28/// Retriever` from the same run, deliberately, and a type that lowercased them both would be a type
29/// overruling the engine about a vocabulary the engine owns.
30///
31/// So `Cat` and `cat` are TWO labels here. A caller that wants them to be one asks with
32/// `containsNocase` or `eqNocase`'s neighbours on [`TextFilter`], which is where a case question
33/// belongs: a QUERY's, asked per query, rather than a value's, decided once for everybody at a
34/// constructor.
35///
36/// # WHAT IS REFUSED, and it is one rule
37///
38/// A label that is empty, **or that is nothing but whitespace**. The second clause is the first one
39/// read honestly: `" "` is a string a producer sent by accident, it names nothing, and admitting
40/// it would put a row in a table whose label no query can ever match and no reader can ever see.
41///
42/// **The whitespace is a PREDICATE and never a transform.** `Label::new(" cat ")` succeeds and
43/// holds `" cat "` — the six characters it was handed, byte for byte. That is the division above
44/// kept where it would have been easiest to bend: trimming is normalisation, normalisation is the
45/// engine's, and this crate has no trim-at-a-constructor anywhere else either. What the trim decides
46/// is *whether there is a word here*, not *what the word is*.
47///
48/// It follows that a value this crate wrote reads back byte for byte at every door — the decode, the
49/// cursor and the document all re-enter [`new`](Self::new), and a constructor that rewrites nothing
50/// admits exactly what it was given.
51///
52/// # NO VOCABULARY, and that is the ruling rather than an omission
53///
54/// A label is an OPEN word. Every model ships its own roster — Apple's image classifier, a
55/// zero-shot tagger, a barcode symbology reader — the rosters disagree, and none of them is a
56/// standard this crate could hold a table of. So there is no enum here and none is coming: an
57/// `#[ingraph::enumerate]` vocabulary over a model's output would be a closed surface over an open
58/// world, which is the one shape this framework does not build. See
59/// [`lang`](crate::primitives::lang), where the opposite case is argued — a language IS a standard,
60/// so it IS a type family.
61///
62/// # Examples
63///
64/// ```
65/// use ingraph::Label;
66///
67/// assert_eq!(Label::new("golden retriever").unwrap().as_str(), "golden retriever");
68///
69/// // Case is the ENGINE's, so two spellings are two labels.
70/// assert_ne!(Label::new("Cat").unwrap(), Label::new("cat").unwrap());
71///
72/// // The whitespace decides whether there is a word, and never what the word is.
73/// assert!(Label::new("").is_err());
74/// assert!(Label::new(" ").is_err());
75/// assert_eq!(Label::new(" cat ").unwrap().as_str(), " cat ");
76/// ```
77#[derive(Clone, PartialEq, Eq, PartialOrd, Ord, Hash)]
78pub struct Label(Utf8Bytes);
79
80impl Label {
81 /// Construct a label, or refuse a value that is not one.
82 ///
83 /// Takes anything the crate's text carrier is built from — a `&str`, a [`String`], a
84 /// [`Utf8Bytes`] already in hand — so a caller holding an owned word hands it over rather than
85 /// copying it, and `Label::new(Utf8Bytes::from_static("person"))` is the door a compile-time word
86 /// takes with no allocation at all.
87 ///
88 /// # Errors
89 ///
90 /// [`EmptyLabel`] where the text is empty or holds nothing but whitespace. It is the only refusal
91 /// this type has — see the type's note, where the case question is answered.
92 pub fn new(text: impl Into<Utf8Bytes>) -> Result<Self, EmptyLabel> {
93 let text = text.into();
94
95 if text.as_str().trim().is_empty() {
96 return Err(EmptyLabel);
97 }
98
99 Ok(Self(text))
100 }
101
102 /// The word, as text.
103 #[inline]
104 #[must_use]
105 pub fn as_str(&self) -> &str {
106 self.0.as_str()
107 }
108
109 /// The word, as the carrier it is held in.
110 #[inline]
111 #[must_use]
112 pub fn into_inner(self) -> Utf8Bytes {
113 self.0
114 }
115}
116
117/// The word itself, with nothing around it.
118impl fmt::Display for Label {
119 #[inline]
120 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
121 f.write_str(self.as_str())
122 }
123}
124
125/// The word QUOTED, under the type's own name — which is what makes a whitespace-carrying label
126/// visible in a test failure instead of vanishing into the alignment.
127impl fmt::Debug for Label {
128 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
129 write!(f, "Label({:?})", self.as_str())
130 }
131}
132
133impl FromStr for Label {
134 type Err = EmptyLabel;
135
136 #[inline]
137 fn from_str(text: &str) -> Result<Self, Self::Err> {
138 Self::new(text)
139 }
140}
141
142impl AsRef<str> for Label {
143 #[inline]
144 fn as_ref(&self) -> &str {
145 self.as_str()
146 }
147}
148
149/// The label, as the carrier it holds.
150///
151/// ONE direction, which is the type's whole subject: `From<Utf8Bytes> for Label` would say that any
152/// text IS a label, and the empty string is the counter-example this newtype exists to keep out of a
153/// row. Minting one is [`Label::new`], where the caller meets the refusal.
154impl From<Label> for Utf8Bytes {
155 #[inline]
156 fn from(label: Label) -> Self {
157 label.into_inner()
158 }
159}
160
161/// What gives `String: TryFrom<Label>` through std's blanket, which is the crossing a `TEXT`
162/// column's comparison makes — and it makes it with `Error = Infallible`, a label being valid text
163/// by construction.
164impl From<Label> for String {
165 #[inline]
166 fn from(label: Label) -> Self {
167 Self::from(label.as_str())
168 }
169}
170
171/// **What a label refuses a value with** — one sentence, at the four doors that mint one from the
172/// outside: a caller's constructor, a stored column, a cursor a client handed back, and a wire
173/// operand.
174///
175/// It carries no value, which is [`OutsideTheUnitInterval`](crate::OutsideTheUnitInterval)'s own
176/// shape and its reason: what is wrong is a property of the text the caller already has in hand, and
177/// a copy of nothing would be a second spelling of an empty string. The COLUMN's name arrives with
178/// the [`sqlx::Error::ColumnDecode`] this is wrapped in, and a wire operand travels back to a client
179/// in async-graphql's own error context.
180#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
181pub struct EmptyLabel;
182
183impl fmt::Display for EmptyLabel {
184 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
185 f.write_str("a label is a word: it holds at least one character that is not whitespace")
186 }
187}
188
189impl core::error::Error for EmptyLabel {}
190
191/// **ONE column**, which is the default — stated rather than inherited, because the two composites
192/// in this house read their own widths off this row and a reader auditing them should find the
193/// answer here rather than the absence of one.
194impl ColumnKind for Label {}
195
196// A label is the same as a label when its bytes are, byte for byte — no case fold, no trim: the
197// engine owns normalisation and this type owns only whether a word is there at all.
198column_eq! { Label }
199
200/// **THE STORED WORD is text's**, in every dialect that has one.
201///
202/// Delegated to [`String`] rather than named, for the reason the bind below is: a label IS its text,
203/// so the column is a text column and the dialect's own word for one is the only answer. The
204/// delegation carries the ADMISSION with it — a label is declarable exactly where text is, which is
205/// everywhere.
206///
207/// The non-emptiness is kept by the DECODE rather than by the schema; no dialect here has a `CHECK`
208/// this crate emits. See the assemble row below, which refuses.
209impl<Db> crate::StoredAs<Db> for Label
210where
211 String: crate::StoredAs<Db>,
212{
213 const WORDS: &'static [&'static str] = <String as crate::StoredAs<Db>>::WORDS;
214}
215
216/// **ONE BIND OUT** — the word, as text.
217///
218/// An OWNED [`String`] rather than the borrowed `&str` the slot already holds, and the reason is
219/// [`sqlx::QueryBuilder`]'s own lifetime rather than a preference: `push_bind` requires its value to
220/// outlive the builder's `'args`, which this trait's signature leaves unrelated to `&self`, so a
221/// borrow of `self` cannot satisfy it. That is the same copy every text newtype in
222/// [`primitives`](crate::primitives) pays at this seat.
223#[cfg(feature = "sqlx")]
224impl<Db> crate::Carrier<Db> for Label
225where
226 Db: sqlx::Database,
227 String: crate::Carrier<Db>,
228{
229 fn push_bind(&self, qb: &mut sqlx::QueryBuilder<Db>) {
230 <String as crate::Carrier<Db>>::push_bind(&String::from(self.as_str()), qb);
231 }
232}
233
234/// **AND THE WORD BACK IN**, through the constructor rather than around it.
235///
236/// A database is exactly the place that can hand back a value this type says cannot exist — a
237/// hand-written `UPDATE`, a restore, a column shared with something else — so the read refuses
238/// rather than substituting a placeholder. That is [`Count`](crate::Count)'s posture at its own
239/// column and every subtag's at theirs: loudly, at the row that held it, never a value quietly
240/// minted around the hole.
241#[cfg(feature = "sqlx")]
242impl<'a, R: sqlx::Row> crate::Assemble<'a, R> for Label
243where
244 String: crate::Assemble<'a, R>,
245{
246 fn assemble(row: &'a R, under: Option<&crate::Path<'_>>) -> sqlx::Result<Self> {
247 let stored: String = <String as crate::Assemble<'a, R>>::assemble(row, under)?;
248
249 Self::new(stored).map_err(|refused| sqlx::Error::Decode(Box::new(refused)))
250 }
251}
252
253/// **THE KEYSET POSITION**: the word's UTF-8 bytes, which is byte for byte what [`Utf8Bytes`]' own
254/// row writes — so a label column and a text column page past the same cursor.
255///
256/// No framing is added, and none may be: a cursor slot is already length-delimited by the layer
257/// above, so a row for a variable-width value writes the value and nothing else. The read
258/// RE-VALIDATES because a cursor is a string a CLIENT hands back — a forged empty position is
259/// refused rather than turned into a label whose type says it cannot exist.
260impl CursorValue for Label {
261 #[inline]
262 fn write_cursor(&self, out: &mut Vec<u8>) {
263 out.extend_from_slice(self.as_str().as_bytes());
264 }
265
266 #[inline]
267 fn read_cursor(bytes: &[u8]) -> Option<Self> {
268 Self::new(Utf8Bytes::try_from(bytes).ok()?).ok()
269 }
270}
271
272/// **THE DOCUMENT'S FORM: a BSON `String`** — the same text the `TEXT` column above binds, at the
273/// one BSON type that holds it.
274///
275/// A label is ONE WORD, so there is nothing here of a composite's key-set question. This row is the
276/// FILTER OPERAND's form and not a serde row, which is the posture every storage type this crate
277/// ships takes — see [`Timestamp`](crate::Timestamp)'s, where the `E0277` a bare column earns at a
278/// declaration is named.
279#[cfg(feature = "mongo")]
280impl crate::MongoCarrier for Label {
281 #[inline]
282 fn to_bson(&self) -> bson::Bson {
283 bson::Bson::String(String::from(self.as_str()))
284 }
285}
286
287/// **THE READ: the same word, back through the door** — [`MongoCarrier`](crate::MongoCarrier)'s
288/// mirror.
289///
290/// A `string` field is exactly as untrusted as the `TEXT` column [`Assemble`](crate::Assemble) above
291/// reads: nothing stops a document holding `""`, one written before this type existed, or one
292/// written by hand for a test. So the read goes through [`Label::new`] rather than wrapping the
293/// bytes.
294#[cfg(feature = "mongo")]
295impl crate::query::mongo::MongoExtract for Label {
296 const BSON: &'static str = "string";
297
298 fn extract(value: Option<&bson::Bson>) -> Result<Self, crate::query::mongo::MongoTypeError> {
299 match value {
300 Some(bson::Bson::String(text)) => Self::new(text.as_str()).map_err(|_refused| {
301 crate::query::mongo::MongoTypeError::Range(
302 "this field holds a string that is empty or nothing but whitespace, which is no label",
303 )
304 }),
305 Some(other) => Err(crate::query::mongo::MongoTypeError::wrong_type(
306 Self::BSON,
307 crate::query::mongo::alias(other),
308 )),
309 None => Err(crate::query::mongo::MongoTypeError::Absent),
310 }
311 }
312}
313
314/// **The TEXT reading**, which is what an open vocabulary earns.
315///
316/// A label takes the twenty-slot [`TextFilter`] rather than the eight-slot
317/// [`ScalarFilter`](crate::ScalarFilter) the [`lang`](crate::primitives::lang) subtags take, and the
318/// difference is what the two words ARE. A subtag is one token of a closed grammar, so *does it
319/// start with* is a question about spelling rather than about meaning. A label is FREE TEXT from a
320/// model's own roster — `golden retriever`, `traffic light`, `person` — so `contains: "retriever"`
321/// is a real question a real client asks, and the `nocase` half of every affix slot is where the
322/// case this type refuses to fold gets asked about instead.
323///
324/// The lexical ORDERING slots come with the kind and they are honest here: text has a byte order,
325/// [`Utf8Bytes`] publishes a filter carrying `gt`/`gte`/`lt`/`lte` over exactly that order, and the
326/// non-emptiness rule disturbs none of it. A label column is an ORDER SUBJECT in the same breath —
327/// see the [`CursorValue`] row above, which is what a page walks.
328impl StringFilterMarker for Label {
329 type Filter = TextFilter<Label, LabelWire>;
330}
331
332/// The interpretation a [`Label`] field is read under — the TEXT family's, which is what puts
333/// `Option<Label>` on the `isNull` road rather than on a collection's.
334impl DefaultMarker for Label {
335 type Marker = StringMarker<Label>;
336}
337
338/// How a label crosses when the framework's own text filter holds it — the reading that gives
339/// `TextFilter<Label, LabelWire>` a face.
340///
341/// A marker carrying the wire NAME beside the operand, which is the shape every registered text
342/// filter here takes: `TextFilter<S, I>`'s second parameter is what its input object is called, so a
343/// filter over a label is named by a TYPE rather than by a table only this crate could extend. It is
344/// the surface a declaring crate joins through, and this house is the framework's own worked example
345/// of doing so with a validated newtype.
346///
347/// **The carrier is [`String`] and the crossing is FALLIBLE**, which is the whole difference from
348/// the [`lang`](crate::primitives::lang) subtags' [`ScalarWire`](crate::ScalarWire) rows: those
349/// types ARE their own GraphQL scalars, so a refusal happens at the scalar's door and the crossing
350/// is [`Infallible`](core::convert::Infallible). A label publishes NO scalar of its own — see the
351/// module note, where the retirement that decided it is cited — so this row is the door, and
352/// `{ eq: "" }` meets [`EmptyLabel`] here.
353pub enum LabelWire {}
354
355impl TextWire<Label> for LabelWire {
356 const NAME: &'static str = "LabelFilter";
357
358 type Carrier = String;
359 type Error = EmptyLabel;
360
361 #[inline]
362 fn cross(carrier: String) -> Result<Label, Self::Error> {
363 Label::new(carrier)
364 }
365
366 #[inline]
367 fn carry(operand: &Label) -> String {
368 String::from(operand.as_str())
369 }
370}
371
372/// **THE CROSSING IN — a label arrives as the roster's own `String`**, and the non-emptiness is kept
373/// HERE.
374///
375/// No `#[Scalar]` of its own, and the absence is [`NormCoord`](crate::NormCoord)'s ruling one house
376/// over rather than an omission: a named scalar has to say something the roster does not, and what a
377/// `Label` scalar would have said is NON-EMPTY — a constructor's promise rather than a grammar,
378/// which a client can act on nowhere. So a label column and a plain text column publish one SDL
379/// scalar, the rule reaches a reader through the FIELD's documentation, and every operand reaches it
380/// through [`Label::new`], which this row calls.
381#[cfg(feature = "async-graphql")]
382impl crate::ToGraphqlInput for Label {
383 type Input = String;
384 type Error = EmptyLabel;
385
386 #[inline]
387 fn cross(input: String) -> Result<Self, EmptyLabel> {
388 Self::new(input)
389 }
390
391 #[inline]
392 fn carry(operand: &Self) -> String {
393 String::from(operand.as_str())
394 }
395}
396
397/// **AND OUT**, mirroring the row above so the two directions cannot come to disagree.
398///
399/// A BORROW of the text rather than of the value, which is [`Utf8Bytes`]' own bargain at this seat:
400/// the label has no scalar to be returned as, so what a field yields is the string it holds.
401#[cfg(feature = "async-graphql")]
402impl crate::ToGraphqlOutput for Label {
403 type Output<'a> = &'a str;
404
405 #[inline]
406 fn to_graphql_output(marked: &Self) -> &str {
407 marked.as_str()
408 }
409}