adar 0.2.0

Collection of architectural tools including flags, state machine, enum and tuple operations.
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
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
# Advanced Architecture (ADAR)

[![Crates.io](https://img.shields.io/crates/v/adar.svg)](https://crates.io/crates/adar)
[![Downloads](https://img.shields.io/crates/d/adar.svg)](https://crates.io/crates/adar)
[![Docs](https://docs.rs/adar/badge.svg)](https://docs.rs/adar/latest/adar/)

Adar is a collection of architectural tools that help you write more readable and performant code.

### Table of contents
- [Flags](#flags)
- [StateMachine](#state-machine)
- [ReflectEnum](#reflect-enum)
- [EnumTraitDeref](#enum-trait-deref)
- [Tuple operations](#tuple-operations)

## Flags

[Flags](`crate::enums::Flags`) is a type-safe and verbose bitwise flag container. Most of the flag operations are inlined.

### Features

- Union, Intersect
- Serialization (requires `serde` feature)
- Conversion to and from raw values
- Intuitive syntax

### Example

```rust
use adar::prelude::*;

#[FlagEnum]
enum MyFlag {F1, F2, F3}

let mut a = Flags::from(MyFlag::F1);
a.set(MyFlag::F2);
let mut b = MyFlag::F1 | MyFlag::F2 | MyFlag::F3;
b.reset(MyFlag::F1);

println!("a: {:?}, {:03b}", a, a.into_raw());
println!("b: {:?}, {:03b}", b, b.into_raw());

println!("a.any(F1,F3): {:?}", a.any(MyFlag::F1 | MyFlag::F3));
println!("a.all(F1,F3): {:?}", a.all(MyFlag::F1 | MyFlag::F3));

println!("a.intersect(b): {:?}", a.intersect(b));
println!("a.union(b): {:?}", a.union(b));
println!("full(): {:?}", Flags::<MyFlag>::full());
```

<details>
<summary>Click to see the output</summary>
<code><b>>> cargo run --example flags</b></code>

```ignore
a: (F1,F2), 011
b: (F2,F3), 110
a.any(F1,F3): true
a.all(F1,F3): false
a.intersect(b): (F2)
a.union(b): (F1,F2,F3)
full(): (F1,F2,F3)
```

</details>

<details>
<summary>Click to see the generated code</summary>
<code><b>>> cargo expand --example flags</b></code>

```rust,ignore
...
#[repr(u32)]
enum MyFlag {
    F1 = 1,
    F2 = 2,
    F3 = 4,
}
...
impl std::ops::BitOr for MyFlag
where
    Self: adar::prelude::ReflectEnum,
{
    type Output = adar::prelude::Flags<Self>;
    fn bitor(self, rhs: Self) -> Self::Output {
        Flags::empty() | self | rhs
    }
}
...
```

</details>

## State Machine

### Features

- [State](`crate::state_machine::State`) callback:
  - [on_enter](`crate::state_machine::State::on_enter`) - Called when the state machine enters a state
  - [on_update](`crate::state_machine::State::on_update`) - Called when the state machine is updated (always for the current state)
  - [on_leave](`crate::state_machine::State::on_leave`) - Called when the state machine leaves a state
- [Machine](`crate::state_machine::Machine`) callback:
  - [on_update](`crate::state_machine::Machine::on_update`) - Called when update is called
  - [on_transition](`crate::state_machine::Machine::on_transition`) - Called at each transition (after [on_leave](`crate::state_machine::State::on_leave`), before [on_enter](`crate::state_machine::State::on_enter`))
- Pass arguments to updates (see [update_args](`crate::state_machine::StateMachine::update_args`), [run_args](`crate::state_machine::StateMachine::run_args`), [transition_args](`crate::state_machine::StateMachine::transition_args`))
- Store context in the [StateMachine](`crate::state_machine::StateMachine`) (see [new_context](`crate::state_machine::StateMachine::new_context`), with up to 8 generic parameters)
- Operating modes
  - Non-blocking mode (see [update_args](crate::state_machine::StateMachine::update_args))
  - Blocking mode (see [run_args](crate::state_machine::StateMachine::run_args))
- End state (see [EndState](crate::state_machine::EndState), [is_finished](crate::state_machine::HasEndState::is_finished))
- Sync only

### Example

[![](https://mermaid.ink/img/pako:eNp1kVFPgzAUhf8Kub4ZtkiBMfpgYpxZlixithmjYpYKF0ZW6FKKOpf9d8sYTjHep3tvv3NOm-4gEjEChVIxhaOMpZLlvTcSFoauiLOyHGFiSIyNJOOcnjFCzEhwIen7KlPY4VKJWBxJwlrylbNo3SG3yLl4b027aAM_n78Yvd6lMVdi02zqjlJaX6c-GKOaIYu3BjXGwXK-CO6Wo_vZ1WIS3DZ8C2jNMfAgE1rweDOdBg9dXmiyeUQbPEnmLMF_E07I74x6_zcFTEhlFgNVskITcpQ5q0fY1W4hqBXmGALVbczkOoSw2GvNhhVPQuStTIoqXQFNGC_1VG3i09d9byUWMcprURUKqDvwDyZAd_AB1PbtvmUPLddziUM81zJhqyGr79ue49nEcayB5wzdvQmfh9iL_tBz_J-1_wJ7ja8f?type=png)](https://mermaid.live/edit#pako:eNp1kVFPgzAUhf8Kub4ZtkiBMfpgYpxZlixithmjYpYKF0ZW6FKKOpf9d8sYTjHep3tvv3NOm-4gEjEChVIxhaOMpZLlvTcSFoauiLOyHGFiSIyNJOOcnjFCzEhwIen7KlPY4VKJWBxJwlrylbNo3SG3yLl4b027aAM_n78Yvd6lMVdi02zqjlJaX6c-GKOaIYu3BjXGwXK-CO6Wo_vZ1WIS3DZ8C2jNMfAgE1rweDOdBg9dXmiyeUQbPEnmLMF_E07I74x6_zcFTEhlFgNVskITcpQ5q0fY1W4hqBXmGALVbczkOoSw2GvNhhVPQuStTIoqXQFNGC_1VG3i09d9byUWMcprURUKqDvwDyZAd_AB1PbtvmUPLddziUM81zJhqyGr79ue49nEcayB5wzdvQmfh9iL_tBz_J-1_wJ7ja8f)

```rust,no_run
use adar::prelude::*;
use std::{process::Command, time::Duration};

#[StateEnum]
#[ReflectEnum] // Optional. (Used here to print the name of the state)
enum TrafficLight {
    Go,
    GetReady,
    StopIfSafe,
    Stop,
}

impl TrafficLight {
    const YELLOW_DURATION: Duration = Duration::from_secs(1);
    const GO_STOP_DURATION: Duration = Duration::from_secs(2);
}

impl Machine for TrafficLight {
    fn on_transition(&mut self, new_state: &Self::States, _context: &mut Self::Context) {
        Command::new("clear")
            .status()
            .expect("Failed to clear screen!");

        println!("{}", new_state.name());
    }
}

impl State for Go {
    fn on_enter(&mut self, _args: Option<&mut Self::Args>, _context: &mut Self::Context) {
        println!("⚫\n⚫\n🟢");
    }
    fn on_update(
        &mut self,
        _args: Option<&mut Self::Args>,
        _context: &mut Self::Context,
    ) -> Option<Self::States> {
        std::thread::sleep(TrafficLight::GO_STOP_DURATION);
        Some(StopIfSafe.into())
    }
}

impl State for GetReady {
    fn on_enter(&mut self, _args: Option<&mut Self::Args>, _context: &mut Self::Context) {
        println!("šŸ”“\n🟔\n⚫");
    }
    fn on_update(
        &mut self,
        _args: Option<&mut Self::Args>,
        _context: &mut Self::Context,
    ) -> Option<Self::States> {
        std::thread::sleep(TrafficLight::YELLOW_DURATION);
        Some(Go.into())
    }
}

impl State for StopIfSafe {
    fn on_enter(&mut self, _args: Option<&mut Self::Args>, _context: &mut Self::Context) {
        println!("⚫\n🟔\n⚫");
    }
    fn on_update(
        &mut self,
        _args: Option<&mut Self::Args>,
        _context: &mut Self::Context,
    ) -> Option<Self::States> {
        std::thread::sleep(TrafficLight::YELLOW_DURATION);
        Some(Stop.into())
    }
}

impl State for Stop {
    fn on_enter(&mut self, _args: Option<&mut Self::Args>, _context: &mut Self::Context) {
        println!("šŸ”“\n⚫\n⚫")
    }
    fn on_update(
        &mut self,
        _args: Option<&mut Self::Args>,
        _context: &mut Self::Context,
    ) -> Option<Self::States> {
        std::thread::sleep(TrafficLight::GO_STOP_DURATION);
        Some(GetReady.into())
    }
}

fn main() {
    StateMachine::new(Stop).run();
}
```

<details>
<summary>Click to see the output</summary>
<code><b>>> cargo run --example statemachine_trafficlight</b></code>

```ignore
Stop
šŸ”“
⚫
⚫
... (5s)
GetReady
šŸ”“
🟔
⚫
... (2s)
Go
⚫
⚫
🟢
... (5s)
StopIfSafe
⚫
🟔
⚫
... (2s, then repeats)
```

</details>
<details>
<summary>Click to see the generated code</summary>
<code><b>>> cargo expand --example statemachine_trafficlight</b></code>

```rust,ignore
...
enum TrafficLight {
    Go(Go),
    GetReady(GetReady),
    StopIfSafe(StopIfSafe),
    Stop(Stop),
}
impl adar::prelude::ReflectEnum for TrafficLight {
    type Type = u32;
    fn variants() -> &'static [adar::prelude::EnumVariant<TrafficLight>] {
        const VARIANTS: &[adar::prelude::EnumVariant<TrafficLight>] = &[
            EnumVariant::new("Go", None),
            EnumVariant::new("GetReady", None),
            EnumVariant::new("StopIfSafe", None),
            EnumVariant::new("Stop", None),
        ];
        VARIANTS
    }
    fn count() -> usize {
        4usize
    }
    fn name(&self) -> &'static str {
        match self {
            Self::Go { .. } => "Go",
            Self::GetReady { .. } => "GetReady",
            Self::StopIfSafe { .. } => "StopIfSafe",
            Self::Stop { .. } => "Stop",
        }
    }
}
struct Go;
impl adar::prelude::StateTypes for Go {
    type States = TrafficLight;
    type Args = ();
    type Context = ();
}
impl Into<TrafficLight> for Go {
    fn into(self) -> TrafficLight {
        TrafficLight::Go(self)
    }
}
struct GetReady;
impl adar::prelude::StateTypes for GetReady {
    type States = TrafficLight;
    type Args = ();
    type Context = ();
}
impl Into<TrafficLight> for GetReady {
    fn into(self) -> TrafficLight {
        TrafficLight::GetReady(self)
    }
}
struct StopIfSafe;
impl adar::prelude::StateTypes for StopIfSafe {
    type States = TrafficLight;
    type Args = ();
    type Context = ();
}
impl Into<TrafficLight> for StopIfSafe {
    fn into(self) -> TrafficLight {
        TrafficLight::StopIfSafe(self)
    }
}
struct Stop;
impl adar::prelude::StateTypes for Stop {
    type States = TrafficLight;
    type Args = ();
    type Context = ();
}
impl Into<TrafficLight> for Stop {
    fn into(self) -> TrafficLight {
        TrafficLight::Stop(self)
    }
}
impl adar::prelude::StateTypes for TrafficLight {
    type States = Self;
    type Args = ();
    type Context = ();
}
impl adar::prelude::State for TrafficLight {
    fn on_enter(&mut self, args: Option<&mut Self::Args>, context: &mut Self::Context) {
        match self {
            Self::Go(s) => Go::on_enter(s, args, context),
            Self::GetReady(s) => GetReady::on_enter(s, args, context),
            Self::StopIfSafe(s) => StopIfSafe::on_enter(s, args, context),
            Self::Stop(s) => Stop::on_enter(s, args, context),
            _ => {}
        }
    }
    fn on_update(
        &mut self,
        args: Option<&mut Self::Args>,
        context: &mut Self::Context,
    ) -> Option<Self::States> {
        match self {
            Self::Go(s) => Go::on_update(s, args, context),
            Self::GetReady(s) => GetReady::on_update(s, args, context),
            Self::StopIfSafe(s) => StopIfSafe::on_update(s, args, context),
            Self::Stop(s) => Stop::on_update(s, args, context),
            _ => None,
        }
    }
    fn on_leave(&mut self, args: Option<&mut Self::Args>, context: &mut Self::Context) {
        match self {
            Self::Go(s) => Go::on_leave(s, args, context),
            Self::GetReady(s) => GetReady::on_leave(s, args, context),
            Self::StopIfSafe(s) => StopIfSafe::on_leave(s, args, context),
            Self::Stop(s) => Stop::on_leave(s, args, context),
            _ => {}
        }
    }
}
...
```

</details>

## Reflect Enum

Reflects information about the enum and its variants.

### Features

- Reflects the underlying type (see [ReflectEnum::Type](crate::enums::ReflectEnum::Type))
  - You may define your own repr (e.g. `#[repr(u8)]`)
- Reflects the name and value, or iterates over enum variants (see [ReflectEnum::variants](crate::enums::ReflectEnum::variants),[EnumVariant](crate::enums::EnumVariant))
- Number of variants (see [ReflectEnum::count](crate::enums::ReflectEnum::count))
- Name of the enum (see [ReflectEnum::name](crate::enums::ReflectEnum::name))

### Example

```rust
use adar::prelude::*;

#[ReflectEnum]
#[repr(u32)]
#[derive(Debug)]
enum MyEnum {
    Value1 = 33,
    Value2(i32),
    Value3 { a: String },
}

fn main() {
    println!("Variants count: {}", MyEnum::count());
    for variant in MyEnum::variants() {
        println!("{}, {:?}", variant.name, variant.value,);
    }
}
```

<details>
<summary>Click to see the output</summary>
<code><b>>> cargo run --example reflect_enum</b></code>

```ignore
Variants count: 3
Value1, Some(Value1)
Value2, None
Value3, None
```

</details>

<details>
<summary>Click to see the generated code</summary>
<code><b>>> cargo expand --example reflect_enum</b></code>

```rust,ignore
...
impl adar::prelude::ReflectEnum for MyEnum {
    type Type = u32;
    fn variants() -> &'static [adar::prelude::EnumVariant<MyEnum>] {
        const VARIANTS: &[adar::prelude::EnumVariant<MyEnum>] = &[
            EnumVariant::new("Value1", Some(MyEnum::Value1)),
            EnumVariant::new("Value2", None),
            EnumVariant::new("Value3", None),
        ];
        VARIANTS
    }
    fn count() -> usize {
        3usize
    }
    fn name(&self) -> &'static str {
        match self {
            Self::Value1 { .. } => "Value1",
            Self::Value2 { .. } => "Value2",
            Self::Value3 { .. } => "Value3",
        }
    }
}
...
```

</details>

## Enum Trait Deref

Enables you to access a trait through an enum whose named variants implement the same trait.

### Features

- Deref implementation (see [EnumTraitDeref](macros::EnumTraitDeref))
- DerefMut implementation (see [EnumTraitDerefMut](macros::EnumTraitDerefMut), also implements [EnumTraitDeref](macros::EnumTraitDeref) trait)

### Example

```rust
use adar::prelude::*;

trait MyTrait {
    fn my_func(&self);
}

#[EnumTraitDeref(MyTrait)]
enum MyEnum {
    A(A),
    B(B),
}

#[derive(Clone)]
struct A;

#[derive(Clone)]
struct B;

impl MyTrait for A {
    fn my_func(&self) {
        println!("Hello A");
    }
}

impl MyTrait for B {
    fn my_func(&self) {
        println!("Hello B");
    }
}

fn main() {
    for e in [MyEnum::A(A), MyEnum::B(B)] {
        e.my_func();
    }
}
```

<details>
<summary>Click to see the output</summary>
<code><b>>> cargo run --example enum_trait_deref</b></code>

```ignore
Hello A
Hello B
```

</details>
<details>
<summary>Click to see the generated code</summary>
<code><b>>> cargo expand --example enum_trait_deref</b></code>

```rust,ignore
...
impl ::core::ops::Deref for MyEnum {
    type Target = dyn MyTrait;
    fn deref(&self) -> &Self::Target {
        match self {
            Self::A(v) => v as &Self::Target,
            Self::B(v) => v as &Self::Target,
        }
    }
}
...
```

</details>

## Tuple operations
### Features
- Concatenation (When the exact type is known at compile time, see [TupleConcat::concat()](prelude::TupleConcat::concat))
- Iteration (Only for homogeneous tuples, see [TupleIter::iter()](prelude::TupleIter::iter))
- Iteration over implemented trait (Each tuple element needs to implement the trait, see [TupleTraitIter::iter_trait()](prelude::TupleTraitIter::iter_trait), [TupleTraitIterMut::iter_trait_mut()](prelude::TupleTraitIterMut::iter_trait_mut))
- Select tuple element by type (The tuple must contain exactly one element of the given type, see [TupleSelect::select](prelude::TupleSelect::select))
### Example
```rust
use adar::prelude::*;

#[TraitRef]
trait ToStringCapital {
    fn to_string_capital(&self) -> String;
}

impl<T> ToStringCapital for T
where
    T: ToString,
{
    fn to_string_capital(&self) -> String {
        self.to_string()
            .chars()
            .map(|c| c.to_uppercase().next().unwrap())
            .collect()
    }
}

fn main() {
    println!("Homogeneous:");
    let homogeneous = (1, 2, 3, 4);
    for i in homogeneous.iter() {
        println!("\t{i}");
    }

    let mixed = ("String", 24, true, 2.2);
    println!("Mixed -> ToString:");
    // Automatically implemented for all std/core traits
    for i in mixed.iter_trait::<dyn ToString>() {
        println!("\t{}", i.to_string());
    }
    // Needs #[TraitRef] for custom traits
    println!("Mixed -> ToStringCapital:");
    for i in mixed.iter_trait::<dyn ToStringCapital>() {
        println!("\t{}", i.to_string_capital());
    }

    println!("Concat: {:?}", homogeneous.concat(mixed));
    println!("Sum of homogeneous: {:?}", homogeneous.iter().sum::<i32>());
    println!("F32 from mixed: {:?}", mixed.select::<f32>());
    println!("bool from mixed: {:?}", mixed.select::<bool>());
}
```

<details>
<summary>Click to see the output</summary>
<code><b>>> cargo run --example tuple_operations</b></code>

```ignore
Homogeneous:
        1
        2
        3
        4
Mixed -> ToString:
        String
        24
        true
        2.2
Mixed -> ToStringCapital:
        STRING
        24
        TRUE
        2.2
Concat: (1, 2, 3, 4, "String", 24, true, 2.2)
Sum of homogeneous: 10
F32 from mixed: 2.2
bool from mixed: true
```

</details>
<details>
<summary>Click to see the generated code</summary>
<code><b>>> cargo expand --example tuple_operations</b></code>

```rust,ignore
...
impl<'a, T> adar::prelude::AsTraitRef<T> for dyn CustomTrait
where
    T: CustomTrait + 'static,
{
    fn as_trait_ref(value: &T) -> &Self {
        value
    }
}
impl<'a, T> adar::prelude::AsTraitMut<T> for dyn CustomTrait
where
    T: CustomTrait + 'static,
{
    fn as_trait_mut(value: &mut T) -> &mut Self {
        value
    }
}
...
```

</details>