mod-events 0.1.0

A high-performance, zero-overhead event dispatcher library for Rust
Documentation

Key Features

  • Zero-cost abstractions: No runtime overhead for event dispatch.
  • Type-safe: Compile-time guarantees for event handling.
  • Thread-safe: Built for concurrent applications.
  • Async support: Full async/await compatibility.
  • Flexible: Support for sync, async, and priority-based listeners.
  • Easy to use: Simple API and intuitive methods.
  • Performance: Optimized for high-throughput scenarios.
  • Monitoring: Built-in metrics and middleware support.

Quick Start

Add this to your Cargo.toml:

[dependencies]
mod-events = "0.1"

Basic Usage

use mod_events::prelude::*;

// Define your event
#[derive(Debug, Clone)]
struct UserRegistered {
    user_id: u64,
    email: String,
}

impl Event for UserRegistered {
    fn as_any(&self) -> &dyn std::any::Any {
        self
    }
}

// Create dispatcher and subscribe
let dispatcher = EventDispatcher::new();
dispatcher.on(|event: &UserRegistered| {
    println!("Welcome {}!", event.email);
});

// Dispatch events
dispatcher.emit(UserRegistered {
    user_id: 123,
    email: "alice@example.com".to_string(),
});

Features

Priority System

use mod_events::{EventDispatcher, Priority};

let dispatcher = EventDispatcher::new();

// High priority listener executes first
dispatcher.subscribe_with_priority(|event: &MyEvent| {
    println!("High priority handler");
    Ok(())
}, Priority::High);

// Normal priority listener executes second
dispatcher.on(|event: &MyEvent| {
    println!("Normal priority handler");
});

Async Support

// Enable with the "async" feature
dispatcher.subscribe_async(|event: &MyEvent| async {
    // Async processing
    tokio::time::sleep(Duration::from_millis(100)).await;
    println!("Async handler completed");
    Ok(())
});

let result = dispatcher.dispatch_async(MyEvent { /* ... */ }).await;

Middleware

// Add middleware for logging, filtering, etc.
dispatcher.add_middleware(|event: &dyn Event| {
    println!("Processing: {}", event.event_name());
    true // Allow event to continue
});

Error Handling

let result = dispatcher.dispatch(MyEvent { /* ... */ });

if result.all_succeeded() {
    println!("All handlers succeeded");
} else {
    for error in result.errors() {
        eprintln!("Handler error: {}", error);
    }
}

Examples

Run the examples:

cargo run --example basic_usage
cargo run --features async --example async_usage

Benchmarks

cargo test --release benchmark

Documentation