go-vise

Constrained Size Output Virtual Machine
Info | Log | Files | Refs | README | LICENSE

mem.go (1629B)


      1 package resource
      2 
      3 import (
      4 	"context"
      5 	"fmt"
      6 )
      7 
      8 type MemResource struct {
      9 	MenuResource
     10 	templates map[string]string
     11 	bytecodes map[string][]byte
     12 	menus map[string]string
     13 	funcs map[string]EntryFunc
     14 }
     15 
     16 func NewMemResource() MemResource {
     17 	mr := MemResource{
     18 		templates: make(map[string]string),
     19 		bytecodes: make(map[string][]byte),
     20 		funcs: make(map[string]EntryFunc),
     21 	}
     22 	mr.WithCodeGetter(mr.getCode)
     23 	mr.WithTemplateGetter(mr.getTemplate)
     24 	mr.WithEntryFuncGetter(mr.getFunc)
     25 	mr.WithMenuGetter(mr.getMenu)
     26 	return mr
     27 }
     28 
     29 func(mr MemResource) getTemplate(ctx context.Context, sym string) (string, error) {
     30 	r, ok := mr.templates[sym]
     31 	if !ok {
     32 		return "", fmt.Errorf("unknown template symbol: %s", sym)
     33 	}
     34 	return r, nil
     35 }
     36 
     37 func(mr MemResource) getCode(sym string) ([]byte, error) {
     38 	r, ok := mr.bytecodes[sym]
     39 	if !ok {
     40 		return nil, fmt.Errorf("unknown bytecode: %s", sym)
     41 	}
     42 	return r, nil
     43 }
     44 
     45 func(mr MemResource) getMenu(ctx context.Context, sym string) (string, error) {
     46 	r, ok := mr.menus[sym]
     47 	if !ok {
     48 		r = sym
     49 	}
     50 	return r, nil
     51 
     52 }
     53 
     54 func(mr MemResource) getFunc(sym string) (EntryFunc, error) {
     55 	r, ok := mr.funcs[sym]
     56 	if !ok {
     57 		return nil, fmt.Errorf("unknown entry func: %s", sym)
     58 	}
     59 	return r, nil
     60 }
     61 
     62 func(mr *MemResource) AddTemplate(sym string, tpl string) {
     63 	Logg.Tracef("mem resource added template", "sym", sym, "length", len(tpl))
     64 	mr.templates[sym] = tpl
     65 }
     66 
     67 
     68 func(mr *MemResource) AddEntryFunc(sym string, fn EntryFunc) {
     69 	mr.funcs[sym] = fn
     70 }
     71 
     72 func(mr *MemResource) AddBytecode(sym string, code []byte) {
     73 	Logg.Tracef("mem resource added bytecode", "sym", sym, "code", code)
     74 	mr.bytecodes[sym] = code
     75 }