Skip to content

Commit

Permalink
feat(router): add more routers (#24)
Browse files Browse the repository at this point in the history
  • Loading branch information
fu050409 authored Oct 27, 2024
1 parent 48f23cf commit 1afc5a0
Show file tree
Hide file tree
Showing 2 changed files with 100 additions and 2 deletions.
5 changes: 5 additions & 0 deletions .changes/routers.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"aionbot-core": patch:feat
---

Add more internal routers.
97 changes: 95 additions & 2 deletions crates/aionbot-core/src/router.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
use rayon::iter::{IntoParallelRefIterator, ParallelIterator};

use crate::event::Event;

pub trait Router: Send + Sync {
Expand Down Expand Up @@ -69,11 +71,102 @@ where
}
}

pub struct ContainsRouter<T>
where
T: Send + Sync + AsRef<str> + 'static,
{
pub pattern: T,
}

impl Router for ContainsRouter<&str> {
fn matches(&self, event: &dyn Event) -> bool {
if let Ok(val) = event.content().downcast::<&str>() {
val.contains(self.pattern)
} else {
false
}
}
}

impl<T> ContainsRouter<T>
where
T: Send + Sync + AsRef<str> + 'static,
{
pub fn new(pattern: T) -> Self {
Self { pattern }
}
}

pub struct EndsWithRouter<T>
where
T: Send + Sync + AsRef<str> + 'static,
{
pub pattern: T,
}

impl Router for EndsWithRouter<&str> {
fn matches(&self, event: &dyn Event) -> bool {
if let Ok(val) = event.content().downcast::<&str>() {
val.ends_with(self.pattern)
} else {
false
}
}
}

impl<T> EndsWithRouter<T>
where
T: Send + Sync + AsRef<str> + 'static,
{
pub fn new(pattern: T) -> Self {
Self { pattern }
}
}

#[derive(Default)]
pub struct AnyRouter;
pub struct AllRouter;

impl Router for AnyRouter {
impl Router for AllRouter {
fn matches(&self, _event: &dyn Event) -> bool {
true
}
}

pub struct AnyRouter {
pub routers: Vec<Box<dyn Router>>,
}

impl Router for AnyRouter {
fn matches(&self, event: &dyn Event) -> bool {
self.routers.par_iter().any(|r| r.matches(event))
}
}

impl AnyRouter {
pub fn new(routers: Vec<Box<dyn Router>>) -> Self {
Self { routers }
}
}

pub struct CommandRouter {
pub prefixes: Vec<String>,
pub command: String,
}

impl Router for CommandRouter {
fn matches(&self, event: &dyn Event) -> bool {
if let Ok(val) = event.content().downcast::<&str>() {
for prefix in &self.prefixes {
if val.starts_with(prefix) {
let command = val.strip_prefix(prefix).unwrap();
if command == self.command {
return true;
}
}
}
false
} else {
false
}
}
}

0 comments on commit 1afc5a0

Please sign in to comment.