Rust Guards Guide¶
The Guard Trait¶
All guards implement the Guard trait:
pub trait Guard: Send + Sync {
fn name(&self) -> &str;
fn check(&self, content: &str) -> GuardCheckResult;
fn action(&self) -> GuardAction;
fn severity_threshold(&self) -> Severity { Severity::Low }
}
Using the Derive Macro¶
The #[derive(Guard)] macro auto-generates the trait implementation.
Field Detection¶
The macro inspects your struct fields:
| Field | Type | Generated Method |
|---|---|---|
name |
String |
fn name() -> &str { &self.name } |
action |
GuardAction |
fn action() -> GuardAction { self.action } |
severity_threshold |
Severity |
fn severity_threshold() -> Severity { self.severity_threshold } |
Missing fields get defaults:
- No name → uses snake_case of struct name
- No action → defaults to GuardAction::Block
- No severity_threshold → defaults to Severity::Low
Attributes¶
Use #[guard(name = "...")] to set a fixed name:
The guard_check Method¶
You must implement guard_check(&self, content: &str) -> GuardCheckResult. The macro's generated check() delegates to this method:
GuardCheckResult¶
Use the convenience constructors:
// Content is safe
GuardCheckResult::pass("guard_name")
// Content is flagged
GuardCheckResult::fail("guard_name", GuardAction::Block, matches, "reason")
// With sanitized content
GuardCheckResult::fail(...).with_sanitized("cleaned content".to_string())
GuardAction Options¶
| Action | Description |
|---|---|
Allow |
Content passes through |
Block |
Content is blocked (default) |
Sanitize |
Content is cleaned/redacted |
Log |
Content is logged but allowed |
Alert |
Alert is raised but content allowed |
Suggest |
Suggestion provided, no blocking |
Severity Levels¶
| Level | Score | Use Case |
|---|---|---|
Info |
0 | Informational only |
Low |
1 | Minor issues |
Medium |
2 | Standard threats (default) |
High |
3 | Significant threats |
Critical |
4 | Severe threats requiring immediate action |
Utilities¶
The utils module provides text processing helpers:
use oxide_guard_sdk::utils;
let tokens = utils::tokenize("Hello, World!");
// ["hello", "world"]
let normalized = utils::normalize(" Hello World ");
// "hello world"
let matched = utils::pattern_match("Hello World", "hel*rld");
// true
let score = utils::similarity("hello world", "hello earth");
// 0.333...