codon icon indicating copy to clipboard operation
codon copied to clipboard

Cannot set the bits of UInt data with __setitem__.

Open iSunfield opened this issue 1 year ago • 1 comments

I tried to implement code to extend the UInt[N] class to set a specific bit of UInt[N] type data, but it seems that the setitem argument, self, is given a copy of the UInt[N] data as an argument, so the setitem function I could not set a specific bit of UInt[N] type data. After checking with the following simple code, it seems that the cause is that the address of the A variable and the address of self in setitem are different. Is there a way to use setitem to set bits of data of type UInt[N]?

@extend
class UInt:
    def __setitem__(self,Slice,val):
        print(f"self of A address:{__ptr__(self)} , Slice:{Slice.start}:{Slice.stop}:{Slice.step} , Set value:{val}")
        self = UInt[N](int(val))

A = UInt[64](0)
B = UInt[32](1)

A[0:32] = B
print(f"A address:{__ptr__(A)}, Result:{A}")

self of A address:0x7ffe93eecbe8 , Slice:0:32:None , Set value:1
A address:0x7ffe93eecbb8, Result:0

iSunfield avatar Apr 14 '24 04:04 iSunfield

Hi @iSunfield

Ints are passed by value (not by reference), hence __setitem__ will receive a copy. Right now only correct way to do this is to do value |= value[5:8] if you have setitem implemented. You can also try passing __ptr__(val) to a function (then you get the address of the value) but that's very C-ish and quite ugly.

inumanag avatar Sep 23 '24 05:09 inumanag