github.com/aacfactory/fns@v1.2.86-0.20240310083819-80d667fc0a17/commons/switchs/switch.go (about)

     1  /*
     2   * Copyright 2023 Wang Min Xiang
     3   *
     4   * Licensed under the Apache License, Version 2.0 (the "License");
     5   * you may not use this file except in compliance with the License.
     6   * You may obtain a copy of the License at
     7   *
     8   * 	http://www.apache.org/licenses/LICENSE-2.0
     9   *
    10   * Unless required by applicable law or agreed to in writing, software
    11   * distributed under the License is distributed on an "AS IS" BASIS,
    12   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13   * See the License for the specific language governing permissions and
    14   * limitations under the License.
    15   *
    16   */
    17  
    18  package switchs
    19  
    20  import (
    21  	"sync/atomic"
    22  )
    23  
    24  type Switch struct {
    25  	value uint64
    26  }
    27  
    28  func (s *Switch) On() {
    29  	atomic.StoreUint64(&s.value, 2)
    30  }
    31  
    32  func (s *Switch) Off() {
    33  	atomic.StoreUint64(&s.value, 1)
    34  }
    35  
    36  func (s *Switch) Confirm() {
    37  	n := atomic.LoadUint64(&s.value)
    38  	switch n {
    39  	case 2:
    40  		atomic.StoreUint64(&s.value, 3)
    41  		break
    42  	case 1:
    43  		atomic.StoreUint64(&s.value, 0)
    44  		break
    45  	default:
    46  		break
    47  	}
    48  }
    49  
    50  func (s *Switch) IsOn() (ok bool, confirmed bool) {
    51  	n := atomic.LoadUint64(&s.value)
    52  	switch n {
    53  	case 2:
    54  		ok = true
    55  		break
    56  	case 3:
    57  		ok = true
    58  		confirmed = true
    59  		break
    60  	default:
    61  		break
    62  	}
    63  	return
    64  }
    65  
    66  func (s *Switch) IsOff() (ok bool, confirmed bool) {
    67  	n := atomic.LoadUint64(&s.value)
    68  	switch n {
    69  	case 1:
    70  		ok = true
    71  		break
    72  	case 0:
    73  		ok = true
    74  		confirmed = true
    75  		break
    76  	default:
    77  		break
    78  	}
    79  	return
    80  }