looking-glass 0.1.3

looking-glass is a reflection & type-erasure library for Rust
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
use crate::*;
pub use bytes::Bytes;
pub use smol_str::SmolStr;
use std::{collections::HashMap, fmt::Debug, hash::BuildHasher};

/// Any reflected type
pub trait Instance<'ty>: TypedObj + Send + Sync {
    /// Returns the name of a instance
    fn name(&self) -> SmolStr;

    fn as_inst(&self) -> &(dyn Instance<'ty> + 'ty);
}

impl<'ty> dyn Instance<'ty> + 'ty {
    /// Downcasts to a concere type
    #[inline]
    pub fn downcast_ref<'val, 't, T: Typed<'ty> + 'ty>(&'val self) -> Option<&'val T>
    where
        'ty: 'val,
    {
        if self.inst_ty() == T::ty() {
            // Safety: This is essentially a copy from `Any` and follows much the same logic.
            // The major difference is that we allow non-static casts.
            // The above check makes sure that the lifetime erased type T, and Self are the same.
            // However that does not ensure that the lifetimes match.
            // We ensure that saftey through the lifetime bounds. The lifetime bound `T: 'ty`
            // ensures that we only ever give out a lifetime that 'val (the lifetime of the parent struct) out lives.
            // Which is equivalent to a safe Rust cast (&'a () as &'b () where 'a: 'b).
            Some(unsafe { &*(self as *const dyn Instance<'ty> as *const T) })
        } else {
            None
        }
    }
}

/// A extension trait that provides downcasting
pub trait DowncastExt<'ty> {
    /// Downcasts to a boxed concrete type
    fn downcast<T: Typed<'ty> + 'ty>(self) -> Option<Box<T>>;
}
impl<'ty> DowncastExt<'ty> for Box<dyn Instance<'ty> + 'ty> {
    fn downcast<T: Typed<'ty> + 'ty>(self) -> Option<Box<T>> {
        if self.inst_ty() == T::ty() {
            unsafe {
                // Safety: This is also a copy from `Any`, and its lifetime saftey is guarenteed in
                // same way as [`Instance::downcast_ref`]
                let raw: *mut (dyn Instance<'ty> + 'ty) = Box::into_raw(self);
                Some(Box::from_raw(raw as *mut T))
            }
        } else {
            None
        }
    }
}

/// A reflected struct
pub trait StructInstance<'s>: Instance<'s> {
    /// Returns a reference to a field in a struct
    fn get_value<'a>(&'a self, field: &str) -> Option<CowValue<'a, 's>>
    where
        's: 'a;

    /// Updates an instance based on the instance passed in. If a field mask is specified only the fields passed with the mask will be updated.
    fn update<'a>(
        &'a mut self,
        update: &'a (dyn StructInstance<'s> + 's),
        field_mask: Option<&FieldMask>,
        replace_repeated: bool,
    ) -> Result<(), Error>;

    /// Returns a HashMap containing all the attributes of the instance.
    fn values<'a>(&'a self) -> HashMap<SmolStr, CowValue<'a, 's>>;

    /// Returns a clone of the instance in a [`Box`].
    fn boxed_clone(&self) -> Box<dyn StructInstance<'s> + 's>;

    /// Casts `Self` to a `Box<dyn Instance>`
    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's>;
}

impl<'s> std::fmt::Debug for dyn StructInstance<'s> + 's {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut builder = f.debug_struct(&self.name());
        for (name, val) in self.values() {
            builder.field(&name, &val);
        }
        builder.finish()
    }
}

impl<'s> PartialEq for dyn StructInstance<'s> + 's {
    fn eq(&self, other: &Self) -> bool {
        self.values() == other.values()
    }
}

impl<'s> Clone for Box<dyn StructInstance<'s> + 's> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

/// A reflected enum
pub trait EnumInstance<'s>: Instance<'s> {
    /// Returns a clone of the instance in a [`Box`].
    fn boxed_clone(&self) -> Box<dyn EnumInstance<'s> + 's>;
    /// Returns the current value of the reflected enum.
    fn field<'a>(&'a self) -> EnumField<'a, 's>
    where
        's: 'a;

    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s>>;
}

