Skip to content

proposal: allow conversion of bools to numerics. #45341

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
docmerlin opened this issue Apr 1, 2021 · 3 comments
Closed

proposal: allow conversion of bools to numerics. #45341

docmerlin opened this issue Apr 1, 2021 · 3 comments

Comments

@docmerlin
Copy link

docmerlin commented Apr 1, 2021

A lot of branch-less algorithms are developed for c where a<b is 0 when false and 1 when true.

It would be really helpful to be able to use those algorithms by being able to have uint64(a<b) and it be uint64(0) or uint64(1) depending on a and b.

Note: this isn't an April fools proposal. (someone pointed out I should say this).

@gopherbot gopherbot added this to the Proposal milestone Apr 1, 2021
@seankhliao
Copy link
Member

Duplicate of #7657 #9367 #45320

@ianlancetaylor
Copy link
Contributor

It's important to not confuse an algorithm that is branchless in the Go code and an algorithm that is branchless in the generated machine code.

For example, when using the gccgo compiler, this Go function

func Cmp(a, b int) int {
	if a < b {
		return 0
	}
	return 1
}

compiles to this assembly code (ignoring the stack-splitting code):

	xorl	%eax, %eax
	cmpq	%rsi, %rdi
	setge	%al
	ret

@FiloSottile
Copy link
Contributor

Larger branches will not be made branchless by the compiler, and numeric booleans are usually used with subtle.ConstantTimeSelect. This is why the crypto/subtle and filippo.io/edwards25519 return 0 or 1 instead of false or true.

@golang golang locked and limited conversation to collaborators Apr 1, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

5 participants