passdata 0.0.2

Authentication and authorization data in a logic programming language.
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
#[cfg(all(feature = "alloc", not(feature = "std")))]
use alloc::{borrow::Cow, string::String, vec::Vec};
use core::{
    convert::Infallible,
    fmt::{self, Display},
};
#[cfg(feature = "std")]
use std::{borrow::Cow, error, string::String, vec::Vec};

use generic_array::{ArrayLength, GenericArray};
use typenum::U1;

use crate::{
    values::{self, InvalidType},
    ConstantTy,
};

macro_rules! count_ident {
    ($i0:ident) => {1};
    ($i0:ident, $($I:ident),*) => {1 + count_ident!($($I),*)};
}

macro_rules! count_ident_typenum {
    ($i0:ident) => {U1};
    ($i0:ident, $($I:ident),*) => {<U1 as core::ops::Add<count_ident_typenum!($($I),*)>>::Output};
}

macro_rules! ignore_ident {
    ($id:ident, $($t:tt)*) => {
        $($t)*
    };
}

/// Converts data into an array.
pub trait IntoArray<T>: Sized {
    /// Length of the generic array.
    type Length: ArrayLength<T>;

    /// Converts `self` into an array.
    fn into_array(self) -> GenericArray<T, Self::Length>;
}

macro_rules! impl_into_array_single_ty {
    ($i0:ty) => {
        impl<'a> IntoArray<values::Constant<'a>> for $i0
        {
            type Length = U1;

            fn into_array(self) -> GenericArray<values::Constant<'a>, Self::Length> {
                [values::Constant::from(self)].into()
            }
        }
    };
    ($i0:ty, $($I:ty),+) => {
      impl_into_array_single_ty!($i0);

      impl_into_array_single_ty!($($I),+);
    };
}

impl_into_array_single_ty!(bool, i64, &'a str, &'a [u8]);

macro_rules! impl_into_array_tuple {
    ($i0:ident) => {};
    ($i0:ident, $($I:ident),+) => {
        impl_into_array_tuple!($($I),+);

        impl<T, $($I),+> IntoArray<T> for ($($I,)+)
            where $(T: From<$I>,)+
        {
            type Length = count_ident_typenum!($($I),+);

            fn into_array(self) -> GenericArray<T, Self::Length> {
                #[allow(non_snake_case)]
                let ($($I,)+) = self;

                [$(T::from($I)),+].into()
            }
        }

        impl<T, S> IntoArray<S> for [T; { count_ident!($($I),+) }]
            where S: From<T>,
        {
            type Length = count_ident_typenum!($($I),+);

            fn into_array(self) -> GenericArray<S, Self::Length>  {
                #[allow(non_snake_case)]
                let [$($I,)+] = self;

                [$(S::from($I)),+].into()
            }
        }
    };
}

impl_into_array_tuple!(dummy, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);

/// Expected value used in a query.
pub trait QueryValue {
    /// The expected type to match.
    type Ty<'a>: TryFrom<values::Constant<'a>>;

    fn ty() -> ConstantTy;

    /// Determines if the found value matches the expected value.
    fn is_match(&self, other: &Self::Ty<'_>) -> bool;
}

impl QueryValue for bool {
    type Ty<'a> = bool;

    fn ty() -> ConstantTy {
        ConstantTy::Bool
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        *self == *other
    }
}

/// Any boolean value.
#[derive(Debug, Clone, Copy)]
pub struct AnyBool;

impl QueryValue for AnyBool {
    type Ty<'a> = bool;

    fn ty() -> ConstantTy {
        ConstantTy::Bool
    }

    fn is_match(&self, _other: &Self::Ty<'_>) -> bool {
        true
    }
}

impl QueryValue for i64 {
    type Ty<'a> = i64;

    fn ty() -> ConstantTy {
        ConstantTy::Num
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        *self == *other
    }
}

/// Any number value.
#[derive(Debug, Clone, Copy)]
pub struct AnyNum;

impl QueryValue for AnyNum {
    type Ty<'a> = i64;

    fn ty() -> ConstantTy {
        ConstantTy::Num
    }

    fn is_match(&self, _other: &Self::Ty<'_>) -> bool {
        true
    }
}

impl<'b> QueryValue for &'b str {
    type Ty<'a> = &'a str;

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        self == other
    }
}

impl QueryValue for String {
    type Ty<'a> = &'a str;

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        self == *other
    }
}

impl<'b> QueryValue for Cow<'b, str> {
    type Ty<'a> = &'a str;

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        self == *other
    }
}

impl<'b> QueryValue for &'b [u8] {
    type Ty<'a> = &'a [u8];

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        self == other
    }
}

impl QueryValue for Vec<u8> {
    type Ty<'a> = &'a [u8];

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        self == other
    }
}

impl<'b> QueryValue for Cow<'b, [u8]> {
    type Ty<'a> = &'a [u8];

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, other: &Self::Ty<'_>) -> bool {
        *self == *other
    }
}

/// Any string value.
#[derive(Debug, Clone, Copy)]
pub struct AnyStr;

impl QueryValue for AnyStr {
    type Ty<'a> = &'a str;

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, _other: &Self::Ty<'_>) -> bool {
        true
    }
}

/// Any string value.
#[derive(Debug, Clone, Copy)]
pub struct AnyBytes;