/// A reflected field of an enum
#[derive(PartialEq, Clone, Debug)]
pub enum EnumField<'a, 's> {
    Unit(SmolStr),
    Tuple {
        name: SmolStr,
        fields: Vec<CowValue<'a, 's>>,
    },
    Struct {
        name: SmolStr,
        fields: HashMap<SmolStr, CowValue<'a, 's>>,
    },
}

impl<'s> PartialEq for dyn EnumInstance<'s> + 's {
    fn eq(&self, other: &Self) -> bool {
        self.field() == other.field()
    }
}

impl<'s> std::fmt::Debug for dyn EnumInstance<'s> + 's {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self.field() {
            EnumField::Unit(name) => f.write_str(name.as_str()),
            EnumField::Tuple { name, fields } => {
                let mut tuple = f.debug_tuple(name.as_str());
                for field in fields {
                    tuple.field(&field);
                }
                tuple.finish()
            }
            EnumField::Struct { name, fields } => {
                let mut s = f.debug_struct(&name);
                for (name, field) in fields {
                    s.field(&name, &field);
                }
                s.finish()
            }
        }
    }
}

impl<'s> Clone for Box<dyn EnumInstance<'s> + 's> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

/// A reflected [`Vec`]
pub trait VecInstance<'s>: Instance<'s> + 's {
    /// Returns a reference to a field in a reflected vec
    fn get_value<'a>(&'a self, i: usize) -> Option<Value<'a, 's>>
    where
        's: 'a;

    /// Returns a Vec containing all the attributes of the instance.
    fn values<'a>(&'a self) -> Vec<CowValue<'a, 's>>
    where
        's: 'a;

    /// Returns a clone of the instance in a [`Box`].
    fn boxed_clone(&self) -> Box<dyn VecInstance<'s> + 's>;

    /// Updates an instance based on the instance passed in. If a field mask is specified only the fields passed with the mask will be updated.
    fn update<'a>(
        &'a mut self,
        update: &'a (dyn VecInstance<'s> + 's),
        replace_repeated: bool,
    ) -> Result<(), Error>;

    /// Returns whether the vec is empty
    fn is_empty(&self) -> bool;

    /// Returns whether the length of the vec;
    fn len(&self) -> usize;

    fn vec_eq(&self, inst: &(dyn VecInstance<'s> + 's)) -> bool;

    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's>;
}

impl<'s> std::fmt::Debug for dyn VecInstance<'s> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_list().entries(self.values().iter()).finish()
    }
}

impl<'s> PartialEq for dyn VecInstance<'s> + 's {
    fn eq(&self, other: &Self) -> bool {
        self.vec_eq(other)
    }
}

impl<'s> Clone for Box<dyn VecInstance<'s> + 's> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

/// A reflected [`HashMap`]
pub trait HashMapInstance<'s>: Instance<'s> + 's {
    fn get_value<'a>(&'a self, key: &str) -> Option<Value<'a, 's>>
    where
        's: 'a;

    fn is_empty(&self) -> bool;

    fn len(&self) -> usize;

    /// Returns a clone of the instance in a [`Box`].
    fn boxed_clone(&self) -> Box<dyn HashMapInstance<'s> + 's>;

    /// Updates an instance based on the instance passed in. If a field mask is specified only the fields passed with the mask will be updated.
    fn update<'a>(
        &'a mut self,
        update: &'a (dyn HashMapInstance<'s> + 's),
        field_mask: Option<&FieldMask>,
        replace_repeated: bool,
    ) -> Result<(), Error>;

    /// Returns a HashMap containing all the attributes of the instance.
    fn values<'a>(&'a self) -> HashMap<String, CowValue<'a, 's>>
    where
        's: 'a;

    fn hashmap_eq(&self, inst: &(dyn HashMapInstance<'s> + 's)) -> bool;

    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's>;
}

