bools.go 831 B

12345678910111213141516171819202122232425262728293031323334353637
  1. // Copyright (c) Tailscale Inc & contributors
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. // Package bools contains the [Int], [Compare], and [IfElse] functions.
  4. package bools
  5. // Int returns 1 for true and 0 for false.
  6. func Int(v bool) int {
  7. if v {
  8. return 1
  9. } else {
  10. return 0
  11. }
  12. }
  13. // Compare compares two boolean values as if false is ordered before true.
  14. func Compare[T ~bool](x, y T) int {
  15. switch {
  16. case x == false && y == true:
  17. return -1
  18. case x == true && y == false:
  19. return +1
  20. default:
  21. return 0
  22. }
  23. }
  24. // IfElse is a ternary operator that returns trueVal if condExpr is true
  25. // otherwise it returns falseVal.
  26. // IfElse(c, a, b) is roughly equivalent to (c ? a : b) in languages like C.
  27. func IfElse[T any](condExpr bool, trueVal T, falseVal T) T {
  28. if condExpr {
  29. return trueVal
  30. } else {
  31. return falseVal
  32. }
  33. }