impl QueryValue for AnyBytes {
    type Ty<'a> = &'a [u8];

    fn ty() -> ConstantTy {
        ConstantTy::Bytes
    }

    fn is_match(&self, _other: &Self::Ty<'_>) -> bool {
        true
    }
}

/// Any constant value.
#[derive(Debug, Clone, Copy)]
pub struct AnyConstant;

impl QueryValue for AnyConstant {
    type Ty<'a> = crate::values::Constant<'a>;

    fn ty() -> ConstantTy {
        ConstantTy::Unknown
    }

    fn is_match(&self, _other: &Self::Ty<'_>) -> bool {
        true
    }
}

/// Errors in converting to a tuple.
#[derive(Clone, Copy, PartialEq)]
pub enum QueryResultError {
    /// Missing an element for the tuple
    MissingElement,
    /// Invalid arity
    InvalidLength,
    /// Invalid type for element
    InvalidType,
}

#[cfg(feature = "std")]
impl error::Error for QueryResultError {
    fn source(&self) -> Option<&(dyn error::Error + 'static)> {
        None
    }
}

impl Display for QueryResultError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingElement => f.write_str("missing element"),
            Self::InvalidLength => f.write_str("invalid length"),
            Self::InvalidType => f.write_str("invalid element type"),
        }
    }
}

impl fmt::Debug for QueryResultError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            Self::MissingElement => f.write_str("missing element"),
            Self::InvalidLength => f.write_str("invalid length"),
            Self::InvalidType => f.write_str("invalid element type"),
        }
    }
}

impl From<InvalidType> for QueryResultError {
    fn from(_value: InvalidType) -> Self {
        Self::InvalidType
    }
}

impl From<Infallible> for QueryResultError {
    fn from(_: Infallible) -> Self {
        unreachable!()
    }
}

/// Converts data into a query result.
pub trait QueryResult<'a>
where
    Self: Sized,
{
    /// Length of a `lang::Constant` generic array.
    type Length: ArrayLength<values::Constant<'a>> + ArrayLength<ConstantTy>;

    /// Result type.
    type ResultTy;

    fn tys() -> GenericArray<ConstantTy, Self::Length>;

    /// If the given values matches the expected values.
    fn is_match(&self, other: &Self::ResultTy) -> bool;

    /// Converts values into a tuple.
    ///
    /// # Errors
    ///
    /// If the given `GenericArray` is not the correct length, is missing an
    /// element, or cannot convert a type.
    fn into_tuple(
        values: GenericArray<values::Constant<'a>, Self::Length>,
    ) -> Result<Self::ResultTy, QueryResultError>;
}

impl<'a, T, E> QueryResult<'a> for T
where
    T::Ty<'a>: TryFrom<values::Constant<'a>, Error = E>,
    T: QueryValue,
    QueryResultError: From<E>,
{
    type Length = U1;

    type ResultTy = T::Ty<'a>;

    fn tys() -> GenericArray<ConstantTy, Self::Length> {
        generic_array::arr![ConstantTy; T::ty()]
    }

    fn is_match(&self, other: &Self::ResultTy) -> bool {
        self.is_match(other)
    }

    fn into_tuple(
        values: GenericArray<values::Constant<'a>, Self::Length>,
    ) -> Result<Self::ResultTy, QueryResultError> {
        let mut iter = values.into_iter();

        let t = <T::Ty<'a>>::try_from(iter.next().ok_or(QueryResultError::MissingElement)?)?;

        if iter.next().is_some() {
            return Err(QueryResultError::InvalidLength);
        }

        Ok(t)
    }
}

macro_rules! impl_query_result {
    ($i0:ident) => {};
    ($i0:ident, $($I:ident),+) => {
        impl_query_result!($($I),+);

        paste::paste! {

        impl<'a, $($I),+, $([<E $I>]),+> QueryResult<'a> for ($($I,)+)
            where $($I::Ty<'a> : TryFrom<values::Constant<'a>, Error =  [<E $I>]>),+,
            $($I: QueryValue),+,
            $(QueryResultError: From<[<E $I>]>),+,
            Self: Sized
        {
            type Length = count_ident_typenum!($($I),+);

            type ResultTy = ($($I::Ty<'a>,)+);

            fn tys() -> GenericArray<ConstantTy, Self::Length> {
                generic_array::arr![ConstantTy; $($I::ty()),+]
            }

            fn is_match(&self, other: &Self::ResultTy) -> bool {
                #[allow(non_snake_case)]
                let ($([<a_ $I>],)+) = self;
                #[allow(non_snake_case)]
                let ($([<b_ $I>],)+) = other;

                $(
                    if ![<a_ $I>].is_match([<b_ $I>]) {
                        return false;
                    }
                )+

                true
            }

            fn into_tuple(values: GenericArray<values::Constant<'a>, Self::Length>) -> Result<Self::ResultTy, QueryResultError> {
                let mut iter = values.into_iter();

                let t = (
                    $(
                        {
                            let ignore_ident!($I, a) = <$I::Ty<'a>>::try_from(iter.next().ok_or_else(|| QueryResultError::MissingElement)?)?;
                            a
                        }
                    ,)+
                );

                if iter.next().is_some() {
                    return Err(QueryResultError::InvalidLength);
                }

                Ok(t)
            }
        }

        }
    };
}

impl_query_result!(dummy, T0, T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12);