wasi-module-sdk-go/registry.go

66 lines
1.1 KiB
Go
Raw Normal View History

2023-05-08 13:21:31 +00:00
package sdk
import (
"sync"
)
2023-05-13 15:46:09 +00:00
type Reference struct {
Category Category
Type string
}
2023-05-08 13:21:31 +00:00
type Registration interface {
RegisterAt(registry *TypeRegistry)
}
type RegistrationFunc func(registry *TypeRegistry)
func (f RegistrationFunc) RegisterAt(registry *TypeRegistry) {
f(registry)
}
func NewTypeRegistry() *TypeRegistry {
return &TypeRegistry{
2023-08-15 19:46:02 +00:00
registrations: make(map[Reference]Factory),
2023-05-08 13:21:31 +00:00
}
}
type TypeRegistry struct {
lock sync.Mutex
2023-08-15 19:46:02 +00:00
registrations map[Reference]Factory
2023-05-08 13:21:31 +00:00
}
2023-05-13 15:46:09 +00:00
func (r *TypeRegistry) List() (refs []Reference) {
refs = make([]Reference, 0, len(r.registrations))
for k := range r.registrations {
2023-08-15 19:46:02 +00:00
refs = append(refs, k)
2023-05-13 15:46:09 +00:00
}
return refs
}
2023-05-08 13:21:31 +00:00
func (r *TypeRegistry) Add(cat Category, moduleName string, factory Factory) {
r.lock.Lock()
defer r.lock.Unlock()
r.registrations[specOf(cat, moduleName)] = factory
}
func (r *TypeRegistry) Get(cat Category, moduleName string) Module {
f, ok := r.registrations[specOf(cat, moduleName)]
if !ok {
return nil
}
return f.Create()
}
2023-08-15 19:46:02 +00:00
func specOf(cat Category, moduleName string) Reference {
return Reference{
Category: cat,
Type: moduleName,
}
2023-05-08 13:21:31 +00:00
}