aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
author2026-01-24 17:56:58 +0300
committer2026-01-24 17:56:58 +0300
commit9fb220096a8a50bd89f0d7578d572629531f8141 (patch)
treed454c0efc1268cc0c15384d2a4585312562a1c0c
parentv1.0.0 (diff)
downloadeventbus-9fb220096a8a50bd89f0d7578d572629531f8141.tar.gz
eventbus-9fb220096a8a50bd89f0d7578d572629531f8141.tar.bz2
eventbus-9fb220096a8a50bd89f0d7578d572629531f8141.tar.xz
eventbus-9fb220096a8a50bd89f0d7578d572629531f8141.zip
v1.0.1v1.0.1
-rw-r--r--README.md76
-rw-r--r--bus.go20
-rw-r--r--opts.go11
3 files changed, 70 insertions, 37 deletions
diff --git a/README.md b/README.md
index 2ec98d8..6f777fe 100644
--- a/README.md
+++ b/README.md
@@ -1,18 +1,26 @@
# eventbus - Асинхронная шина событий для Go
-[![License: GPL v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
+[![License: GPL
+v3](https://img.shields.io/badge/License-GPLv3-blue.svg)](https://www.gnu.org/licenses/gpl-3.0)
[English version below](#english-version)
-`eventbus` - это реализация асинхронной шины событий для языка программирования Go. Библиотека предоставляет механизм публикации и подписки на события с использованием trie-структуры для эффективного управления подписками.
+`eventbus` - это реализация асинхронной шины событий для языка программирования
+Go. Библиотека предоставляет механизм публикации и подписки на события с
+использованием trie-структуры для эффективного управления подписками.
## Особенности
-- **Trie-структура**: Использует префиксное дерево для хранения подписок, что обеспечивает эффективный поиск подписчиков
-- **Конфигурируемость**: Поддерживает настройку разделителя имен и символа wildcard через опции конструктора
-- **Асинхронная доставка**: События доставляются подписчикам асинхронно, что предотвращает блокировку отправителя
-- **Потокобезопасность**: Все операции синхронизированы с использованием `sync.RWMutex`
-- **Обобщения**: Реализована с использованием обобщений Go 1.18+, что позволяет использовать любые сравнимые типы
+- **Trie-структура**: Использует префиксное дерево для хранения подписок, что
+ обеспечивает эффективный поиск подписчиков
+- **Конфигурируемость**: Поддерживает настройку разделителя имен и символа
+ wildcard через опции конструктора
+- **Асинхронная доставка**: События доставляются подписчикам асинхронно, что
+ предотвращает блокировку отправителя
+- **Потокобезопасность**: Все операции синхронизированы с использованием
+ `sync.RWMutex`
+- **Обобщения**: Реализована с использованием обобщений Go 1.18+, что позволяет
+ использовать любые сравнимые типы
## Установка
@@ -95,15 +103,18 @@ func main() {
### `func New(opts ...Opt) *bus`
-Создает новую шину событий с опциональными настройками. Поддерживает следующие опции:
+Создает новую шину событий с опциональными настройками. Поддерживает следующие
+опции:
- `NameSeparator` - задает разделитель имен событий (по умолчанию ".")
-- `Wildcard` - задает символ wildcard для подписок (по умолчанию "*")
-- `Capacity` - задает начальную емкость для каналов подписчиков (по умолчанию 32)
+- `Wildcard` - задает символ wildcard для подписок (по умолчанию "\*")
+- `Capacity` - задает начальную емкость для узлов дерева подписчиков (по
+ умолчанию 32)
### `func (b *bus) Subscribe(path string) Listener`
-Подписывается на событие по указанному пути. Возвращает канал-подписчик для получения событий.
+Подписывается на событие по указанному пути. Возвращает канал-подписчик для
+получения событий.
### `func (b *bus) Unsubscribe(l Listener)`
@@ -115,11 +126,13 @@ func main() {
### `func (b *bus) Fire(ev Event)`
-Отправляет событие всем подписчикам, которые подписаны на соответствующий путь события.
+Отправляет событие всем подписчикам, которые подписаны на соответствующий путь
+события.
## Лицензия
-Этот проект лицензирован в соответствии с GNU General Public License версии 3 (GPLv3). Подробности смотрите в файле [LICENSE](LICENSE).
+Этот проект лицензирован в соответствии с GNU General Public License версии 3
+(GPLv3). Подробности смотрите в файле [LICENSE](LICENSE).
```
GNU GENERAL PUBLIC LICENSE
@@ -132,20 +145,27 @@ func main() {
## Ссылки
-- **Репозиторий**: [https://gitrepo.ru/NeonXP/eventbus.git](https://gitrepo.ru/NeonXP/eventbus.git)
+- **Репозиторий**:
+ [https://gitrepo.ru/NeonXP/eventbus.git](https://gitrepo.ru/NeonXP/eventbus.git)
- **Автор**: Alexander NeonXP Kiryukhin <i@neonxp.ru>
# English Version
-`eventbus` is an implementation of an asynchronous event bus for the Go programming language. The library provides a publish-subscribe mechanism for events using a trie structure for efficient subscription management.
+`eventbus` is an implementation of an asynchronous event bus for the Go
+programming language. The library provides a publish-subscribe mechanism for
+events using a trie structure for efficient subscription management.
## Features
-- **Trie structure**: Uses a prefix tree to store subscriptions, providing efficient subscriber lookup
-- **Configurable**: Supports configuration of name separator and wildcard character through constructor options
-- **Asynchronous delivery**: Events are delivered to subscribers asynchronously, preventing sender blocking
+- **Trie structure**: Uses a prefix tree to store subscriptions, providing
+ efficient subscriber lookup
+- **Configurable**: Supports configuration of name separator and wildcard
+ character through constructor options
+- **Asynchronous delivery**: Events are delivered to subscribers asynchronously,
+ preventing sender blocking
- **Thread-safe**: All operations are synchronized using `sync.RWMutex`
-- **Generics**: Implemented using Go 1.18+ generics, allowing any comparable types
+- **Generics**: Implemented using Go 1.18+ generics, allowing any comparable
+ types
## Installation
@@ -231,12 +251,13 @@ func main() {
Creates a new event bus with optional settings. Supports the following options:
- `NameSeparator` - sets the event name separator (default ".")
-- `Wildcard` - sets the wildcard character for subscriptions (default "*")
-- `Capacity` - sets the initial capacity for listener channels (default 32)
+- `Wildcard` - sets the wildcard character for subscriptions (default "\*")
+- `Capacity` - sets the initial capacity for listeners trie (default 32)
### `func (b *bus) Subscribe(path string) Listener`
-Subscribes to an event at the specified path. Returns a listener channel for receiving events.
+Subscribes to an event at the specified path. Returns a listener channel for
+receiving events.
### `func (b *bus) Unsubscribe(l Listener)`
@@ -248,11 +269,13 @@ Closes the event bus and all listener channels.
### `func (b *bus) Fire(ev Event)`
-Fires an event to all subscribers who are subscribed to the corresponding event path.
+Fires an event to all subscribers who are subscribed to the corresponding event
+path.
## License
-This project is licensed under the GNU General Public License version 3 (GPLv3). See the [LICENSE](LICENSE) file for details.
+This project is licensed under the GNU General Public License version 3 (GPLv3).
+See the [LICENSE](LICENSE) file for details.
```
GNU GENERAL PUBLIC LICENSE
@@ -265,5 +288,6 @@ This project is licensed under the GNU General Public License version 3 (GPLv3).
## Links
-- **Repository**: [https://gitrepo.ru/NeonXP/eventbus.git](https://gitrepo.ru/NeonXP/eventbus.git)
-- **Author**: Alexander NeonXP Kiryukhin <i@neonxp.ru> \ No newline at end of file
+- **Repository**:
+ [https://gitrepo.ru/NeonXP/eventbus.git](https://gitrepo.ru/NeonXP/eventbus.git)
+- **Author**: Alexander NeonXP Kiryukhin <i@neonxp.ru>
diff --git a/bus.go b/bus.go
index 7ce4860..9ab1980 100644
--- a/bus.go
+++ b/bus.go
@@ -10,7 +10,7 @@ const (
defaultCapacity = 32
)
-type bus struct {
+type Bus struct {
noCopy
listeners node[Listener]
@@ -18,8 +18,8 @@ type bus struct {
wildcard string
}
-func New(opts ...Opt) *bus {
- b := &bus{
+func New(opts ...Opt) *Bus {
+ b := &Bus{
nameSeparator: ".",
wildcard: "*",
}
@@ -44,25 +44,31 @@ type Event interface {
Event() string
}
-func (b *bus) Subscribe(path string) Listener {
+// Subscribe to an event at the specified path. Returns a listener channel for
+// receiving events.
+func (b *Bus) Subscribe(path string) Listener {
splitedPath := strings.Split(path, b.nameSeparator)
ch := make(Listener, 1)
b.listeners.Put(splitedPath, ch)
return ch
}
-func (b *bus) Unsubscribe(l Listener) {
+// Unsubscribe from an event and closes the listener channel.
+func (b *Bus) Unsubscribe(l Listener) {
close(l)
b.listeners.Remove(l)
}
-func (b *bus) Close() {
+// Close the event bus and all listener channels.
+func (b *Bus) Close() {
b.listeners.Clear(func(value Listener) {
close(value)
})
}
-func (b *bus) Fire(ev Event) {
+// Fire an event to all subscribers who are subscribed to the corresponding
+// event path.
+func (b *Bus) Fire(ev Event) {
splitedEventName := strings.Split(ev.Event(), b.nameSeparator)
listeners := b.listeners.Get(splitedEventName, b.wildcard)
diff --git a/opts.go b/opts.go
index 620e263..905c193 100644
--- a/opts.go
+++ b/opts.go
@@ -1,24 +1,27 @@
package eventbus
type Opt interface {
- Apply(b *bus)
+ Apply(b *Bus)
}
+// NameSeparator sets the event name separator (default ".").
type NameSeparator string
-func (n NameSeparator) Apply(b *bus) {
+func (n NameSeparator) Apply(b *Bus) {
b.nameSeparator = string(n)
}
+// Wildcard sets the wildcard character for subscriptions (default "*").
type Wildcard string
-func (w Wildcard) Apply(b *bus) {
+func (w Wildcard) Apply(b *Bus) {
b.wildcard = string(w)
}
+// Capacity sets the initial capacity for listeners trie (default 32).
type Capacity int
-func (c Capacity) Apply(b *bus) {
+func (c Capacity) Apply(b *Bus) {
b.listeners = node[Listener]{
children: make(map[string]*node[Listener], c),
values: make([]Listener, 0, c),