toasty-core 0.2.0

Core types, schema representations, and driver interface for Toasty
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
use crate::{
    schema::{
        app::{Field, FieldId},
        db::ColumnId,
    },
    stmt::{Expr, Value},
};

use indexmap::Equivalent;
use std::{
    borrow::Borrow,
    cmp::Ordering,
    fmt,
    hash::{Hash, Hasher},
    ops,
};

/// A sequence of field indices describing how to navigate into a nested
/// value.
///
/// A `Projection` can be:
/// - **Identity** (empty) -- refers to the base value itself
/// - **Single-step** -- indexes one level deep (e.g., field 2 of a record)
/// - **Multi-step** -- indexes through multiple levels (e.g., field 1, then
///   field 0 of the nested record)
///
/// Dereferences to `[usize]`, so slice operations work directly.
///
/// # Examples
///
/// ```
/// use toasty_core::stmt::Projection;
///
/// let p = Projection::single(3);
/// assert_eq!(p.as_slice(), &[3_usize]);
///
/// let p = Projection::identity();
/// assert!(p.is_identity());
/// assert!(p.as_slice().is_empty());
/// ```
#[derive(Clone, PartialEq, Eq)]
pub struct Projection {
    steps: Steps,
}

impl PartialOrd for Projection {
    fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
        Some(self.cmp(other))
    }
}

impl Ord for Projection {
    fn cmp(&self, other: &Self) -> Ordering {
        self.as_slice().cmp(other.as_slice())
    }
}

/// Trait for types that can be projected through a [`Projection`].
///
/// Returns the projected expression, or `None` if the projection is not
/// applicable.
pub trait Project {
    /// Applies the projection and returns the resulting expression.
    fn project(self, projection: &Projection) -> Option<Expr>;
}

#[derive(Debug, Clone, PartialEq, Eq)]
enum Steps {
    /// References the projection base
    Identity,

    /// One field step
    Single([usize; 1]),

    /// Multi field steps
    Multi(Vec<usize>),
}

// Custom Hash implementation to ensure compatibility with Equivalent trait:
// - Single-step projections hash like their contained usize: hash(Projection([1])) == hash(1)
// - Multi-step projections hash like their slice: hash(Projection([1,2])) == hash([1,2])
// This allows IndexMap lookups with both usize and [usize] to work correctly.
impl Hash for Projection {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.steps.hash(state);
    }
}

impl Hash for Steps {
    fn hash<H: Hasher>(&self, state: &mut H) {
        match self {
            Steps::Identity => {
                // Hash a discriminant for identity
                0u8.hash(state);
            }
            Steps::Single([index]) => {
                // Hash as a single usize (no length prefix, no array wrapping)
                // This makes hash(Projection([i])) == hash(i)
                index.hash(state);
            }
            Steps::Multi(indices) => {
                // Hash as a slice: this includes length and elements
                // This makes hash(Projection([i,j])) == hash([i,j])
                indices.as_slice().hash(state);
            }
        }
    }
}

/// An iterator over the steps of a [`Projection`].
pub struct Iter<'a>(std::slice::Iter<'a, usize>);

impl Projection {
    /// Creates an identity projection (zero steps, refers to the base itself).
    pub const fn identity() -> Self {
        Self {
            steps: Steps::Identity,
        }
    }

    /// Returns `true` if this is an identity projection (no steps).
    pub const fn is_identity(&self) -> bool {
        matches!(self.steps, Steps::Identity)
    }

    /// Creates a single-step projection indexing one field.
    pub fn single(step: usize) -> Self {
        Self {
            steps: Steps::Single([step]),
        }
    }

    /// Mostly here for `const`
    pub const fn from_index(index: usize) -> Self {
        Self {
            steps: Steps::Single([index]),
        }
    }

    /// Returns the projection steps as a slice.
    pub fn as_slice(&self) -> &[usize] {
        self.steps.as_slice()
    }

    /// Appends a step to this projection.
    pub fn push(&mut self, step: usize) {
        match &mut self.steps {
            Steps::Identity => {
                self.steps = Steps::Single([step]);
            }
            Steps::Single([first]) => {
                self.steps = Steps::Multi(vec![*first, step]);
            }
            Steps::Multi(steps) => {
                steps.push(step);
            }
        }
    }

    /// Returns `true` if this projection is equal to `other`.
    pub fn resolves_to(&self, other: impl Into<Self>) -> bool {
        let other = other.into();
        *self == other
    }
}

impl AsRef<[usize]> for Projection {
    fn as_ref(&self) -> &[usize] {
        self.as_slice()
    }
}

impl ops::Deref for Projection {
    type Target = [usize];

    fn deref(&self) -> &Self::Target {
        self.steps.as_slice()
    }
}

impl ops::DerefMut for Projection {
    fn deref_mut(&mut self) -> &mut Self::Target {
        match &mut self.steps {
            Steps::Identity => &mut [],
            Steps::Single(step) => &mut step[..],
            Steps::Multi(steps) => &mut steps[..],
        }
    }
}

impl<'a> IntoIterator for &'a Projection {
    type Item = usize;
    type IntoIter = Iter<'a>;

    fn into_iter(self) -> Self::IntoIter {
        Iter(self[..].iter())
    }
}

impl From<&Field> for Projection {
    fn from(value: &Field) -> Self {
        Self::single(value.id.index)
    }
}

impl From<FieldId> for Projection {
    fn from(value: FieldId) -> Self {
        Self::single(value.index)
    }
}

