bitset: to panic or not to panic, that is the question

New() intercepts a panic in defer() of makeslice and at least for this reason New() is not inlineable and therefore the slice always escapes to the heap. Currently I work around this with From(buffer) but would it also be possible that a MustNew(int) is possibly inlineable if it just propagates the panic.

About this issue

  • Original URL
  • State: closed
  • Created 2 years ago
  • Comments: 18 (17 by maintainers)

Most upvoted comments

@lukesandberg

Just a random note. I wanted to use the Len() function to recover the value i passed to New instead of passing it around separately. But this issue demonstrated that that was unsafe… not a big deal in my case… and not a spec issue really since it is documented as a ‘hint’, but a stronger guarantee here would be nice.

Fundamentally, the call to New is allocating and can thus panic.

The Len function is trivial:

func (b *BitSet) Len() uint {
	return b.length
}

The New function is effectively just…

	bset = &BitSet{
		length,
		make([]uint64, wordsNeeded(length)),
	}

	return bset

The only difference is that we recover on a panic caused by a lack of memory when the make function is called.

So the only case that matters is the one where you ask for a slice that Go cannot create.

In that case, instead of doing nothing (which would just cause a panic in your code which you would need to handle), we set the length to zero and use a zero slice.

To be clear, in Go, the following is not guaranteed to work…

x := make([]uint64, somelength)
fmt.Println(len(x))

If somelength is an arbitary value, the call to make may fail. This has nothing to do with the library, it is part of the Go language.

You can try it out with this program:

package main

import "fmt"

func main() {
        x := make([]uint64, 9223372036854775807)
        fmt.Println(len(x))
}

It should panic. So the line fmt.Println(len(x)) is never called.

Our API can change but it would change the semantics of the code, so we need to make sure that the users are made aware of the change… otherwise we risk creating unexpected bugs in existing code.

@gaissmai

I no longer use bitset.New, but take the zero value b := &bitset.BitSet{} and, if I know the maximum length l, followed by b.Set(l).Clear(l)

You know this, but for people reading these comments… The code (b.Set(l).Clear(l)) may panic if l is an arbitrary integer. Thus, in general, if you do not want to have a panic, and you cannot control what l is, you should have a defer in your code.

Sure, pull request invited.