From ecc8035f73f62424298d2a36dc2d747601fb04c8 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Fri, 11 Oct 2024 13:12:18 -0700 Subject: [PATCH] types/bools: add Compare to compare boolean values (#13792) The bools.Compare function compares boolean values by reporting -1, 0, +1 for ordering so that it can be easily used with slices.SortFunc. Updates #cleanup Updates tailscale/corp#11038 Signed-off-by: Joe Tsai --- types/bools/compare.go | 17 +++++++++++++++++ types/bools/compare_test.go | 21 +++++++++++++++++++++ 2 files changed, 38 insertions(+) create mode 100644 types/bools/compare.go create mode 100644 types/bools/compare_test.go diff --git a/types/bools/compare.go b/types/bools/compare.go new file mode 100644 index 000000000..ac433b240 --- /dev/null +++ b/types/bools/compare.go @@ -0,0 +1,17 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +// Package bools contains the bools.Compare function. +package bools + +// Compare compares two boolean values as if false is ordered before true. +func Compare[T ~bool](x, y T) int { + switch { + case x == false && y == true: + return -1 + case x == true && y == false: + return +1 + default: + return 0 + } +} diff --git a/types/bools/compare_test.go b/types/bools/compare_test.go new file mode 100644 index 000000000..280294621 --- /dev/null +++ b/types/bools/compare_test.go @@ -0,0 +1,21 @@ +// Copyright (c) Tailscale Inc & AUTHORS +// SPDX-License-Identifier: BSD-3-Clause + +package bools + +import "testing" + +func TestCompare(t *testing.T) { + if got := Compare(false, false); got != 0 { + t.Errorf("Compare(false, false) = %v, want 0", got) + } + if got := Compare(false, true); got != -1 { + t.Errorf("Compare(false, true) = %v, want -1", got) + } + if got := Compare(true, false); got != +1 { + t.Errorf("Compare(true, false) = %v, want +1", got) + } + if got := Compare(true, true); got != 0 { + t.Errorf("Compare(true, true) = %v, want 0", got) + } +}