gitee.com/sy_183/go-common@v1.0.5-0.20231205030221-958cfe129b47/lifecycle/state.go (about) 1 package lifecycle 2 3 import ( 4 "strings" 5 ) 6 7 const ( 8 StateClosed = State(iota) 9 StateStarting 10 StateRunning 11 StateClosing 12 ) 13 14 type StateInfo struct { 15 State State 16 UpperName string 17 LowerName string 18 } 19 20 var StateInfos = []StateInfo{ 21 {State: StateClosed, UpperName: "CLOSED"}, 22 {State: StateStarting, UpperName: "STARTING"}, 23 {State: StateRunning, UpperName: "RUNNING"}, 24 {State: StateClosing, UpperName: "CLOSING"}, 25 } 26 27 func init() { 28 for i := range StateInfos { 29 StateInfos[i].LowerName = strings.ToLower(StateInfos[i].UpperName) 30 } 31 } 32 33 type State int 34 35 func (s State) Closed() bool { 36 return s == StateClosed 37 } 38 39 func (s State) Starting() bool { 40 return s == StateStarting 41 } 42 43 func (s State) Running() bool { 44 return s == StateRunning 45 } 46 47 func (s State) Closing() bool { 48 return s == StateClosing 49 } 50 51 func (s State) String() string { 52 for _, info := range StateInfos { 53 if s == info.State { 54 return info.UpperName 55 } 56 } 57 return "UNKNOWN" 58 } 59 60 func (s State) check() { 61 if s > StateClosing { 62 panic(NewUnknownStateError("", s)) 63 } 64 } 65 66 func (s *State) ToClosed() { 67 s.check() 68 *s = StateClosed 69 } 70 71 func (s *State) ToStarting() { 72 s.check() 73 if s.Running() { 74 panic(NewStateNotAllowSwitchError("", StateRunning.String(), StateStarting.String())) 75 } 76 *s = StateStarting 77 } 78 79 func (s *State) ToRunning() { 80 s.check() 81 *s = StateRunning 82 } 83 84 func (s *State) ToClosing() { 85 s.check() 86 if s.Closed() { 87 panic(NewStateNotAllowSwitchError("", StateClosed.String(), StateClosing.String())) 88 } 89 *s = StateClosing 90 }