56 lines
928 B
Go
56 lines
928 B
Go
package events
|
|
|
|
import (
|
|
"fmt"
|
|
"reflect"
|
|
)
|
|
|
|
type EventType = string
|
|
|
|
type IEvent interface {
|
|
Typ() EventType
|
|
Data(ref any) error
|
|
}
|
|
|
|
func NewEvent[T any](typ EventType, data ...T) IEvent {
|
|
var d T
|
|
if len(data) > 0 {
|
|
d = data[0]
|
|
}
|
|
ev := &event[T]{
|
|
typ: typ,
|
|
data: d,
|
|
}
|
|
return ev
|
|
}
|
|
|
|
type event[T any] struct {
|
|
typ EventType
|
|
data T
|
|
}
|
|
|
|
func (event *event[T]) Typ() EventType {
|
|
return event.typ
|
|
}
|
|
|
|
func (event *event[T]) Data(ref any) error {
|
|
val := reflect.ValueOf(ref)
|
|
if val.Kind() != reflect.Ptr {
|
|
return fmt.Errorf("need Pointer to get Event Data")
|
|
}
|
|
|
|
valElem := val.Elem()
|
|
if !valElem.CanSet() {
|
|
return fmt.Errorf("cannot set value of the provided pointer")
|
|
}
|
|
|
|
dataType := reflect.TypeOf(event.data)
|
|
if valElem.Type() != dataType {
|
|
return fmt.Errorf("type mismatch: expected %s, got %s", dataType.String(), valElem.Type().String())
|
|
}
|
|
|
|
valElem.Set(reflect.ValueOf(event.data))
|
|
|
|
return nil
|
|
}
|