impl<'s> std::fmt::Debug for dyn HashMapInstance<'s> + 's {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut builder = f.debug_map();
        for (k, v) in self.values() {
            builder.entry(&k, &v);
        }
        builder.finish()
    }
}

impl<'s> PartialEq for dyn HashMapInstance<'s> + 's {
    fn eq(&self, other: &Self) -> bool {
        self.hashmap_eq(other)
    }
}

impl<'s> Clone for Box<dyn HashMapInstance<'s> + 's> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

/// A reflected [`Option`]
pub trait OptionInstance<'s>: Instance<'s> {
    /// Returns a reference to a field in a reflected vec
    fn value<'a>(&'a self) -> Option<Value<'a, 's>>
    where
        's: 'a;

    /// Returns a clone of the instance in a [`Box`].
    fn boxed_clone(&self) -> Box<dyn OptionInstance<'s> + 's>;

    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's>;
}

impl<'s> std::fmt::Debug for dyn OptionInstance<'s> + 's {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let mut build = f.debug_tuple(&self.name());
        if let Some(val) = self.value() {
            build.field(&val);
        }
        build.finish()
    }
}

impl<'s, T: Typed<'s> + Clone + 's> Typed<'s> for Option<T> {
    fn ty() -> ValueTy {
        ValueTy::Option(Box::new(T::ty()))
    }

    fn as_value<'a>(&'a self) -> Value<'a, 's>
    where
        's: 'a,
    {
        Value::from_option(self)
    }
}

impl<'s> PartialEq for dyn OptionInstance<'s> + 's {
    fn eq(&self, other: &Self) -> bool {
        self.value() == other.value()
    }
}

impl<'s> Clone for Box<dyn OptionInstance<'s> + 's> {
    fn clone(&self) -> Self {
        self.boxed_clone()
    }
}

impl<'a, T: Typed<'a> + Clone + PartialEq + 'a> Instance<'a> for Vec<T> {
    fn name(&self) -> SmolStr {
        format!("Vec<{:?}>", T::ty()).into()
    }

    fn as_inst(&self) -> &(dyn Instance<'a> + 'a) {
        self
    }
}

impl<'s, T: Typed<'s> + Clone + 's + PartialEq> VecInstance<'s> for Vec<T> {
    fn get_value<'a>(&'a self, i: usize) -> Option<Value<'a, 's>>
    where
        's: 'a,
    {
        let val = self.get(i)?.as_value();
        Some(val)
    }

    fn values<'a>(&'a self) -> Vec<CowValue<'a, 's>>
    where
        's: 'a,
    {
        self.iter().map(|e| CowValue::Ref(e.as_value())).collect()
    }

    fn boxed_clone(&self) -> Box<dyn VecInstance<'s> + 's> {
        Box::new(self.clone())
    }

    fn update<'a>(
        &'a mut self,
        update: &'a (dyn VecInstance<'s> + 's),
        replace_repeated: bool,
    ) -> Result<(), Error> {
        if let Some(vec) = Value::from_vec(update).borrow::<&Vec<T>>() {
            if replace_repeated {
                let vec = vec.clone();
                let _ = std::mem::replace(self as &mut Vec<T>, vec);
            } else {
                self.extend_from_slice(&vec[..]);
            }
        }
        Ok(())
    }

    fn is_empty(&self) -> bool {
        Vec::is_empty(self)
    }

    fn len(&self) -> usize {
        Vec::len(self)
    }

    fn vec_eq(&self, inst: &(dyn VecInstance<'s> + 's)) -> bool {
        inst.as_inst().downcast_ref::<Self>() == Some(self)
    }

    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's> {
        self
    }
}

impl<'s, T: Typed<'s> + Clone + 's + PartialEq> Typed<'s> for Vec<T> {
    fn ty() -> ValueTy {
        ValueTy::Vec(Box::new(T::ty()))
    }

    fn as_value<'a>(&'a self) -> Value<'a, 's>
    where
        's: 'a,
    {
        Value::from_vec(self)
    }
}

