github.com/15mga/kiwi@v0.0.2-0.20240324021231-b95d5c3ac751/util/enable.go (about) 1 package util 2 3 import ( 4 "sync" 5 ) 6 7 type Enable struct { 8 Mtx sync.RWMutex 9 disabled bool 10 } 11 12 func NewEnable() *Enable { 13 return &Enable{ 14 disabled: true, 15 } 16 } 17 18 func (e *Enable) Disabled() bool { 19 return e.disabled 20 } 21 22 func (e *Enable) RAction(fn FnAnySlc, params ...any) *Err { 23 if fn == nil { 24 return nil 25 } 26 e.Mtx.RLock() 27 if e.disabled { 28 e.Mtx.RUnlock() 29 return NewErr(EcClosed, nil) 30 } 31 fn(params) 32 e.Mtx.RUnlock() 33 return nil 34 } 35 36 func (e *Enable) WAction(fn FnAnySlc, params ...any) *Err { 37 if fn == nil { 38 return nil 39 } 40 e.Mtx.Lock() 41 if e.disabled { 42 e.Mtx.Unlock() 43 return NewErr(EcClosed, nil) 44 } 45 fn(params) 46 e.Mtx.Unlock() 47 return nil 48 } 49 50 func (e *Enable) WAction2(fn Fn) *Err { 51 if fn == nil { 52 return nil 53 } 54 e.Mtx.Lock() 55 if e.disabled { 56 e.Mtx.Unlock() 57 return NewErr(EcClosed, nil) 58 } 59 fn() 60 e.Mtx.Unlock() 61 return nil 62 } 63 64 func (e *Enable) Disable(fn FnAnySlc, params ...any) bool { 65 e.Mtx.Lock() 66 if e.disabled { 67 e.Mtx.Unlock() 68 return false 69 } 70 e.disabled = true 71 if fn != nil { 72 fn(params) 73 } 74 e.Mtx.Unlock() 75 return true 76 } 77 78 func (e *Enable) Enable(fn FnAnySlc, params ...any) bool { 79 e.Mtx.Lock() 80 if !e.disabled { 81 e.Mtx.Unlock() 82 return false 83 } 84 e.disabled = false 85 if fn != nil { 86 fn(params) 87 } 88 e.Mtx.Unlock() 89 return true 90 } 91 92 func (e *Enable) IfDisable(fn Fn) (ok bool) { 93 if fn == nil { 94 ok = true 95 return 96 } 97 e.Mtx.RLock() 98 if e.disabled { 99 ok = true 100 if fn != nil { 101 fn() 102 } 103 } 104 e.Mtx.RUnlock() 105 return 106 } 107 108 func (e *Enable) IfEnable(fn Fn) (ok bool) { 109 if fn == nil { 110 ok = true 111 return 112 } 113 e.Mtx.RLock() 114 if !e.disabled { 115 ok = true 116 if fn != nil { 117 fn() 118 } 119 } 120 e.Mtx.RUnlock() 121 return 122 }