impl From<ColumnId> for Projection {
    fn from(value: ColumnId) -> Self {
        Self::single(value.index)
    }
}

impl From<usize> for Projection {
    fn from(value: usize) -> Self {
        Self::single(value)
    }
}

impl From<&[usize]> for Projection {
    fn from(value: &[usize]) -> Self {
        match value {
            [] => Self::identity(),
            [value] => Self::single(*value),
            value => Self {
                steps: Steps::Multi(value.into()),
            },
        }
    }
}

impl<const N: usize> From<[usize; N]> for Projection {
    fn from(value: [usize; N]) -> Self {
        Self::from(&value[..])
    }
}

impl fmt::Debug for Projection {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut f = f.debug_tuple("Projection");

        if self.is_identity() {
            f.field(&"identity");
        } else {
            for field in &self[..] {
                f.field(&field);
            }
        }

        f.finish()
    }
}

impl Steps {
    fn as_slice(&self) -> &[usize] {
        match self {
            Self::Identity => &[],
            Self::Single(step) => &step[..],
            Self::Multi(steps) => &steps[..],
        }
    }
}

impl Iterator for Iter<'_> {
    type Item = usize;

    fn next(&mut self) -> Option<usize> {
        self.0.next().copied()
    }
}

impl Project for Expr {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection)?.to_expr())
    }
}

impl Project for &Expr {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection)?.to_expr())
    }
}

impl Project for &&Expr {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection)?.to_expr())
    }
}

impl Project for Value {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection).to_expr())
    }
}

impl Project for &Value {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection).to_expr())
    }
}

impl Project for &&Value {
    fn project(self, projection: &Projection) -> Option<Expr> {
        Some(self.entry(projection).to_expr())
    }
}

// Borrow implementations for BTreeMap lookups
impl Borrow<[usize]> for Projection {
    fn borrow(&self) -> &[usize] {
        self.as_slice()
    }
}

// Allow using usize directly where Projection is expected (for single-step projections)
impl Equivalent<Projection> for usize {
    fn equivalent(&self, key: &Projection) -> bool {
        matches!(key.as_slice(), [index] if *index == *self)
    }
}

// Allow using &Projection where Projection is expected
impl Equivalent<Projection> for &Projection {
    fn equivalent(&self, key: &Projection) -> bool {
        *self == key
    }
}

// Note: `Equivalent<Projection> for [usize]` is provided automatically by
// the blanket impl in `equivalent` crate because `Projection: Borrow<[usize]>`.

// PartialEq implementations for ergonomic comparisons
impl PartialEq<usize> for Projection {
    fn eq(&self, other: &usize) -> bool {
        matches!(self.as_slice(), [index] if *index == *other)
    }
}

impl PartialEq<Projection> for usize {
    fn eq(&self, other: &Projection) -> bool {
        other == self
    }
}

impl PartialEq<[usize]> for Projection {
    fn eq(&self, other: &[usize]) -> bool {
        self.as_slice() == other
    }
}

impl PartialEq<Projection> for [usize] {
    fn eq(&self, other: &Projection) -> bool {
        other == self
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_projection_eq_usize() {
        let proj_single = Projection::from(5);
        let proj_multi = Projection::from([1, 2]);

        // Single-step projection == usize (both directions)
        assert_eq!(proj_single, 5);
        assert_eq!(5, proj_single);
        assert_ne!(proj_single, 3);
        assert_ne!(3, proj_single);

        // Multi-step projection != usize
        assert_ne!(proj_multi, 1);
        assert_ne!(1, proj_multi);
    }

    #[test]
    fn test_projection_eq_slice() {
        let proj_single = Projection::from(5);
        let proj_multi = Projection::from([1, 2, 3]);

        // Projection == [usize] slice (both directions)
        assert_eq!(proj_single, [5][..]);
        assert_eq!([5][..], proj_single);
        assert_eq!(proj_multi, [1, 2, 3][..]);
        assert_eq!([1, 2, 3][..], proj_multi);

        // Mismatches
        assert_ne!(proj_single, [1, 2][..]);
        assert_ne!([1, 2][..], proj_single);
    }

    #[test]
    fn test_projection_hash_compatibility() {
        use std::collections::hash_map::DefaultHasher;
        use std::hash::{Hash, Hasher};

        fn hash<T: Hash + ?Sized>(value: &T) -> u64 {
            let mut hasher = DefaultHasher::new();
            value.hash(&mut hasher);
            hasher.finish()
        }

        // Single-step projection should hash like the contained usize
        let proj_single = Projection::from(42);
        assert_eq!(hash(&proj_single), hash(&42_usize));

        // Multi-step projection should hash like the slice
        let proj_multi = Projection::from([1, 2, 3]);
        let slice: &[usize] = &[1, 2, 3];
        assert_eq!(hash(&proj_multi), hash(slice));

        // Verify this works with IndexMap
        use indexmap::IndexMap;
        let mut map = IndexMap::new();
        map.insert(Projection::from(5), "value");

        // Can look up with usize
        assert_eq!(map.get(&5_usize), Some(&"value"));

        // Can look up with single-element slice
        let slice_single: &[usize] = &[5];
        assert_eq!(map.get(slice_single), Some(&"value"));

        // Multi-step example
        map.insert(Projection::from([1, 2]), "multi");

        // Can look up with multi-element slice
        let slice_multi: &[usize] = &[1, 2];
        assert_eq!(map.get(slice_multi), Some(&"multi"));
    }
}