impl<'s, T> Instance<'s> for HashMap<String, T>
where
    T: Typed<'s> + Clone + 's + PartialEq,
{
    fn name(&self) -> SmolStr {
        format!("HashMap<String, {:?}>", T::ty()).into() 
    }

    fn as_inst(&self) -> &(dyn Instance<'s> + 's) {
        self
    }
}

impl<'s, T> HashMapInstance<'s> for HashMap<String, T>
where
    T: Typed<'s> + Clone + 's + PartialEq,
{
    fn get_value<'a>(&'a self, key: &str) -> Option<Value<'a, 's>>
    where
        's: 'a,
    {
        let val = self.get(key)?.as_value();
        Some(val)
    }

    fn update<'a>(
        &'a mut self,
        update: &'a (dyn HashMapInstance<'s> + 's),
        field_mask: Option<&FieldMask>,
        replace_repeated: bool,
    ) -> Result<(), Error> {
        if let Some(map) = Value::from_hashmap(update).borrow::<&HashMap<String, T>>() {
            match (replace_repeated, field_mask) {
                (true, None) => {
                    let _ = std::mem::replace(self as &mut HashMap<String, T>, map.clone());
                }
                (true, Some(mask)) => {
                    let masked_keys_to_remove: Vec<String> = self
                        .keys()
                        .filter(|k| {
                            let in_mask = mask.child(&SmolStr::new(k.as_str())).is_some();
                            let in_update = map.contains_key(k.as_str());
                            in_mask && !in_update
                        })
                        .cloned()
                        .collect();
                    for key in masked_keys_to_remove {
                        self.remove(&key);
                    }
                    for (key, value) in map.iter() {
                        if mask.child(&SmolStr::new(key.as_str())).is_some() {
                            self.insert(key.clone(), value.clone());
                        }
                    }
                }
                (false, None) => {
                    for (key, value) in map.iter() {
                        self.insert(key.clone(), value.clone());
                    }
                }
                (false, Some(mask)) => {
                    for (key, value) in map.iter() {
                        if mask.child(&SmolStr::new(key.as_str())).is_some() {
                            self.insert(key.clone(), value.clone());
                        }
                    }
                }
            }
        }
        Ok(())
    }

    fn values<'a>(&'a self) -> HashMap<String, CowValue<'a, 's>>
    where
        's: 'a,
    {
        self.iter()
            .map(|(k, v)| {
                let key_str = k.clone(); 
                let cow_val = CowValue::Ref(v.as_value());
                (key_str, cow_val)
            })
            .collect()
    }

    fn boxed_clone(&self) -> Box<dyn HashMapInstance<'s> + 's> {
        Box::new(self.clone())
    }

    fn is_empty(&self) -> bool {
        HashMap::is_empty(self)
    }

    fn len(&self) -> usize {
        HashMap::len(self)
    }

    fn hashmap_eq(&self, inst: &(dyn HashMapInstance<'s> + 's)) -> bool {
        inst.as_inst().downcast_ref::<Self>() == Some(self)
    }
        
    fn into_boxed_instance(self: Box<Self>) -> Box<dyn Instance<'s> + 's> {
        self
    }
}

impl<'s, T> Typed<'s> for HashMap<String, T>
where
    T: Typed<'s> + Clone + 's + PartialEq,
{
    fn ty() -> ValueTy {
        ValueTy::HashMap(Box::new(T::ty()))
    }

    fn as_value<'a>(&'a self) -> Value<'a, 's>
    where
        's: 'a,
    {
        Value::from_hashmap(self)
    }
}

impl<'s> Instance<'s> for String {
    fn name(&self) -> SmolStr {
        "String".into()
    }

    fn as_inst(&self) -> &(dyn Instance<'s> + 's) {
        self
    }
}

impl<'s> Instance<'s> for Bytes {
    fn name(&self) -> SmolStr {
        "Bytes".into()
    }

    fn as_inst(&self) -> &(dyn Instance<'s> + 's) {
        self
    }
}