gloc 0.1.0

A universal business logic architecture for Rust, inspired by the Bloc/Cubit pattern from Flutter. Includes core traits and the #[cubit] macro.
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
<div align="center">

# GLOC

_The **G** is intentional — GLOC started as **Godwin's** Business Logic Component,  
a personal mission to bring the architecture that made Flutter's Bloc legendary  
into the Rust ecosystem. If it grows into something universal, the G will mean  
**Global** too. One pattern. Everywhere Rust runs._

A universal business logic architecture for Rust,  
a faithful recreation of the [Bloc/Cubit pattern](https://bloclibrary.dev) from Flutter.

[![CI — PR](https://github.com/godwinjk/gloc/actions/workflows/pr.yml/badge.svg)](https://github.com/godwinjk/gloc/actions/workflows/pr.yml)
[![CI — Main](https://github.com/godwinjk/gloc/actions/workflows/main.yml/badge.svg)](https://github.com/godwinjk/gloc/actions/workflows/main.yml)
[![Crates.io](https://img.shields.io/crates/v/gloc.svg)](https://crates.io/crates/gloc)
[![Docs.rs](https://docs.rs/gloc/badge.svg)](https://docs.rs/gloc)
[![License](https://img.shields.io/badge/license-MIT-blue.svg)](#license)

</div>

---

## What is GLOC?


GLOC - a Rust port of the [Bloc](https://bloclibrary.dev) architecture that powers state management in Flutter.
Flutter's Bloc is one of the most battle-tested and beloved patterns in mobile
development. GLOC's goal was simple: _recreate that same clean separation of
business logic and UI, but make it work anywhere Rust runs_, not just in one framework.

GLOC separates **business logic** from **presentation** in any Rust application.  
Write your domain logic once, run it everywhere Rust runs.

```
┌─────────────────────────────────────────────────────────────┐
│  Without GLOC           │  With GLOC                        │
│─────────────────────────│───────────────────────────────────│
│  Logic tangled in UI    │  Cubit owns logic                 │
│  State scattered        │  Single source of truth           │
│  Hard to test           │  Fully injectable & mockable      │
│  Framework-locked       │  Web · Desktop · CLI · Embedded   │
└─────────────────────────────────────────────────────────────┘
```

**One pattern. Everywhere Rust runs.**

---

## Table of Contents

- [Concepts]#concepts
- [Installation]#installation
- [Quick Start]#quick-start
- [Cubit — Version 0.1]#cubit--version-01
  - [Define State]#define-state
  - [Implement a Cubit]#implement-a-cubit
  - [Use It]#use-it
  - [Change Detection]#change-detection
  - [Dependency Injection via Trait Objects]#dependency-injection-via-trait-objects
- [Macro — Version 0.2]#macro--version-02
  - [Mode A — Bring Your Own State]#mode-a--bring-your-own-state
  - [Mode B — Generated State]#mode-b--generated-state
  - [Auto-Generated API]#auto-generated-api
  - [on\_change Observer]#on_change-observer
  - [Attribute Options]#attribute-options
  - [Compile-Time Error Messages]#compile-time-error-messages
- [Dioxus Example]#dioxus-example
- [Feature Flags]#feature-flags
- [Comparison with Flutter Bloc]#comparison-with-flutter-bloc
- [Roadmap]#roadmap
- [Contributing]#contributing
- [License]#license

---

## Concepts

| Concept | Description |
|---------|-------------|
| **State** | An immutable snapshot of your domain's data at a point in time. Any `Clone + PartialEq + Debug` type is automatically a `State`. |
| **Cubit** | Owns one slice of state. Exposes domain methods that call `emit()` to transition to the next state. No event type — callers invoke methods directly. |
| **emit()** | The state-transition primitive. Built-in change-detection: emitting a value equal to the current state is a no-op. |
| **on\_change** | Observer hook generated by `#[cubit]`. Registers callbacks that fire synchronously on every real state transition. |

---

## Installation

Add a single dependency — `gloc` includes both the core traits and the `#[cubit]` macro:

```toml
[dependencies]
gloc = "0.1"
```

Then import everything from one place:

```rust
use gloc::{cubit, Cubit, State, CubitBase};
```

**Advanced** — use the individual crates if you only need part of the library:

```toml
[dependencies]
gloc-core  = "0.1"   # traits only — Cubit, State, CubitBase
gloc-macro = "0.1"   # #[cubit] macro only
```

**With tracing** — logs every state transition via the [`tracing`](https://crates.io/crates/tracing) crate:

```toml
[dependencies]
gloc    = { version = "0.1", features = ["tracing"] }
tracing = "0.1"
```

---

## Quick Start

```rust
use gloc::Cubit;
use gloc::cubit;

// 1. Define your state.
#[derive(Clone, PartialEq, Debug)]
struct CounterState { pub count: i32 }

// 2. One line — macro generates everything else.
#[cubit(state = CounterState)]
pub struct CounterCubit {}

// 3. Add your domain methods.
impl CounterCubit {
    pub fn increment(&mut self) {
        let next = self.state().count + 1;
        self.emit(CounterState { count: next });
    }
}

// 4. Use it.
fn main() {
    let mut counter = CounterCubit::new(CounterState { count: 0 });
    counter.increment();
    println!("{}", counter.state().count); // 1
}
```

---

## Cubit — Version 0.1

> The foundation. Zero dependencies, pure traits.

### Define State

Any type that implements `Clone + PartialEq + Debug` is automatically a `State` via the blanket implementation — no explicit `impl State` needed.

```rust
use gloc::State;

// Struct state — the most common pattern
#[derive(Clone, PartialEq, Debug)]
struct AuthState {
    pub is_authenticated: bool,
    pub username: Option<String>,
}

// Enum state — great for loading flows
#[derive(Clone, PartialEq, Debug)]
enum FetchState<T> {
    Idle,
    Loading,
    Success(T),
    Error(String),
}

// Primitive state — works too
fn assert_is_state<S: State>() {}
assert_is_state::<i32>();
assert_is_state::<String>();
assert_is_state::<bool>();
assert_is_state::<Option<String>>();
```

### Implement a Cubit

```rust
use gloc::{Cubit, State};

#[derive(Clone, PartialEq, Debug)]
struct CounterState { pub count: i32 }

struct CounterCubit {
    state: CounterState,
}

impl CounterCubit {
    pub fn new(initial: i32) -> Self {
        Self { state: CounterState { count: initial } }
    }

    /// Increases the count by 1.
    pub fn increment(&mut self) {
        let next = self.state().count + 1;
        self.emit(CounterState { count: next });
    }

    /// Decreases the count by 1.
    pub fn decrement(&mut self) {
        let next = self.state().count - 1;
        self.emit(CounterState { count: next });
    }

    /// Resets count to 0. No-op if already at 0.
    pub fn reset(&mut self) {
        self.emit(CounterState { count: 0 });
    }
}

impl Cubit for CounterCubit {
    type State = CounterState;

    fn state(&self) -> &CounterState {
        &self.state
    }

    fn emit(&mut self, next: CounterState) {
        if next != self.state {
            self.state = next;
        }
    }
}
```

### Use It

```rust
let mut counter = CounterCubit::new(0);

counter.increment();
counter.increment();
assert_eq!(counter.state().count, 2);

counter.decrement();
assert_eq!(counter.state().count, 1);

counter.reset();
assert_eq!(counter.state().count, 0);
```

### Change Detection

`emit()` is a **no-op when the new state equals the current state**. This prevents unnecessary work, matching the semantics of `flutter_bloc`.

```rust
let mut cubit = CounterCubit::new(5);

// count is already 0 after reset, calling it again does nothing
cubit.reset();
cubit.reset(); // no-op — state is already { count: 0 }

assert_eq!(cubit.state().count, 0);
```

### Dependency Injection via Trait Objects

Because everything depends on the `Cubit` **trait** rather than a concrete type, you can inject any implementation — including mocks — without changing call-site code.

```rust
use gloc::Cubit;

// This function knows nothing about CounterCubit specifically.
fn apply_n_increments(cubit: &mut dyn Cubit<State = CounterState>, n: u32) {
    for _ in 0..n {
        let next = cubit.state().count + 1;
        cubit.emit(CounterState { count: next });
    }
}

// Works with your real cubit
let mut real = CounterCubit::new(0);
apply_n_increments(&mut real, 10);
assert_eq!(real.state().count, 10);

// Works with a mock that records every emitted state — no code change needed
struct RecordingCubit { state: CounterState, history: Vec<CounterState> }

impl Cubit for RecordingCubit {
    type State = CounterState;
    fn state(&self) -> &CounterState { &self.state }
    fn emit(&mut self, next: CounterState) {
        if next != self.state {
            self.state = next.clone();
            self.history.push(next);
        }
    }
}

let mut mock = RecordingCubit { state: CounterState { count: 0 }, history: vec![] };
apply_n_increments(&mut mock, 5);
assert_eq!(mock.history.len(), 5);
```

### `CubitBase` — Zero-Boilerplate Wrapper

For simple cases where you do not need custom methods, `CubitBase<S>` is a ready-made cubit for any `State` type:

```rust
use gloc::{Cubit, CubitBase};

let mut cubit = CubitBase::new(String::from("idle"));
cubit.emit(String::from("loading"));
cubit.emit(String::from("success"));

assert_eq!(cubit.state(), "success");

// Change detection built in
cubit.emit(String::from("success")); // no-op
assert_eq!(cubit.state(), "success");
```

---

## Macro — Version 0.2

> Zero boilerplate. Everything generated. Developer writes only domain logic.

The `#[cubit]` attribute macro eliminates the `impl Cubit` block, the `state` field, the constructor, and the observer method. Two modes are available — pick the one that fits your use case.

### Mode A — Bring Your Own State

Use when your state type already exists or needs custom methods.

```rust
use gloc::Cubit;
use gloc::cubit;

// Developer writes the state struct — full control over its shape
#[derive(Clone, PartialEq, Debug)]
pub struct CartState {
    pub items: Vec<String>,
    pub total: f64,
}

// One line — macro generates impl Cubit, new(), on_change()
#[cubit(state = CartState)]
pub struct CartCubit {}

impl CartCubit {
    pub fn add_item(&mut self, name: String, price: f64) {
        let mut next = self.state().clone();
        next.items.push(name);
        next.total += price;
        self.emit(next);
    }

    pub fn clear(&mut self) {
        self.emit(CartState { items: vec![], total: 0.0 });
    }
}

// Usage — new() is generated
let mut cart = CartCubit::new(CartState { items: vec![], total: 0.0 });
cart.add_item("Book".into(), 12.99);
cart.add_item("Pen".into(), 1.49);
assert_eq!(cart.state().items.len(), 2);
assert_eq!(cart.state().total, 14.48);
```

**With extra fields on the cubit** — non-state fields stay on the struct; the generated `new()` takes them as additional leading parameters:

```rust
#[cubit(state = CounterState)]
pub struct CounterCubit {
    pub step: i32,   // extra cubit field — becomes a parameter in new()
}

impl CounterCubit {
    pub fn advance(&mut self) {
        let next = self.state().count + self.step;
        self.emit(CounterState { count: next });
    }
}

// Generated: pub fn new(step: i32, initial: CounterState) -> Self
let mut c = CounterCubit::new(5, CounterState { count: 0 });
c.advance();
assert_eq!(c.state().count, 5);
```

### Mode B — Generated State

Use when you want GLOC to generate the state struct for you. Annotate fields with `#[state]` — those become the generated `{CubitName}State` struct. Non-annotated fields remain on the cubit.

```rust
use gloc::Cubit;
use gloc::cubit;

#[cubit]
pub struct UserCubit {
    #[state] pub name: String,       // goes into UserCubitState
    #[state] pub is_verified: bool,  // goes into UserCubitState
    cache_ttl: u64,                  // stays on UserCubit — not in state
}

// Macro generates:
//   #[derive(Clone, PartialEq, Debug)]
//   pub struct UserCubitState {
//       pub name: String,
//       pub is_verified: bool,
//   }

impl UserCubit {
    pub fn verify(&mut self) {
        let mut next = self.state().clone();
        next.is_verified = true;
        self.emit(next);
    }
}

// Generated: pub fn new(cache_ttl: u64, initial: UserCubitState) -> Self
let mut user = UserCubit::new(
    300,
    UserCubitState { name: "Alice".into(), is_verified: false },
);
user.verify();
assert!(user.state().is_verified);
```

**Mode B — simple toggle example:**

```rust
#[cubit]
pub struct ToggleCubit {
    #[state] pub active: bool,
}

impl ToggleCubit {
    pub fn toggle(&mut self) {
        self.emit(ToggleCubitState { active: !self.state().active });
    }
}

let mut toggle = ToggleCubit::new(ToggleCubitState { active: false });
toggle.toggle();
assert!(toggle.state().active);
toggle.toggle();
assert!(!toggle.state().active);
```

### Auto-Generated API

Both modes generate the following for every `#[cubit]` struct:

```rust
// 1. impl Cubit — type State, state(), emit() with change-detection
impl Cubit for MyCubit {
    type State = MyState;
    fn state(&self) -> &MyState { ... }
    fn emit(&mut self, next: MyState) { /* change-detection + observer calls */ }
}

// 2. Constructor
impl MyCubit {
    pub fn new(/* extra fields, */ initial: MyState) -> Self { ... }
}

// 3. Observer registration
impl MyCubit {
    pub fn on_change(&mut self, callback: impl Fn(&MyState) + 'static) { ... }
}
```

### `on_change` Observer

Subscribe to state transitions without touching rendering or business logic code:

```rust
use gloc::cubit;

#[derive(Clone, PartialEq, Debug)]
struct ScoreState { pub value: u32 }

#[cubit(state = ScoreState)]
pub struct ScoreCubit {}

impl ScoreCubit {
    pub fn add(&mut self, points: u32) {
        let next = self.state().value + points;
        self.emit(ScoreState { value: next });
    }
}

let mut score = ScoreCubit::new(ScoreState { value: 0 });

// Register a logger
score.on_change(|state| {
    println!("[ScoreCubit] score → {}", state.value);
});

// Register an analytics hook
score.on_change(|state| {
    if state.value >= 100 {
        println!("[Analytics] milestone reached: {}", state.value);
    }
});

score.add(60);  // fires both callbacks: "score → 60"
score.add(50);  // fires both: "score → 110", "milestone reached: 110"
score.add(0);   // no-op — change-detection prevents callback fire
```

### Attribute Options

| Argument | Effect | Example |
|---|---|---|
| `state = SomeType` | Mode A — use an existing type as State | `#[cubit(state = MyState)]` |
| `no_new` | Skip generating `new()` — write your own constructor | `#[cubit(state = MyState, no_new)]` |
| `no_observers` | Skip generating `on_change()` and the listener field | `#[cubit(state = MyState, no_observers)]` |

**`no_new` example — custom constructor with validation:**

```rust
#[cubit(state = ConfigState, no_new)]
pub struct ConfigCubit {}

impl ConfigCubit {
    /// Custom constructor with extra validation.
    pub fn from_env() -> Result<Self, std::env::VarError> {
        let value = std::env::var("APP_CONFIG")?;
        Ok(Self {
            __gloc_state: ConfigState { value },
            __gloc_listeners: Vec::new(),
        })
    }
}
```

**`no_observers` example — backend / CLI cubit with no UI subscriptions:**

```rust
#[cubit(state = JobState, no_observers)]
pub struct JobCubit {}

impl JobCubit {
    pub fn start(&mut self) {
        self.emit(JobState { status: "running".into() });
    }

    pub fn finish(&mut self) {
        self.emit(JobState { status: "done".into() });
    }
}
```

### Compile-Time Error Messages

GLOC gives actionable errors at compile time, not at runtime:

```
// Error: no state type provided
#[cubit]
struct BadCubit {}
```

```
error: No state type found for this cubit.

       Provide one of:
       • `#[cubit(state = MyStateType)]`  — use an existing State type (Mode A)
       • `#[state] field: Type` inside the struct  — let gloc generate the State (Mode B)
  --> src/lib.rs:3:8
   |
 3 | struct BadCubit {}
   |        ^^^^^^^^
```

```
// Error: both modes used at once
#[cubit(state = MyState)]
struct Conflict {
    #[state] count: i32,
}
```

```
error: #[cubit] conflict: `state = SomeType` and `#[state]` fields cannot be used together.
       Pick one: either supply `state = SomeType` (Mode A) or annotate fields with `#[state]` (Mode B).
```

---

## Dioxus Example

GLOC cubits integrate cleanly with any Rust UI framework. Here is the full counter example using [Dioxus](https://dioxuslabs.com) 0.7 desktop.

The cubit is stored in a Dioxus `Signal` — reads register the component as a subscriber, writes trigger re-renders.

```rust
// src/cubits/counter.rs — zero Dioxus imports, pure domain logic
use gloc::Cubit;
use gloc::cubit;

#[derive(Clone, PartialEq, Debug)]
pub struct CounterState {
    pub count: i32,
    pub label: String,
}

impl CounterState {
    pub fn new(count: i32) -> Self {
        let label = match count {
            i32::MIN..=-1 => "Negative",
            0             => "Zero",
            1..=9         => "Low",
            10..=99       => "Medium",
            _             => "High",
        }.into();
        Self { count, label }
    }
}

#[cubit(state = CounterState)]
pub struct CounterCubit {}

impl CounterCubit {
    pub fn increment(&mut self) {
        self.emit(CounterState::new(self.state().count + 1));
    }
    pub fn decrement(&mut self) {
        self.emit(CounterState::new(self.state().count - 1));
    }
    pub fn reset(&mut self) {
        self.emit(CounterState::new(0));
    }
}
```

```rust
// src/main.rs — Dioxus wiring
#![allow(non_snake_case)]
mod cubits;

use cubits::{CounterCubit, CounterState};
use dioxus::prelude::*;
use gloc::Cubit;

fn main() { dioxus::launch(App); }

#[component]
fn App() -> Element {
    // CounterCubit::new() is generated by #[cubit]
    let cubit = use_signal(|| CounterCubit::new(CounterState::new(0)));
    rsx! { CounterView { cubit } }
}

#[component]
fn CounterView(cubit: Signal<CounterCubit>) -> Element {
    let state = cubit.read().state().clone();
    rsx! {
        div {
            p { "{state.label}: {state.count}" }
            button { onclick: move |_| cubit.write().decrement(), "−" }
            button { onclick: move |_| cubit.write().reset(),     "Reset" }
            button { onclick: move |_| cubit.write().increment(), "+" }
        }
    }
}
```

Run it:

```sh
cargo run -p counter-dioxus-v02
```

Full example source: [`examples/v0.2/counter-dioxus/`](examples/v0.2/counter-dioxus/)

---

## Feature Flags

| Crate | Feature | Effect |
|---|---|---|
| `gloc` | `tracing` | Enables `tracing::debug!` inside `emit()` — logs every state transition. Zero cost when disabled. |
| `gloc-macro` | `tracing` | Same — gates the tracing call in macro-generated `emit()`. |

Enable tracing:

```toml
[dependencies]
gloc       = { version = "0.1", features = ["tracing"] }
gloc-macro = { version = "0.1", features = ["tracing"] }
tracing    = "0.1"
tracing-subscriber = "0.3"
```

Every `emit()` call that transitions state will log:

```
DEBUG CounterCubit{old=CounterState { count: 0 }, new=CounterState { count: 1 }}
```

---

## Comparison with Flutter Bloc

GLOC is a deliberate port of Flutter's Bloc/Cubit pattern into idiomatic Rust.

| Concept | Flutter Bloc | GLOC |
|---|---|---|
| State container | `Cubit<State>` | `Cubit` trait + `#[cubit]` |
| State type | `class CounterState` | Any `Clone + PartialEq + Debug` |
| State transition | `emit(nextState)` | `self.emit(next_state)` |
| Change detection | built-in | built-in (PartialEq guard) |
| Boilerplate removal | `@cubit` annotation | `#[cubit]` proc macro |
| Code generation | `build_runner` (runtime) | proc macro (compile-time, zero overhead) |
| State provider | `BlocProvider` widget | `Signal<MyCubit>` (framework-specific) |
| State listener | `BlocListener` | `on_change(callback)` |
| Observer | `BlocObserver` | `on_change` + tracing feature |
| Scope | Flutter only | **Any Rust application** |

---

## Roadmap

| Phase | Version | Status | Description |
|---|---|---|---|
| 1 | v0.1 | ✅ Released | `Cubit` trait, `CubitBase`, `State` blanket impl |
| 2 | v0.2 | ✅ Released | `#[cubit]` proc macro — Mode A, Mode B, `on_change`, tracing |
| 3 | v0.3 | 🔲 Planned | `Bloc` trait — full event-driven `Event → State` flow |
| 4 | v0.4 | 🔲 Planned | `#[bloc]` macro + Dioxus, Axum, Bevy adapters |
| 5 | v1.0 | 🔲 Planned | Stable API, dedicated docs site, DevTools |

### Phase 3 Preview — Bloc

```rust
// Coming in v0.3
enum CounterEvent { Increment, Decrement }

#[derive(Clone, PartialEq, Debug)]
struct CounterState { count: i32 }

struct CounterBloc { state: CounterState }

impl Bloc for CounterBloc {
    type Event = CounterEvent;
    type State = CounterState;

    fn on_event(&mut self, event: CounterEvent) {
        match event {
            CounterEvent::Increment =>
                self.emit(CounterState { count: self.state().count + 1 }),
            CounterEvent::Decrement =>
                self.emit(CounterState { count: self.state().count - 1 }),
        }
    }
}
```

---

## Project Structure

```
GLoC/
├── gloc-core/                  Core crate — published as `gloc-core`
│   └── src/
│       ├── lib.rs
│       ├── state.rs            State trait (blanket impl)
│       └── cubit.rs            Cubit trait + CubitBase
│   └── tests/
│       └── cubit_tests.rs      39 integration tests
│
├── gloc-macro/                 Proc macro crate — published as `gloc-macro`
│   └── src/
│       ├── lib.rs              #[cubit] entry point
│       ├── args.rs             Attribute argument parsing (darling)
│       ├── codegen.rs          Shared code generation helpers
│       ├── mode_a.rs           Mode A — bring-your-own state
│       ├── mode_b.rs           Mode B — generated state struct
│       └── errors.rs           Compile-time diagnostic helpers
│   └── tests/
│       ├── cubit_macro_tests.rs   30 integration tests
│       ├── ui_tests.rs            trybuild runner
│       └── ui/pass|fail/          9 compile-pass/fail scenarios
├── gloc/                       Umbrella crate — published as `gloc`
│
├── examples/
│   ├── v0.1/counter-dioxus/    Dioxus 0.7 desktop — manual Cubit
│   └── v0.2/counter-dioxus/    Dioxus 0.7 desktop — #[cubit] macro
│
└── .github/
    ├── CODEOWNERS
    └── workflows/
        ├── pr.yml              PR gate (build, test, fmt, clippy)
        └── main.yml            Post-merge verification
```

---

## Contributing

GLOC welcomes contributions of **every kind** — from first-time open-source
contributors to seasoned Rust experts. No contribution is too small. Whether
you are fixing a typo, improving a doc comment, adding a test case, proposing
a new feature, or porting a framework adapter, you are welcome here.

> **The only hard rule:** every change must go through a Pull Request and
> pass the full CI pipeline before it can be merged. This is not bureaucracy —
> it is how we protect every contributor's work, including yours.

---

### Ways to Contribute

| Type | Examples |
|---|---|
| **Bug reports** | Something panics unexpectedly, wrong behaviour, misleading error message |
| **Documentation** | Improve doc comments, fix typos, add usage examples, translate |
| **Tests** | Add missing test cases, improve coverage, add trybuild fail scenarios |
| **Bug fixes** | Fix a reported issue, improve edge-case handling |
| **New features** | New macro arguments, new generated methods, new `CubitBase` helpers |
| **Framework adapters** | Dioxus, Axum, Bevy, Tauri, Leptos, or any other Rust framework |
| **Performance** | Reduce allocations, improve compile times, benchmark regressions |
| **Tooling** | CI improvements, release automation, dev experience |

---

### Getting Started

**1. Fork and clone**

```sh
git clone https://github.com/<your-username>/gloc.git
cd gloc
```

**2. Create a focused branch**

Branch names should describe the change clearly:

```sh
git checkout -b fix/emit-change-detection-edge-case
git checkout -b feat/cubit-history-observer
git checkout -b docs/improve-mode-b-examples
git checkout -b test/add-trybuild-unit-struct-fail
```

**3. Make your changes**

Run the full local check suite before every push — the same checks CI runs:

```sh
# Format (required — CI will reject unformatted code)
cargo fmt --all

# Lint (required — warnings are treated as errors in CI)
cargo clippy --workspace --all-targets -- -D warnings

# Tests (required — all must pass)
cargo test --workspace

# Trybuild UI tests (required if you touched gloc-macro)
cargo test -p gloc-macro --test ui_tests
```

**4. Open a Pull Request**

- Target the `main` branch
- Fill in the PR description: what changed, why, and how to test it
- The CI pipeline runs automatically — **all four jobs must be green** before the PR can be merged
- `@godwinjk` will review every PR (required by CODEOWNERS)

---

### CI Pipeline — What Must Pass

Every PR must pass all four jobs. You can replicate the exact CI checks locally using the commands below.

| Job | What it checks | Local command |
|---|---|---|
| **build** | `cargo build` in debug and release | `cargo build --workspace` |
| **test** | Unit, integration, doc-tests, trybuild | `cargo test --workspace` |
| **fmt** | Code formatted with `rustfmt` | `cargo fmt --all -- --check` |
| **clippy** | No clippy warnings (treated as errors) | `cargo clippy --workspace --all-targets -- -D warnings` |

### Cleaning the Project

Build artifacts accumulate in `target/` and can grow to several gigabytes.
Clean them before a fresh CI-equivalent run or when diagnosing stale-cache issues.

| Command | What it removes | When to use |
|---|---|---|
| `cargo clean` | Entire `target/` directory (all profiles, all crates) | Full clean before a release or when something feels wrong |
| `cargo clean -p gloc` | Artifacts for the `gloc` crate only | Faster rebuild when only the core crate changed |
| `cargo clean -p gloc-macro` | Artifacts for `gloc-macro` only | After changing the proc macro |
| `rm -rf target/release` | Release profile only, keeps debug | Free space without losing incremental debug builds |
| `rm -rf target/tests` | trybuild test cache only | When UI test snapshots behave unexpectedly |

**Full deep clean** (re-downloads all crates — use sparingly):

```sh
cargo clean
rm -rf ~/.cargo/registry/cache
rm -rf ~/.cargo/registry/src
```

**Recommended before pushing a PR** — run a clean build to make sure nothing relies on stale artifacts:

```sh
cargo clean && cargo test --workspace
```

If CI fails on your PR, check the failing job's log in the Actions tab. Fix
the issue and push a new commit — CI re-runs automatically. Do not force-push
over a failing CI run while a review is in progress.

---

### Code Quality Standards

These standards apply to all contributed code and are enforced in code review:

**Documentation**
- Every `pub` item (struct, trait, fn, type) must have a `///` doc comment
- Doc comments must explain: what it does, parameters, return value, panics (if any), and include at least one `# Example` for non-trivial items
- Do not describe *what* the code does — describe *why* it exists and what a caller needs to know

**Testing**
- Every new feature must ship with tests that cover: the happy path, at least one edge case, and at least one boundary condition
- Tests that verify `Cubit` trait implementations must include a trait-object (`dyn Cubit<State = …>`) test to confirm Dependency Inversion compatibility
- New error paths in `gloc-macro` must have a corresponding `trybuild` fail case with a `.stderr` snapshot

**Design**
- Follow SOLID principles — especially **Single Responsibility** (one cubit, one concern) and **Dependency Inversion** (depend on traits, not concrete types)
- Prefer extending existing abstractions over adding new ones
- Do not introduce breaking changes to the public API without a major version discussion in an issue first
- Generated code (proc macro output) must compile without warnings on the consumer's side

**Style**
- `rustfmt` is the style guide — no manual formatting discussions
- Clippy is the linter — fix all warnings, do not `#[allow(...)]` without a comment explaining why
- No `unwrap()` or `expect()` in library code — return a `Result` or emit a compile-time error
- Comments in source explain *why*, not *what*

---

### Reporting Bugs

Open a [GitHub Issue](https://github.com/godwinjk/gloc/issues) and include:

- GLOC version (`cargo tree | grep gloc`)
- Rust version (`rustc --version`)
- A minimal reproducible example
- The behaviour you expected vs. what actually happened

---

### Suggesting Features

Open a GitHub Issue with the `enhancement` label before writing code.
Describe the use case, not just the implementation. This gives maintainers
a chance to confirm the direction before you invest time building it.

---

## Code of Practice

GLOC is built on the belief that great software comes from a community where
every contributor feels safe, respected, and valued. The following principles
govern how we work together.

### Our Pledge

We pledge to make participation in GLOC a harassment-free experience for
everyone, regardless of age, body size, disability, ethnicity, gender identity
and expression, level of experience, nationality, personal appearance, race,
religion, or sexual identity and orientation.

### Expected Behaviour

- **Be respectful.** Treat every contributor with the same respect you would
  want in return. Disagree with ideas, never with people.
- **Be constructive.** Code review feedback should explain *why* a change is
  needed and suggest *how* to improve it. "This is wrong" is not feedback;
  "this will panic when the Vec is empty — consider adding a guard here" is.
- **Be patient.** Contributors work at different paces and in different time
  zones. Maintainers review PRs as promptly as possible, but response time
  is not guaranteed. Do not chase or demand.
- **Be inclusive.** Write code, comments, and documentation that a developer
  new to Rust, new to state management, or new to open source can understand.
  Avoid jargon where plain language works just as well.
- **Give credit.** Acknowledge others' work. If a PR builds on someone else's
  idea or prior work, say so in the description.
- **Ask questions.** There are no stupid questions. If something in the codebase,
  a doc comment, or a review comment is unclear, ask. Clarity is a contribution.

### Unacceptable Behaviour

The following will not be tolerated in any GLOC space (issues, PRs, discussions,
or any affiliated communication channel):

- Harassment, insults, or personal attacks of any kind
- Discriminatory jokes or language
- Posting others' private information without explicit permission
- Deliberately dismissing or belittling contributions based on experience level
- Sustained disruptive behaviour after being asked to stop

### Enforcement

Violations may be reported by contacting `@godwinjk` directly via GitHub.
All reports will be reviewed promptly and handled with confidentiality.
Maintainers reserve the right to remove, edit, or reject contributions
that do not align with this Code of Practice, and to ban contributors
who engage in unacceptable behaviour.

### Attribution

This Code of Practice is adapted from the
[Contributor Covenant v2.1](https://www.contributor-covenant.org/version/2/1/code_of_conduct/).

---

## Support GLOC

GLOC is free, open-source, and built entirely in personal time driven by a
genuine belief that Rust deserves the same elegant state management patterns
that Flutter developers enjoy every day. If GLOC saves you time, simplifies
your architecture, or just sparks joy — any form of support means the world
and keeps the project moving forward.

---

### ⭐ Star the Repository

The simplest thing you can do. A GitHub star signals to other Rust developers
that this project is worth their attention, helps GLOC surface in search
results, and genuinely motivates continued development.

**[→ Star GLOC on GitHub](https://github.com/godwinjk/gloc)**

---

### 📣 Spread the Word

Every share reaches developers who might never have found GLOC otherwise.

- **Write about it** — blog post, dev.to article, or a Twitter/X thread
- **Talk about it** — mention it at your local Rust meetup or in a conference talk
- **Recommend it** — if GLOC helps your team, tell other teams
- **Share on Reddit** — post to [r/rust]https://www.reddit.com/r/rust/ or [r/flutterdev]https://www.reddit.com/r/flutterdev/ — the Flutter community discovering Rust is a beautiful thing
- **Add it to your project's README** — if you build something with GLOC, a link back helps everyone

---

### ☕ Buy me a Coffee

If GLOC has saved you hours of architecture work, consider buying a coffee.
Every contribution — no matter the size — directly funds time spent on new
features, documentation, framework adapters, and keeping the project alive.

<div align="center">

[![ko-fi](https://ko-fi.com/img/githubbutton_sm.svg)](https://ko-fi.com/S6S0176OVQ)

</div>

---

### 💙 Donate via PayPal

Prefer PayPal? Donations of any amount are deeply appreciated and go directly
toward GLOC development time.

<div align="center">

[![Donate with PayPal](https://www.paypalobjects.com/en_US/i/btn/btn_donateCC_LG.gif)](https://paypal.me/godwinj)

</div>

---

### 🤝 Sponsor the Project

Interested in a longer-term sponsorship — for your company, team, or
open-source fund? Reach out via GitHub to discuss sponsorship tiers,
acknowledgement in the README, and priority feature requests.

**[→ Open a sponsorship discussion](https://github.com/godwinjk/gloc/discussions)**

---

> Thank you. Truly. Every star, every share, every coffee, every line of
> contributed code makes GLOC better for every Rust developer who uses it.
> — Godwin

---

## License

Licensed under the [MIT License](LICENSE-MIT).

---

<div align="center">

Built with Rust 🦀 — designed for everyone.

[crates.io/crates/gloc](https://crates.io/crates/gloc) · [docs.rs/gloc](https://docs.rs/gloc)

</div>