<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.
[](https://github.com/godwinjk/gloc/actions/workflows/pr.yml)
[](https://github.com/godwinjk/gloc/actions/workflows/main.yml)
[](https://crates.io/crates/gloc)
[](https://docs.rs/gloc)
[](#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
| **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
| `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
|
```
```
// 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
| `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.
| 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
| 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
├── 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
| **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.
| **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.
| `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">
[](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">
[](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>