code.icb4dc0.de/buildr/wasi-module-sdk-go@v0.0.0-20230524201105-cc52d195017b/registry.go (about)

     1  package sdk
     2  
     3  import (
     4  	"fmt"
     5  	"strings"
     6  	"sync"
     7  )
     8  
     9  type Reference struct {
    10  	Category Category
    11  	Type     string
    12  }
    13  
    14  type Registration interface {
    15  	RegisterAt(registry *TypeRegistry)
    16  }
    17  
    18  type RegistrationFunc func(registry *TypeRegistry)
    19  
    20  func (f RegistrationFunc) RegisterAt(registry *TypeRegistry) {
    21  	f(registry)
    22  }
    23  
    24  func NewTypeRegistry() *TypeRegistry {
    25  	return &TypeRegistry{
    26  		registrations: make(map[string]Factory),
    27  	}
    28  }
    29  
    30  type TypeRegistry struct {
    31  	lock          sync.Mutex
    32  	registrations map[string]Factory
    33  }
    34  
    35  func (r *TypeRegistry) List() (refs []Reference) {
    36  	refs = make([]Reference, 0, len(r.registrations))
    37  
    38  	for k := range r.registrations {
    39  		split := strings.SplitN(k, "/", 2)
    40  		if len(split) < 2 {
    41  			continue
    42  		}
    43  
    44  		refs = append(refs, Reference{
    45  			Category: Category(split[0]),
    46  			Type:     split[1],
    47  		})
    48  	}
    49  
    50  	return refs
    51  }
    52  
    53  func (r *TypeRegistry) Add(cat Category, moduleName string, factory Factory) {
    54  	r.lock.Lock()
    55  	defer r.lock.Unlock()
    56  
    57  	r.registrations[specOf(cat, moduleName)] = factory
    58  }
    59  
    60  func (r *TypeRegistry) Get(cat Category, moduleName string) Module {
    61  	f, ok := r.registrations[specOf(cat, moduleName)]
    62  	if !ok {
    63  		return nil
    64  	}
    65  
    66  	return f.Create()
    67  }
    68  
    69  func specOf(cat Category, moduleName string) string {
    70  	return fmt.Sprintf("%s/%s", cat.String(), moduleName)
    71  }