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 from Flutter.
What is GLOC?
GLOC - a Rust port of the Bloc 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
- Installation
- Quick Start
- Cubit — Version 0.1
- Macro — Version 0.2
- Dioxus Example
- Feature Flags
- Comparison with Flutter Bloc
- Roadmap
- Contributing
- 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:
[]
= "0.1"
Then import everything from one place:
use ;
Advanced — use the individual crates if you only need part of the library:
[]
= "0.1" # traits only — Cubit, State, CubitBase
= "0.1" # #[cubit] macro only
With tracing — logs every state transition via the tracing crate:
[]
= { = "0.1", = ["tracing"] }
= "0.1"
Quick Start
use Cubit;
use cubit;
// 1. Define your state.
// 2. One line — macro generates everything else.
// 3. Add your domain methods.
// 4. Use it.
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.
use State;
// Struct state — the most common pattern
// Enum state — great for loading flows
// Primitive state — works too
;
;
;
;
Implement a Cubit
use ;
Use It
let mut counter = new;
counter.increment;
counter.increment;
assert_eq!;
counter.decrement;
assert_eq!;
counter.reset;
assert_eq!;
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.
let mut cubit = new;
// count is already 0 after reset, calling it again does nothing
cubit.reset;
cubit.reset; // no-op — state is already { count: 0 }
assert_eq!;
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.
use Cubit;
// This function knows nothing about CounterCubit specifically.
// Works with your real cubit
let mut real = new;
apply_n_increments;
assert_eq!;
// Works with a mock that records every emitted state — no code change needed
let mut mock = RecordingCubit ;
apply_n_increments;
assert_eq!;
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:
use ;
let mut cubit = new;
cubit.emit;
cubit.emit;
assert_eq!;
// Change detection built in
cubit.emit; // no-op
assert_eq!;
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.
use Cubit;
use cubit;
// Developer writes the state struct — full control over its shape
// One line — macro generates impl Cubit, new(), on_change()
// Usage — new() is generated
let mut cart = new;
cart.add_item;
cart.add_item;
assert_eq!;
assert_eq!;
With extra fields on the cubit — non-state fields stay on the struct; the generated new() takes them as additional leading parameters:
// Generated: pub fn new(step: i32, initial: CounterState) -> Self
let mut c = new;
c.advance;
assert_eq!;
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.
use Cubit;
use cubit;
// Macro generates:
// #[derive(Clone, PartialEq, Debug)]
// pub struct UserCubitState {
// pub name: String,
// pub is_verified: bool,
// }
// Generated: pub fn new(cache_ttl: u64, initial: UserCubitState) -> Self
let mut user = new;
user.verify;
assert!;
Mode B — simple toggle example:
let mut toggle = new;
toggle.toggle;
assert!;
toggle.toggle;
assert!;
Auto-Generated API
Both modes generate the following for every #[cubit] struct:
// 1. impl Cubit — type State, state(), emit() with change-detection
// 2. Constructor
// 3. Observer registration
on_change Observer
Subscribe to state transitions without touching rendering or business logic code:
use cubit;
let mut score = new;
// Register a logger
score.on_change;
// Register an analytics hook
score.on_change;
score.add; // fires both callbacks: "score → 60"
score.add; // fires both: "score → 110", "milestone reached: 110"
score.add; // 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:
no_observers example — backend / CLI cubit with no UI subscriptions:
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 0.7 desktop.
The cubit is stored in a Dioxus Signal — reads register the component as a subscriber, writes trigger re-renders.
// src/cubits/counter.rs — zero Dioxus imports, pure domain logic
use Cubit;
use cubit;
// src/main.rs — Dioxus wiring
use ;
use *;
use Cubit;
Run it:
Full example source: 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:
[]
= { = "0.1", = ["tracing"] }
= { = "0.1", = ["tracing"] }
= "0.1"
= "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
// Coming in v0.3
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
2. Create a focused branch
Branch names should describe the change clearly:
3. Make your changes
Run the full local check suite before every push — the same checks CI runs:
# Format (required — CI will reject unformatted code)
# Lint (required — warnings are treated as errors in CI)
# Tests (required — all must pass)
# Trybuild UI tests (required if you touched gloc-macro)
4. Open a Pull Request
- Target the
mainbranch - 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
@godwinjkwill 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):
Recommended before pushing a PR — run a clean build to make sure nothing relies on stale artifacts:
&&
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
pubitem (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
# Examplefor 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
Cubittrait implementations must include a trait-object (dyn Cubit<State = …>) test to confirm Dependency Inversion compatibility - New error paths in
gloc-macromust have a correspondingtrybuildfail case with a.stderrsnapshot
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
rustfmtis the style guide — no manual formatting discussions- Clippy is the linter — fix all warnings, do not
#[allow(...)]without a comment explaining why - No
unwrap()orexpect()in library code — return aResultor emit a compile-time error - Comments in source explain why, not what
Reporting Bugs
Open a GitHub Issue 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.
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.
📣 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 or 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.
💙 Donate via PayPal
Prefer PayPal? Donations of any amount are deeply appreciated and go directly toward GLOC development time.
🤝 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
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.
Built with Rust 🦀 — designed for everyone.
