From 8b347060f84f7dffc7b4e8e3781e7e66d110b148 Mon Sep 17 00:00:00 2001 From: Joe Tsai Date: Tue, 11 Feb 2025 10:23:36 -0800 Subject: [PATCH] types/bool: add Int (#14984) Add Int which converts a bool into an integer. Updates tailscale/corp#22024 Signed-off-by: Joe Tsai --- types/bools/bools.go | 11 ++++++++++- types/bools/bools_test.go | 9 +++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/types/bools/bools.go b/types/bools/bools.go index 962e39919..7cef17cf0 100644 --- a/types/bools/bools.go +++ b/types/bools/bools.go @@ -1,9 +1,18 @@ // Copyright (c) Tailscale Inc & AUTHORS // SPDX-License-Identifier: BSD-3-Clause -// Package bools contains the [Compare] and [Select] functions. +// Package bools contains the [Int], [Compare], and [Select] functions. package bools +// Int returns 1 for true and 0 for false. +func Int(v bool) int { + if v { + return 1 + } else { + return 0 + } +} + // Compare compares two boolean values as if false is ordered before true. func Compare[T ~bool](x, y T) int { switch { diff --git a/types/bools/bools_test.go b/types/bools/bools_test.go index 1b466db17..67faf3bcc 100644 --- a/types/bools/bools_test.go +++ b/types/bools/bools_test.go @@ -5,6 +5,15 @@ import "testing" +func TestInt(t *testing.T) { + if got := Int(true); got != 1 { + t.Errorf("Int(true) = %v, want 1", got) + } + if got := Int(false); got != 0 { + t.Errorf("Int(false) = %v, want 0", got) + } +} + func TestCompare(t *testing.T) { if got := Compare(false, false); got != 0 { t.Errorf("Compare(false, false) = %v, want 0", got)