Skip to main content

vitaminc_ore/
target.rs

1//! Targets a caller names when the program is compiled, and the tables
2//! that say what fits them.
3//!
4//! An order space declares the type every value in it is encoded as: its
5//! target. [`OrderTarget`] names one while the program runs, as an index
6//! layer that reads its column types from a schema must. The zero-sized
7//! markers here name one when the program is compiled, so the compiler can
8//! check what goes in: [`FitsIn`] lists the conversions that never lose
9//! information, and [`Orderable`] gives a Rust type the target it is.
10//! Both are sealed tables, generated in this module, so no caller can add
11//! a conversion that might be refused or infer a target from a value.
12//!
13//! The same method takes either: [`OrderEncrypt::target`] is generic over
14//! [`Target`], which every marker and [`OrderTarget`] implement.
15//!
16//! A space can also place nulls first or last, and the policy follows the
17//! target. On a fixed-width marker it is a marker too, [`First`] or
18//! [`Last`], and the space's target becomes [`Nulls<T, P>`](Nulls): the
19//! compiler keeps a nulls-first term out of a nulls-last space's
20//! comparison, as it keeps an `I64` term out of an `I32` space's. On an
21//! [`OrderTarget`] it is a [`NullOrder`] chosen while the program runs,
22//! and the target becomes a [`RuntimeNulls`], whose terms carry their
23//! policy and compare as `None` with a term of the other.
24//!
25//! [`OrderEncrypt::target`]: crate::OrderEncrypt::target
26
27use core::fmt;
28use core::marker::PhantomData;
29
30use vitaminc_aead::{Bytes as RawBytes, Encrypt};
31
32use crate::{NullOrder, OrderScheme, OrderTarget};
33
34mod private {
35    /// Seals [`Target`](super::Target), [`FitsIn`](super::FitsIn) and
36    /// [`Orderable`](super::Orderable) to this crate.
37    pub trait Sealed {}
38}
39
40/// A target an order space can be opened with: one of the zero-sized
41/// markers in this module, named when the program is compiled, or an
42/// [`OrderTarget`], chosen while it runs.
43///
44/// Sealed: every target is one this crate encodes.
45pub trait Target: private::Sealed + Copy + fmt::Debug {
46    /// The target as the value every encoding is keyed by.
47    fn runtime(self) -> OrderTarget;
48
49    /// Where a space of this target places nulls: `None`, unless the
50    /// target is a [`Nulls`] or a [`RuntimeNulls`], which a space's
51    /// `nulls` method makes.
52    fn null_order(self) -> Option<NullOrder> {
53        None
54    }
55}
56
57/// A target known when the program is compiled: one of the markers in this
58/// module. What a space of such a target takes is checked by the compiler,
59/// through [`FitsIn`].
60pub trait StaticTarget: Target + Default {
61    /// The target this marker stands for.
62    const TARGET: OrderTarget;
63}
64
65/// A marker target of fixed width: every marker but [`Text`] and
66/// [`Bytes`]. Only these take a null policy, so
67/// `scheme.target(I32).nulls(Last)` compiles and
68/// `scheme.target(Text).nulls(Last)` does not.
69///
70/// Sealed: implemented for the thirteen fixed-width markers here.
71#[diagnostic::on_unimplemented(
72    message = "`{Self}` takes no null policy",
73    label = "not a fixed-width target",
74    note = "only a fixed-width target places nulls first or last: a text or bytes null already shows by its length, so placing it would hide nothing"
75)]
76pub trait FixedWidth: StaticTarget {}
77
78/// The null policy of a space whose target is named when the program is
79/// compiled: [`First`] or [`Last`], which a marker space's `nulls` method
80/// takes. The policy is then part of the space's type, as the target is.
81///
82/// Sealed: [`First`] and [`Last`] are the only policies.
83pub trait NullPolicy: private::Sealed + Copy + fmt::Debug + Default {
84    /// Where a space of this policy places nulls.
85    const ORDER: NullOrder;
86}
87
88/// Nulls sort below every value, as SQL's `NULLS FIRST`: the policy
89/// [`NullOrder::First`], named when the program is compiled.
90#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
91pub struct First;
92
93/// Nulls sort above every value, as SQL's `NULLS LAST`: the policy
94/// [`NullOrder::Last`], named when the program is compiled.
95#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
96pub struct Last;
97
98impl private::Sealed for First {}
99impl private::Sealed for Last {}
100
101impl NullPolicy for First {
102    const ORDER: NullOrder = NullOrder::First;
103}
104
105impl NullPolicy for Last {
106    const ORDER: NullOrder = NullOrder::Last;
107}
108
109/// A marker target in a space that places nulls first or last: the
110/// target `T` and the policy `P`, both part of the type. Made only by a
111/// marker space's `nulls` method, from a fixed-width target, so every
112/// `Nulls` names a domain label.
113///
114/// A space of a `Nulls` target is not a [`StaticTarget`] space, so it has
115/// no `encrypt`: the policy refuses the maximum of an integer or uuid
116/// target, so a value goes through `encrypt_checked`, which reports it.
117/// Terms of a `Nulls<I32, Last>` space do not compile against an `I32`
118/// space's comparison, nor against a `Nulls<I32, First>` space's.
119#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
120pub struct Nulls<T, P: NullPolicy> {
121    target: T,
122    policy: PhantomData<P>,
123}
124
125impl<T: FixedWidth, P: NullPolicy> Nulls<T, P> {
126    pub(crate) fn new(target: T) -> Self {
127        Self {
128            target,
129            policy: PhantomData,
130        }
131    }
132
133    /// The target the policy is set on.
134    pub fn target(self) -> T {
135        self.target
136    }
137
138    /// Where the space places nulls: `P`'s order.
139    pub fn null_order(self) -> NullOrder {
140        P::ORDER
141    }
142}
143
144impl<T: FixedWidth, P: NullPolicy> private::Sealed for Nulls<T, P> {}
145
146impl<T: FixedWidth, P: NullPolicy> Target for Nulls<T, P> {
147    fn runtime(self) -> OrderTarget {
148        self.target.runtime()
149    }
150
151    fn null_order(self) -> Option<NullOrder> {
152        Some(P::ORDER)
153    }
154}
155
156/// A scheme takes a target in a space that places nulls exactly when it
157/// takes the target: the policy changes no width.
158impl<S: Supports<T> + ?Sized, T: FixedWidth, P: NullPolicy> Supports<Nulls<T, P>> for S {
159    fn supports(target: Nulls<T, P>) -> bool {
160        <S as Supports<T>>::supports(target.target)
161    }
162}
163
164/// A target chosen while the program runs, in a space that places nulls
165/// first or last: the [`OrderTarget`] and its [`NullOrder`], both values.
166/// Made only by `nulls` on a space of an [`OrderTarget`], which refuses
167/// text and bytes, so every `RuntimeNulls` names a domain label.
168///
169/// This is for a layer that reads its column types and null policies from
170/// a schema while the program runs. Every term of such a space carries its
171/// policy, as it carries its target, so a nulls-first and a nulls-last
172/// term of one target compare as `None` rather than as noise.
173#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
174pub struct RuntimeNulls {
175    target: OrderTarget,
176    order: NullOrder,
177}
178
179impl RuntimeNulls {
180    pub(crate) fn new(target: OrderTarget, order: NullOrder) -> Self {
181        Self { target, order }
182    }
183
184    /// The target the policy is set on.
185    pub fn target(self) -> OrderTarget {
186        self.target
187    }
188
189    /// Where the space places nulls.
190    pub fn null_order(self) -> NullOrder {
191        self.order
192    }
193}
194
195impl private::Sealed for RuntimeNulls {}
196
197impl Target for RuntimeNulls {
198    fn runtime(self) -> OrderTarget {
199        self.target
200    }
201
202    fn null_order(self) -> Option<NullOrder> {
203        Some(self.order)
204    }
205}
206
207/// A scheme takes a target chosen while the program runs, in a space that
208/// places nulls, exactly when it takes the target.
209impl<S: Supports<OrderTarget> + ?Sized> Supports<RuntimeNulls> for S {
210    fn supports(target: RuntimeNulls) -> bool {
211        <S as Supports<OrderTarget>>::supports(target.target)
212    }
213}
214
215impl private::Sealed for OrderTarget {}
216
217impl Target for OrderTarget {
218    fn runtime(self) -> OrderTarget {
219        self
220    }
221}
222
223/// A value that always fits target `T`: the conversion loses nothing and
224/// the encoding refuses nothing, so [`OrderSpace::encrypt`] can take it
225/// without a value-refusal arm in its error.
226///
227/// A sealed table, one impl per conversion:
228///
229/// | Target | Takes |
230/// | --- | --- |
231/// | an integer target | every integer type whose whole range it holds, so `I32` takes `i8`, `i16`, `i32` and `u16` (a `u8` is not a scalar of the data model: `Vec<u8>` is bytes). There is no 8-bit target, so an `i8` fits `I16` and up: see [`OrderTarget`] |
232/// | `F64` | `f32`, `f64` |
233/// | `Bytes` | `&[u8]`, `Vec<u8>`, `[u8; N]`, [`Bytes`](vitaminc_aead::Bytes) |
234/// | `Date` | `jiff::civil::Date`, `vitaminc_aead::Date` (feature `jiff`) |
235/// | `Timestamp` | `vitaminc_aead::Timestamp` (feature `jiff`) |
236/// | `Decimal` | `rust_decimal::Decimal`, `vitaminc_aead::Decimal` (feature `rust_decimal`) |
237/// | `Uuid` | `uuid::Uuid`, `vitaminc_aead::Uuid` (feature `uuid`) |
238///
239/// and a reference to any of them. What is not here can be refused: an
240/// `i64` may not fit `I32`, text may hold a code point Unicode 16 does not
241/// assign, and a `jiff::Timestamp` may lie just outside jiff's own range
242/// (see `vitaminc_aead::OutOfRange`). Those go through
243/// [`OrderSpace::encrypt_checked`], which checks the value while the
244/// program runs.
245///
246/// [`OrderSpace::encrypt`]: crate::OrderSpace::encrypt
247/// [`OrderSpace::encrypt_checked`]: crate::OrderSpace::encrypt_checked
248#[diagnostic::on_unimplemented(
249    message = "`{Self}` is not a value that always fits `{T}`",
250    label = "does not always fit `{T}`",
251    note = "`encrypt` takes a value the encoding never refuses: a narrower integer, an `f32`, bytes, or a typed value such as a `jiff::civil::Date`",
252    note = "a value the encoding can refuse (an integer that may be out of range, text, a `jiff::Timestamp`, or any other `Encrypt` value) goes through `encrypt_checked`, which checks it while the program runs"
253)]
254pub trait FitsIn<T: StaticTarget>: Encrypt + private::Sealed {}
255
256/// A type that orders as itself: it can go into an order index without
257/// naming a target, through [`OrderEncrypt::encrypt`] and the other chains
258/// that name none. An `i64` is an `I64`, an `f32` an `F64`, a `&str` a
259/// `Text`.
260///
261/// Not being `Orderable` does not mean a value cannot be ordered, only
262/// that its target must be named:
263///
264/// - An `i8` orders into a wider target it fits, by name:
265///   `scheme.target(I16).encrypt(value)`. It has no target of its own,
266///   because an order term over 256 values reveals them (see
267///   [`OrderTarget`]).
268/// - Bytes order into `Bytes`, by name. No ordering operator compares
269///   bytes, so an order term over them reveals the order of the rows and
270///   answers no query; asking for one is a decision, not a default.
271/// - A newtype names its target with [`OrderEncrypt::target`].
272///
273/// Sealed, and implemented for the data model's own types only. A target
274/// is never inferred from a value: a JavaScript `BigInt` arrives as the
275/// narrowest integer that holds it, and inferring from the value would
276/// scatter one index across several domains.
277///
278/// [`OrderEncrypt::encrypt`]: crate::OrderEncrypt::encrypt
279/// [`OrderEncrypt::target`]: crate::OrderEncrypt::target
280#[diagnostic::on_unimplemented(
281    message = "`{Self}` is not `Orderable`: it has no order target of its own",
282    label = "has no order target of its own",
283    note = "name the target: `scheme.target(I64).encrypt_checked(value)`",
284    note = "there is no 8-bit target: an order term over 256 values reveals them, so an `i8` goes into `I16` or wider by name (`scheme.target(I16).encrypt(value)`), or into an equality index",
285    note = "bytes order only into a target named for them, `scheme.target(Bytes)`: no ordering operator compares bytes"
286)]
287pub trait Orderable: Encrypt + private::Sealed {
288    /// The target this type is.
289    type Target: StaticTarget;
290}
291
292/// What a scheme takes: implemented by a scheme crate for every target
293/// its scheme encrypts, so that `scheme.target(Text)` on a fixed-width
294/// scheme fails to compile rather than returning
295/// [`OrderError::Unsupported`](crate::OrderError::Unsupported).
296///
297/// A scheme answers twice. `Supports<OrderTarget>` is required of every
298/// scheme (no space of any target opens without it), and its
299/// [`supports`](Self::supports) says which targets the scheme takes when
300/// one is chosen while the program runs. `Supports<I32>` and the other
301/// marker impls say the same when the target is named as the program is
302/// compiled. A scheme writes both at once with
303/// [`supports_targets!`](crate::supports_targets), from one list, so
304/// they cannot disagree; a scheme that takes every target writes
305/// [`supports_every_target!`](crate::supports_every_target). A space
306/// asks the runtime answer for every target it is opened with, and in a
307/// debug build asserts that a marker's answer agrees.
308///
309/// A scheme never answers for a target in a space that places nulls
310/// ([`Nulls`], [`RuntimeNulls`]): this crate answers for it, with the
311/// answer for the target
312/// the policy is set on, since the policy changes no width. Those impls
313/// cover every scheme, so a scheme cannot implement `Supports` for every
314/// `T: Target` at once; it lists its targets, as the macros do.
315#[diagnostic::on_unimplemented(
316    message = "`{Self}` has no order term for `{T}`",
317    label = "does not implement `Supports<{T}>`",
318    note = "a scheme lists the targets it takes with `vitaminc_ore::supports_targets!(Scheme; I32, Date)`, which answers for each marker and for `OrderTarget`; pick one it lists, or an `OrderTarget` chosen while the program runs"
319)]
320pub trait Supports<T: Target>: OrderScheme {
321    /// Whether the scheme takes terms of `target`. For a marker, `true`
322    /// (the impl exists); for an [`OrderTarget`], the scheme's list.
323    fn supports(target: T) -> bool;
324}
325
326/// Implement [`Supports`] for the targets a scheme takes, from one list:
327/// once for [`OrderTarget`], answering `true` for a listed target, and
328/// once per listed marker.
329///
330/// ```
331/// # use vitaminc_ore::{Context, OrderPlaintext, OrderScheme};
332/// # struct TenBytes;
333/// # impl OrderScheme for TenBytes {
334/// #     const NAME: &'static str = "ten-bytes";
335/// #     type Term = Vec<u8>;
336/// #     type Error = core::convert::Infallible;
337/// #     type Space = ();
338/// #     fn open(&self, _: vitaminc_ore::OrderTarget, _: &Context<'_>) -> Result<(), Self::Error> {
339/// #         Ok(())
340/// #     }
341/// #     fn encrypt_plaintext(&self, _: &(), p: &OrderPlaintext) -> Result<Vec<u8>, Self::Error> {
342/// #         use vitaminc_protected::Controlled;
343/// #         Ok(p.bytes().risky_ref().clone())
344/// #     }
345/// #     fn compare(a: &Vec<u8>, b: &Vec<u8>) -> Option<core::cmp::Ordering> { Some(a.cmp(b)) }
346/// # }
347/// // A fixed-width scheme over at most ten bytes.
348/// vitaminc_ore::supports_targets!(TenBytes; I16, U16, I32, U32, I64, U64, F64, Date);
349/// ```
350#[macro_export]
351macro_rules! supports_targets {
352    ($scheme:ty; $($marker:ident),* $(,)?) => {
353        impl $crate::Supports<$crate::OrderTarget> for $scheme {
354            fn supports(target: $crate::OrderTarget) -> bool {
355                #[allow(unreachable_patterns)]
356                match target {
357                    $($crate::OrderTarget::$marker => true,)*
358                    _ => false,
359                }
360            }
361        }
362        $(
363            impl $crate::Supports<$crate::target::$marker> for $scheme {
364                fn supports(_: $crate::target::$marker) -> bool {
365                    true
366                }
367            }
368        )*
369    };
370}
371
372/// Implement [`Supports`] for every target, for a scheme that takes them
373/// all, as the CLWW schemes do: [`supports_targets!`] with the full list.
374///
375/// ```
376/// # use vitaminc_ore::{Context, OrderPlaintext, OrderScheme};
377/// # struct Cllw;
378/// # impl OrderScheme for Cllw {
379/// #     const NAME: &'static str = "cllw";
380/// #     type Term = Vec<u8>;
381/// #     type Error = core::convert::Infallible;
382/// #     type Space = ();
383/// #     fn open(&self, _: vitaminc_ore::OrderTarget, _: &Context<'_>) -> Result<(), Self::Error> {
384/// #         Ok(())
385/// #     }
386/// #     fn encrypt_plaintext(&self, _: &(), p: &OrderPlaintext) -> Result<Vec<u8>, Self::Error> {
387/// #         use vitaminc_protected::Controlled;
388/// #         Ok(p.bytes().risky_ref().clone())
389/// #     }
390/// #     fn compare(a: &Vec<u8>, b: &Vec<u8>) -> Option<core::cmp::Ordering> { Some(a.cmp(b)) }
391/// # }
392/// vitaminc_ore::supports_every_target!(Cllw);
393/// ```
394#[macro_export]
395macro_rules! supports_every_target {
396    ($scheme:ty) => {
397        $crate::supports_targets!($scheme;
398            I16, U16, I32, U32, I64, U64, I128, U128,
399            F64, Date, Timestamp, Decimal, Text, Bytes, Uuid);
400    };
401}
402
403/// One marker per target, each a zero-sized `Copy` type that stands for
404/// its [`OrderTarget`] variant.
405macro_rules! markers {
406    ($($(#[$doc:meta])* $marker:ident),* $(,)?) => {
407        $(
408            $(#[$doc])*
409            #[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash)]
410            pub struct $marker;
411
412            impl private::Sealed for $marker {}
413
414            impl Target for $marker {
415                fn runtime(self) -> OrderTarget {
416                    OrderTarget::$marker
417                }
418            }
419
420            impl StaticTarget for $marker {
421                const TARGET: OrderTarget = OrderTarget::$marker;
422            }
423        )*
424    };
425}
426
427/// The fixed-width markers: every one but `Text` and `Bytes`.
428macro_rules! fixed_width {
429    ($($marker:ident),* $(,)?) => {
430        $(impl FixedWidth for $marker {})*
431    };
432}
433
434fixed_width!(I16, U16, I32, U32, I64, U64, I128, U128, F64, Date, Timestamp, Decimal, Uuid);
435
436markers! {
437    /// [`OrderTarget::I16`]. The narrowest integer target: an 8-bit one
438    /// would reveal its values, as [`OrderTarget`] explains.
439    I16,
440    /// [`OrderTarget::U16`].
441    U16,
442    /// [`OrderTarget::I32`].
443    I32,
444    /// [`OrderTarget::U32`].
445    U32,
446    /// [`OrderTarget::I64`].
447    I64,
448    /// [`OrderTarget::U64`].
449    U64,
450    /// [`OrderTarget::I128`].
451    I128,
452    /// [`OrderTarget::U128`].
453    U128,
454    /// [`OrderTarget::F64`].
455    F64,
456    /// [`OrderTarget::Date`].
457    Date,
458    /// [`OrderTarget::Timestamp`].
459    Timestamp,
460    /// [`OrderTarget::Decimal`].
461    Decimal,
462    /// [`OrderTarget::Text`].
463    Text,
464    /// [`OrderTarget::Bytes`].
465    Bytes,
466    /// [`OrderTarget::Uuid`].
467    Uuid,
468}
469
470/// Seal the value types the tables below name, by value and by reference.
471macro_rules! sealed {
472    ($($ty:ty),* $(,)?) => {
473        $(
474            impl private::Sealed for $ty {}
475            impl private::Sealed for &$ty {}
476        )*
477    };
478}
479
480/// `FitsIn` rows: each target, then every type that always fits it, by
481/// value and by reference.
482macro_rules! fits {
483    ($($target:ident: $($ty:ty),*;)*) => {
484        $($(
485            impl FitsIn<$target> for $ty {}
486            impl FitsIn<$target> for &$ty {}
487        )*)*
488    };
489}
490
491/// `Orderable` rows: a type and the target it is, by value and by
492/// reference.
493macro_rules! own {
494    ($($ty:ty => $target:ident),* $(,)?) => {
495        $(
496            impl Orderable for $ty {
497                type Target = $target;
498            }
499            impl Orderable for &$ty {
500                type Target = $target;
501            }
502        )*
503    };
504}
505
506sealed!(
507    i8,
508    i16,
509    u16,
510    i32,
511    u32,
512    i64,
513    u64,
514    i128,
515    u128,
516    f32,
517    f64,
518    str,
519    String,
520    [u8],
521    Vec<u8>,
522);
523
524impl private::Sealed for RawBytes<'_> {}
525impl private::Sealed for &RawBytes<'_> {}
526impl<const N: usize> private::Sealed for [u8; N] {}
527impl<const N: usize> private::Sealed for &[u8; N] {}
528
529// An integer target takes every integer type whose whole range it holds:
530// a signed target holds a narrower type of either sign, an unsigned
531// target only a narrower unsigned one. There is no `u8` row: a `u8` is
532// not a scalar of the data model (a `Vec<u8>` is bytes), so it has no
533// `Encrypt` impl to fit with.
534fits! {
535    I16: i8, i16;
536    U16: u16;
537    I32: i8, i16, i32, u16;
538    U32: u16, u32;
539    I64: i8, i16, i32, i64, u16, u32;
540    U64: u16, u32, u64;
541    I128: i8, i16, i32, i64, i128, u16, u32, u64;
542    U128: u16, u32, u64, u128;
543    F64: f32, f64;
544    Bytes: Vec<u8>;
545}
546
547impl FitsIn<Bytes> for &[u8] {}
548impl FitsIn<Bytes> for RawBytes<'_> {}
549impl FitsIn<Bytes> for &RawBytes<'_> {}
550impl<const N: usize> FitsIn<Bytes> for [u8; N] {}
551impl<const N: usize> FitsIn<Bytes> for &[u8; N] {}
552
553own! {
554    i16 => I16,
555    u16 => U16,
556    i32 => I32,
557    u32 => U32,
558    i64 => I64,
559    u64 => U64,
560    i128 => I128,
561    u128 => U128,
562    f32 => F64,
563    f64 => F64,
564    String => Text,
565}
566
567impl Orderable for &str {
568    type Target = Text;
569}
570
571// The typed values callers hold. Each is inside the range its encoding
572// takes for every value the type can hold: jiff's dates are the range
573// `Logical::Date` admits, a `Timestamp` is always inside the wire's range,
574// and a `rust_decimal::Decimal` has a 96-bit
575// mantissa and a scale of at most 28, which is what the decimal encoding
576// takes. A `jiff::Timestamp` may be one jiff 1.0.0 makes before its own
577// minimum (see `vitaminc_aead::OutOfRange`), which has no count, so it is
578// checked, not fitting.
579#[cfg(feature = "jiff")]
580#[cfg_attr(docsrs, doc(cfg(feature = "jiff")))]
581mod jiff_rows {
582    use super::*;
583    use jiff::civil::Date as CivilDate;
584    use vitaminc_aead::{Date as Day, Timestamp as Instant};
585
586    impl private::Sealed for CivilDate {}
587    impl private::Sealed for &CivilDate {}
588    impl private::Sealed for jiff::Timestamp {}
589    impl private::Sealed for &jiff::Timestamp {}
590    impl private::Sealed for Instant {}
591    impl private::Sealed for &Instant {}
592    impl private::Sealed for Day {}
593    impl private::Sealed for &Day {}
594
595    impl FitsIn<Date> for CivilDate {}
596    impl FitsIn<Date> for &CivilDate {}
597    impl FitsIn<Date> for Day {}
598    impl FitsIn<Date> for &Day {}
599    impl FitsIn<Timestamp> for Instant {}
600    impl FitsIn<Timestamp> for &Instant {}
601
602    impl Orderable for CivilDate {
603        type Target = Date;
604    }
605    impl Orderable for &CivilDate {
606        type Target = Date;
607    }
608    impl Orderable for jiff::Timestamp {
609        type Target = Timestamp;
610    }
611    impl Orderable for &jiff::Timestamp {
612        type Target = Timestamp;
613    }
614    impl Orderable for Instant {
615        type Target = Timestamp;
616    }
617    impl Orderable for &Instant {
618        type Target = Timestamp;
619    }
620    impl Orderable for Day {
621        type Target = Date;
622    }
623    impl Orderable for &Day {
624        type Target = Date;
625    }
626}
627
628#[cfg(feature = "rust_decimal")]
629#[cfg_attr(docsrs, doc(cfg(feature = "rust_decimal")))]
630mod decimal_rows {
631    use super::*;
632
633    impl private::Sealed for rust_decimal::Decimal {}
634    impl private::Sealed for &rust_decimal::Decimal {}
635    impl FitsIn<Decimal> for rust_decimal::Decimal {}
636    impl FitsIn<Decimal> for &rust_decimal::Decimal {}
637    impl Orderable for rust_decimal::Decimal {
638        type Target = Decimal;
639    }
640    impl Orderable for &rust_decimal::Decimal {
641        type Target = Decimal;
642    }
643
644    impl private::Sealed for vitaminc_aead::Decimal {}
645    impl private::Sealed for &vitaminc_aead::Decimal {}
646    impl FitsIn<Decimal> for vitaminc_aead::Decimal {}
647    impl FitsIn<Decimal> for &vitaminc_aead::Decimal {}
648    impl Orderable for vitaminc_aead::Decimal {
649        type Target = Decimal;
650    }
651    impl Orderable for &vitaminc_aead::Decimal {
652        type Target = Decimal;
653    }
654}
655
656#[cfg(feature = "uuid")]
657#[cfg_attr(docsrs, doc(cfg(feature = "uuid")))]
658mod uuid_rows {
659    use super::*;
660
661    impl private::Sealed for uuid::Uuid {}
662    impl private::Sealed for &uuid::Uuid {}
663    impl FitsIn<Uuid> for uuid::Uuid {}
664    impl FitsIn<Uuid> for &uuid::Uuid {}
665    impl Orderable for uuid::Uuid {
666        type Target = Uuid;
667    }
668    impl Orderable for &uuid::Uuid {
669        type Target = Uuid;
670    }
671
672    impl private::Sealed for vitaminc_aead::Uuid {}
673    impl private::Sealed for &vitaminc_aead::Uuid {}
674    impl FitsIn<Uuid> for vitaminc_aead::Uuid {}
675    impl FitsIn<Uuid> for &vitaminc_aead::Uuid {}
676    impl Orderable for vitaminc_aead::Uuid {
677        type Target = Uuid;
678    }
679    impl Orderable for &vitaminc_aead::Uuid {
680        type Target = Uuid;
681    }
682}
683
684#[cfg(test)]
685mod tests {
686    use super::*;
687
688    #[test]
689    fn every_marker_stands_for_its_target_and_every_target_is_itself() {
690        fn check<T: StaticTarget>(expected: OrderTarget) {
691            assert_eq!(T::TARGET, expected);
692            assert_eq!(T::default().runtime(), expected);
693        }
694        check::<I16>(OrderTarget::I16);
695        check::<U16>(OrderTarget::U16);
696        check::<I32>(OrderTarget::I32);
697        check::<U32>(OrderTarget::U32);
698        check::<I64>(OrderTarget::I64);
699        check::<U64>(OrderTarget::U64);
700        check::<I128>(OrderTarget::I128);
701        check::<U128>(OrderTarget::U128);
702        check::<F64>(OrderTarget::F64);
703        check::<Date>(OrderTarget::Date);
704        check::<Timestamp>(OrderTarget::Timestamp);
705        check::<Decimal>(OrderTarget::Decimal);
706        check::<Text>(OrderTarget::Text);
707        check::<Bytes>(OrderTarget::Bytes);
708        check::<Uuid>(OrderTarget::Uuid);
709        for target in OrderTarget::ALL {
710            assert_eq!(target.runtime(), *target);
711        }
712    }
713
714    /// A four-byte scheme, the shape of block ORE at one width.
715    struct Four;
716
717    impl OrderScheme for Four {
718        const NAME: &'static str = "four";
719        type Term = Vec<u8>;
720        type Error = core::convert::Infallible;
721        type Space = ();
722
723        fn open(
724            &self,
725            _: OrderTarget,
726            _: &vitaminc_context::Context<'_>,
727        ) -> Result<(), Self::Error> {
728            Ok(())
729        }
730
731        fn encrypt_plaintext(
732            &self,
733            _: &(),
734            _: &crate::OrderPlaintext,
735        ) -> Result<Vec<u8>, Self::Error> {
736            Ok(vec![0])
737        }
738
739        fn compare(a: &Vec<u8>, b: &Vec<u8>) -> Option<core::cmp::Ordering> {
740            Some(a.cmp(b))
741        }
742    }
743
744    crate::supports_targets!(Four; I32, U32, Date);
745
746    #[test]
747    fn a_scheme_takes_a_target_with_a_null_policy_exactly_when_it_takes_the_target() {
748        fn marker<P: NullPolicy>(order: NullOrder) {
749            assert!(
750                <Four as Supports<Nulls<I32, P>>>::supports(Nulls::new(I32)),
751                "{order:?}: a marker the scheme takes"
752            );
753            let placed = Nulls::<Date, P>::new(Date);
754            assert_eq!(placed.target(), Date);
755            assert_eq!(placed.null_order(), order);
756            assert_eq!(placed.runtime(), OrderTarget::Date);
757            assert_eq!(Target::null_order(placed), Some(order));
758        }
759        marker::<First>(NullOrder::First);
760        marker::<Last>(NullOrder::Last);
761        for order in [NullOrder::First, NullOrder::Last] {
762            assert!(
763                <Four as Supports<RuntimeNulls>>::supports(RuntimeNulls::new(
764                    OrderTarget::Date,
765                    order
766                )),
767                "{order:?}: a runtime target the scheme takes"
768            );
769            assert!(
770                !<Four as Supports<RuntimeNulls>>::supports(RuntimeNulls::new(
771                    OrderTarget::I64,
772                    order
773                )),
774                "{order:?}: a runtime target the scheme does not take"
775            );
776            let placed = RuntimeNulls::new(OrderTarget::Date, order);
777            assert_eq!(placed.target(), OrderTarget::Date);
778            assert_eq!(placed.null_order(), order);
779            assert_eq!(placed.runtime(), OrderTarget::Date);
780            assert_eq!(Target::null_order(placed), Some(order));
781        }
782        assert_eq!(I32.null_order(), None, "a marker places no nulls");
783        assert_eq!(
784            OrderTarget::I32.null_order(),
785            None,
786            "nor does a runtime target"
787        );
788    }
789
790    /// Four bytes again, with a hand-written marker answer that refuses
791    /// `U32`, so the policy impls can be seen to ask the target's answer
792    /// rather than assume one.
793    struct Refusing;
794
795    impl OrderScheme for Refusing {
796        const NAME: &'static str = "refusing";
797        type Term = Vec<u8>;
798        type Error = core::convert::Infallible;
799        type Space = ();
800
801        fn open(
802            &self,
803            _: OrderTarget,
804            _: &vitaminc_context::Context<'_>,
805        ) -> Result<(), Self::Error> {
806            Ok(())
807        }
808
809        fn encrypt_plaintext(
810            &self,
811            _: &(),
812            _: &crate::OrderPlaintext,
813        ) -> Result<Vec<u8>, Self::Error> {
814            Ok(vec![0])
815        }
816
817        fn compare(a: &Vec<u8>, b: &Vec<u8>) -> Option<core::cmp::Ordering> {
818            Some(a.cmp(b))
819        }
820    }
821
822    impl Supports<OrderTarget> for Refusing {
823        fn supports(_: OrderTarget) -> bool {
824            false
825        }
826    }
827
828    impl Supports<U32> for Refusing {
829        fn supports(_: U32) -> bool {
830            false
831        }
832    }
833
834    #[test]
835    fn a_policy_target_takes_the_answer_of_the_target_it_is_set_on() {
836        fn marker<P: NullPolicy>() {
837            assert!(
838                !<Refusing as Supports<Nulls<U32, P>>>::supports(Nulls::new(U32)),
839                "{:?}: a marker the scheme refuses stays refused under a policy",
840                P::ORDER
841            );
842        }
843        marker::<First>();
844        marker::<Last>();
845    }
846
847    #[test]
848    fn each_policy_marker_stands_for_its_null_order() {
849        assert_eq!(First::ORDER, NullOrder::First);
850        assert_eq!(Last::ORDER, NullOrder::Last);
851    }
852}