typex 0.1.1

Runtime reflection: inspection, traversal, equality and mutation
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
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
use super::*;
use alloc::boxed::Box;
use alloc::collections::BTreeMap;
use alloc::string::String;
use alloc::vec::Vec;
use core::any::Any;

pub(super) fn move_item_by_remove_insert(
  value: &mut dyn SequenceAccessMut,
  from: usize,
  to: usize,
) -> Result<(), MoveItemError> {
  let len = value.len();
  if from >= len || to > len {
    return Err(MoveItemError::IndexOutOfBounds);
  }
  if from == to {
    return Ok(());
  }

  let item = value.remove_item(from).ok_or(MoveItemError::RemoveFailed)?;
  let insert_at = if from < to { to - 1 } else { to };
  match value.insert_item(insert_at, item) {
    Ok(_) => Ok(()),
    Err(item) => match value.insert_item(from, item) {
      Ok(_) => Err(MoveItemError::InsertFailed),
      Err(_) => Err(MoveItemError::RestoreFailed),
    },
  }
}

#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)]
pub(super) struct Number(pub(super) u16);

#[derive(Debug)]
pub(super) struct LyingType;

impl Meta for LyingType {
  fn type_info(&self) -> TypeInfo {
    TypeInfo::of::<Number>()
  }

  fn reflect(&self) -> Reflect<'_> {
    Reflect::Scalar
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl Meta for Number {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Scalar
  }

