atomic_bool_go118.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. // Go MySQL Driver - A MySQL-Driver for Go's database/sql package.
  2. //
  3. // Copyright 2022 The Go-MySQL-Driver Authors. All rights reserved.
  4. //
  5. // This Source Code Form is subject to the terms of the Mozilla Public
  6. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  7. // You can obtain one at http://mozilla.org/MPL/2.0/.
  8. //go:build !go1.19
  9. // +build !go1.19
  10. package mysql
  11. import "sync/atomic"
  12. /******************************************************************************
  13. * Sync utils *
  14. ******************************************************************************/
  15. // atomicBool is an implementation of atomic.Bool for older version of Go.
  16. // it is a wrapper around uint32 for usage as a boolean value with
  17. // atomic access.
  18. type atomicBool struct {
  19. _ noCopy
  20. value uint32
  21. }
  22. // Load returns whether the current boolean value is true
  23. func (ab *atomicBool) Load() bool {
  24. return atomic.LoadUint32(&ab.value) > 0
  25. }
  26. // Store sets the value of the bool regardless of the previous value
  27. func (ab *atomicBool) Store(value bool) {
  28. if value {
  29. atomic.StoreUint32(&ab.value, 1)
  30. } else {
  31. atomic.StoreUint32(&ab.value, 0)
  32. }
  33. }
  34. // Swap sets the value of the bool and returns the old value.
  35. func (ab *atomicBool) Swap(value bool) bool {
  36. if value {
  37. return atomic.SwapUint32(&ab.value, 1) > 0
  38. }
  39. return atomic.SwapUint32(&ab.value, 0) > 0
  40. }