github.com/lmorg/murex@v0.0.0-20240217211045-e081c89cd4ef/builtins/core/open/agents.go (about) 1 package open 2 3 import ( 4 "errors" 5 "sync" 6 7 "github.com/lmorg/murex/lang/ref" 8 ) 9 10 // OpenAgents is the exported table of `open`'s helper functions 11 var OpenAgents = newOpenAgents() 12 13 var errNoAgent = errors.New("no agent set for that data type") 14 15 type openBlocks struct { 16 Block []rune 17 FileRef *ref.File 18 } 19 20 func newOpenAgents() *openAgents { 21 oa := new(openAgents) 22 oa.agents = make(map[string]*openBlocks) 23 return oa 24 } 25 26 type openAgents struct { 27 mutex sync.Mutex 28 agents map[string]*openBlocks 29 } 30 31 // Get the murex code block for a particular murex data type 32 func (oa *openAgents) Get(dataType string) (*openBlocks, error) { 33 oa.mutex.Lock() 34 ob := oa.agents[dataType] 35 oa.mutex.Unlock() 36 37 if ob == nil { 38 return nil, errNoAgent 39 } 40 41 return ob, nil 42 } 43 44 // Set the murex code block for a particular murex data type 45 func (oa *openAgents) Set(dataType string, block []rune, fileRef *ref.File) { 46 oa.mutex.Lock() 47 defer oa.mutex.Unlock() 48 49 oa.agents[dataType] = &openBlocks{ 50 Block: block, 51 FileRef: fileRef, 52 } 53 } 54 55 // Unset removes an associated code block for a particular data type 56 func (oa *openAgents) Unset(dataType string) error { 57 oa.mutex.Lock() 58 defer oa.mutex.Unlock() 59 60 if oa.agents[dataType] == nil { 61 return errNoAgent 62 } 63 64 oa.agents[dataType] = nil 65 return nil 66 } 67 68 // Dump returns the entire OpenAgent table 69 func (oa *openAgents) Dump() interface{} { 70 oa.mutex.Lock() 71 defer oa.mutex.Unlock() 72 73 type dumpedBlocks struct { 74 Block string 75 FileRef *ref.File 76 } 77 78 dump := make(map[string]dumpedBlocks) 79 for dt, ob := range oa.agents { 80 dump[dt] = dumpedBlocks{ 81 Block: string(ob.Block), 82 FileRef: ob.FileRef, 83 } 84 } 85 86 return dump 87 }