  fn eq_dyn(&self, other: &dyn Meta) -> bool {
    other.as_any().downcast_ref::<Number>() == Some(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl MetaMut for Number {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Opaque
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

#[derive(Clone, Debug, PartialEq)]
pub(super) struct Text(pub(super) &'static str);

impl Meta for Text {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Scalar
  }

  fn eq_dyn(&self, other: &dyn Meta) -> bool {
    other.as_any().downcast_ref::<Text>() == Some(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl MetaMut for Text {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Opaque
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

/// Manual [`Meta`]/[`MetaMut`] pair standing in for the structural derives.
/// `typex` cannot depend on its derive crate, so this gives field and item
/// mutation tests a concrete value to exercise.
#[derive(Clone, Debug, PartialEq)]
pub(super) struct Pair {
  pub(super) count: u16,
  pub(super) label: Text,
}

impl Meta for Pair {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Struct(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl StructAccess for Pair {
  fn field(&self, name: &str) -> Option<ObjectRef<'_>> {
    match name {
      "count" => Some(ObjectRef::new(&self.count)),
      "label" => Some(ObjectRef::new(&self.label)),
      _ => None,
    }
  }

  fn field_names(&self) -> &'static [&'static str] {
    &["count", "label"]
  }
}

impl MetaMut for Pair {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Struct(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl StructAccessMut for Pair {
  fn field_mut(&mut self, name: &str) -> Option<ObjectRefMut<'_>> {
    match name {
      "count" => Some(ObjectRefMut::new(&mut self.count)),
      "label" => Some(ObjectRefMut::new(&mut self.label)),
      _ => None,
    }
  }
}

/// Hand-written enum with named, tuple and unit variants. It keeps the default
/// `eq_dyn` and navigation methods, which derived enums partly override.
#[derive(Debug, PartialEq)]
pub(super) enum Shape {
  Circle { radius: u8 },
  Pair(u8, u8),
  Empty,
}

impl Meta for Shape {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Enum(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl EnumAccess for Shape {
  fn variant_name(&self) -> &'static str {
    match self {
      Self::Circle { .. } => "Circle",
      Self::Pair(..) => "Pair",
      Self::Empty => "Empty",
    }
  }

  fn fields(&self) -> VariantFields<'_> {
    match self {
      Self::Circle { .. } => VariantFields::Named(self),
      Self::Pair(..) => VariantFields::Positional(self),
      Self::Empty => VariantFields::Unit,
    }
  }
}

impl StructAccess for Shape {
  fn field(&self, name: &str) -> Option<ObjectRef<'_>> {
    match (self, name) {
      (Self::Circle { radius }, "radius") => Some(ObjectRef::new(radius)),
      _ => None,
    }
  }

  fn field_names(&self) -> &'static [&'static str] {
    match self {
      Self::Circle { .. } => &["radius"],
      _ => &[],
    }
  }
}

impl TupleAccess for Shape {
  fn item(&self, index: usize) -> Option<ObjectRef<'_>> {
    match (self, index) {
      (Self::Pair(first, _), 0) => Some(ObjectRef::new(first)),
      (Self::Pair(_, second), 1) => Some(ObjectRef::new(second)),
      _ => None,
    }
  }

  fn len(&self) -> usize {
    match self {
      Self::Pair(..) => 2,
      _ => 0,
    }
  }
}

impl MetaMut for Shape {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Enum(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl EnumAccessMut for Shape {
  fn fields_mut(&mut self) -> VariantFieldsMut<'_> {
    match self {
      Self::Circle { .. } => VariantFieldsMut::Named(self),
      Self::Pair(..) => VariantFieldsMut::Positional(self),
      Self::Empty => VariantFieldsMut::Unit,
    }
  }
}

impl StructAccessMut for Shape {
  fn field_mut(&mut self, name: &str) -> Option<ObjectRefMut<'_>> {
    match (self, name) {
      (Self::Circle { radius }, "radius") => Some(ObjectRefMut::new(radius)),
      _ => None,
    }
  }
}

impl TupleAccessMut for Shape {
  fn item_mut(&mut self, index: usize) -> Option<ObjectRefMut<'_>> {
    match (self, index) {
      (Self::Pair(first, _), 0) => Some(ObjectRefMut::new(first)),
      (Self::Pair(_, second), 1) => Some(ObjectRefMut::new(second)),
      _ => None,
    }
  }
}

/// Ordered list of `(key, value)` records where each key is unique. Items can
/// be looked up by index or by key, so the access kind is
/// [`AccessKind::KeyedItem`]. The value kind is [`ValueKind::Sequence`], so
/// item patches and positional mutation still apply.
#[derive(Debug, PartialEq)]
pub(super) struct KeyedSequence {
  pub(super) items: Vec<(String, Number)>,
}

impl KeyedSequence {
  fn position(&self, key: &str) -> Option<usize> {
    self.items.iter().position(|(item_key, _)| item_key == key)
  }
}

impl Meta for KeyedSequence {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::KeyedSequence(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl SequenceAccess for KeyedSequence {
  fn len(&self) -> usize {
    self.items.len()
  }

  fn item(&self, index: usize) -> Option<ObjectRef<'_>> {
    self.items.get(index).map(|value| ObjectRef::new(value))
  }
}

impl KeyedSequenceAccess for KeyedSequence {
  fn key(&self, key: &str) -> Option<ObjectRef<'_>> {
    self.item(self.position(key)?)
  }

  fn keys(&self) -> Vec<String> {
    self.items.iter().map(|(key, _)| key.clone()).collect()
  }
}

impl MetaMut for KeyedSequence {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::KeyedSequence(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl SequenceAccessMut for KeyedSequence {
  fn item_mut(&mut self, index: usize) -> Option<ObjectRefMut<'_>> {
    self
      .items
      .get_mut(index)
      .map(|value| ObjectRefMut::new(value))
  }

  fn insert_item(&mut self, index: usize, value: Object) -> Result<ObjectRefMut<'_>, Object> {
    if index > self.items.len() || !value.is::<(String, Number)>() {
      return Err(value);
    }
    let record = value.to_ref::<(String, Number)>().unwrap();
    if self.position(&record.0).is_some() {
      return Err(value);
    }
    self
      .items
      .insert(index, value.to::<(String, Number)>().unwrap());
    Ok(ObjectRefMut::new(&mut self.items[index]))
  }

  fn push_item(&mut self, value: Object) -> Result<ObjectRefMut<'_>, Object> {
    self.insert_item(self.items.len(), value)
  }

  fn remove_item(&mut self, index: usize) -> Option<Object> {
    (index < self.items.len()).then(|| Object::new(self.items.remove(index)))
  }

  fn move_item(&mut self, from: usize, to: usize) -> Result<(), MoveItemError> {
    move_item_by_remove_insert(self, from, to)
  }
}

impl KeyedSequenceAccessMut for KeyedSequence {
  fn key_mut(&mut self, key: &str) -> Option<ObjectRefMut<'_>> {
    let index = self.position(key)?;
    self.item_mut(index)
  }
}

#[derive(Debug, PartialEq)]
pub(super) struct PushOnly {
  pub(super) values: Vec<u8>,
}

impl Meta for PushOnly {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Sequence(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl SequenceAccess for PushOnly {
  fn len(&self) -> usize {
    self.values.len()
  }

  fn item(&self, index: usize) -> Option<ObjectRef<'_>> {
    self.values.get(index).map(|value| ObjectRef::new(value))
  }
}

impl MetaMut for PushOnly {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Sequence(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl SequenceAccessMut for PushOnly {
  fn item_mut(&mut self, _index: usize) -> Option<ObjectRefMut<'_>> {
    None
  }

  fn push_item(&mut self, value: Object) -> Result<ObjectRefMut<'_>, Object> {
    if !value.is::<u8>() {
      return Err(value);
    }

    let value = *value.into_inner().into_any().downcast::<u8>().unwrap();
    self.values.push(value);
    Ok(ObjectRefMut::new(self.values.last_mut().unwrap()))
  }
}

#[derive(Clone, Debug, PartialEq)]
pub(super) struct PatchConfig {
  pub(super) enabled: bool,
  pub(super) labels: BTreeMap<String, u8>,
  pub(super) profile: Pair,
  pub(super) items: Vec<u8>,
}

impl Meta for PatchConfig {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Struct(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl StructAccess for PatchConfig {
  fn field(&self, name: &str) -> Option<ObjectRef<'_>> {
    match name {
      "enabled" => Some(ObjectRef::new(&self.enabled)),
      "labels" => Some(ObjectRef::new(&self.labels)),
      "profile" => Some(ObjectRef::new(&self.profile)),
      "items" => Some(ObjectRef::new(&self.items)),
      _ => None,
    }
  }

  fn field_names(&self) -> &'static [&'static str] {
    &["enabled", "labels", "profile", "items"]
  }
}

impl MetaMut for PatchConfig {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Struct(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl StructAccessMut for PatchConfig {
  fn field_mut(&mut self, name: &str) -> Option<ObjectRefMut<'_>> {
    match name {
      "enabled" => Some(ObjectRefMut::new(&mut self.enabled)),
      "labels" => Some(ObjectRefMut::new(&mut self.labels)),
      "profile" => Some(ObjectRefMut::new(&mut self.profile)),
      "items" => Some(ObjectRefMut::new(&mut self.items)),
      _ => None,
    }
  }
}

/// Sequence that rejects every insertion, so a failed move cannot restore its
/// item.
#[derive(Debug, PartialEq)]
pub(super) struct RejectInsert {
  pub(super) values: Vec<u8>,
}

impl Meta for RejectInsert {
  fn reflect(&self) -> Reflect<'_> {
    Reflect::Sequence(self)
  }

  fn into_any(self: Box<Self>) -> Box<dyn Any> {
    self
  }

  fn as_any(&self) -> &dyn Any {
    self
  }
}

impl SequenceAccess for RejectInsert {
  fn len(&self) -> usize {
    self.values.len()
  }

  fn item(&self, index: usize) -> Option<ObjectRef<'_>> {
    self.values.get(index).map(|value| ObjectRef::new(value))
  }
}

impl MetaMut for RejectInsert {
  set_body!();

  fn reflect_mut(&mut self) -> ReflectMut<'_> {
    ReflectMut::Sequence(self)
  }

  fn as_any_mut(&mut self) -> &mut dyn Any {
    self
  }
}

impl SequenceAccessMut for RejectInsert {
  fn item_mut(&mut self, index: usize) -> Option<ObjectRefMut<'_>> {
    self
      .values
      .get_mut(index)
      .map(|value| ObjectRefMut::new(value))
  }

  fn move_item(&mut self, from: usize, to: usize) -> Result<(), MoveItemError> {
    move_item_by_remove_insert(self, from, to)
  }

  fn remove_item(&mut self, index: usize) -> Option<Object> {
    (index < self.values.len()).then(|| Object::new(self.values.remove(index)))
  }
}