Skip to content
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

Unexpected behavior when using BitVector as index #142

Open
leonardt opened this issue Oct 15, 2020 · 1 comment
Open

Unexpected behavior when using BitVector as index #142

leonardt opened this issue Oct 15, 2020 · 1 comment

Comments

@leonardt
Copy link
Owner

Not sure if this is something we want to support, since a workaround is to just call int on the BV index value (but then maybe we should add an error check).

Here's an example:

from hwtypes import BitVector, Bit

idx = BitVector.random(2)
x = BitVector.random(4)
x[idx] = Bit.random()

This will always raise the following error:

    def __setitem__(self, index, value):
        if isinstance(index, slice):
            raise NotImplementedError()
        else:
            if not (isinstance(value, bool) or isinstance(value, Bit) or (isinstanc
e(value, int) and value in {0, 1})):
                raise ValueError("Second argument __setitem__ on a single BitVector
 index should be a boolean or 0 or 1, not {value}".format(value=value))

            if index < 0:
                index = self.size+index

            if not (0 <= index < self.size):
>               raise IndexError()
E               IndexError

The reason is that when doing idx < self.size we get an overflow in the less than operator, so it always evaluates to false (since no BV[2] will be less than 0), here's an example:

from hwtypes import BitVector, Bit

idx = BitVector.random(2)
print(idx)
print(0 <= idx)
print(idx < 4)
print(0 <= idx < 4)

will produce

3
Bit(True)
Bit(False)
Bit(False)

If we want to support a BV index, we probably just need to do some extension logic to catch the overflow case in the comparison.

@leonardt
Copy link
Owner Author

Generally using a BitVector as a key to set/getitem like this is probably problematic for general objects (since I'd imagine most interfaces expect an int type that will certainly behave differently than a BV in some cases)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant