github.com/asynkron/protoactor-go@v0.0.0-20240308120642-ef91a6abee75/actor/behavior.go (about) 1 package actor 2 3 import ( 4 "log/slog" 5 ) 6 7 type Behavior []ReceiveFunc 8 9 func NewBehavior() Behavior { 10 return make(Behavior, 0) 11 } 12 13 func (b *Behavior) Become(receive ReceiveFunc) { 14 b.clear() 15 b.push(receive) 16 } 17 18 func (b *Behavior) BecomeStacked(receive ReceiveFunc) { 19 b.push(receive) 20 } 21 22 func (b *Behavior) UnbecomeStacked() { 23 b.pop() 24 } 25 26 func (b *Behavior) Receive(context Context) { 27 behavior, ok := b.peek() 28 if ok { 29 behavior(context) 30 } else { 31 context.Logger().Error("empty behavior called", slog.Any("pid", context.Self())) 32 } 33 } 34 35 func (b *Behavior) clear() { 36 if len(*b) == 0 { 37 return 38 } 39 40 for i := range *b { 41 (*b)[i] = nil 42 } 43 44 *b = (*b)[:0] 45 } 46 47 func (b *Behavior) peek() (v ReceiveFunc, ok bool) { 48 if l := b.len(); l > 0 { 49 ok = true 50 v = (*b)[l-1] 51 } 52 53 return 54 } 55 56 func (b *Behavior) push(v ReceiveFunc) { 57 *b = append(*b, v) 58 } 59 60 func (b *Behavior) pop() (v ReceiveFunc, ok bool) { 61 if l := b.len(); l > 0 { 62 l-- 63 64 ok = true 65 v = (*b)[l] 66 (*b)[l] = nil 67 *b = (*b)[:l] 68 } 69 70 return 71 } 72 73 func (b *Behavior) len() int { 74 return len(*b) 75 }