Add support for negative slice indices
authorLars-Peter Clausen <lars@metafoo.de>
Tue, 12 Mar 2013 20:34:36 +0000 (21:34 +0100)
committerLars-Peter Clausen <lars@metafoo.de>
Tue, 12 Mar 2013 20:56:01 +0000 (21:56 +0100)
In python a negative indices usually mean start counting from the right side.
I.e. if the index is negative is acutal index used is len(l) + i. E.g. l[-2]
equals l[len(l)-2].

Being able to specify an index this way also comes in handy for migen slices in
some cases. E.g. the following snippet can be implement to shift an abitrary
length register n bits to the right:
reg.eq(Cat(Replicate(0, n), reg[-n:])

Signed-off-by: Lars-Peter Clausen <lars@metafoo.de>
migen/fhdl/structure.py

index 8052fdffbbc700e473247c8dab0f8ecd2643ec15..350670fc5c7306269458995a5cd5ea4ca33b8224 100644 (file)
@@ -89,10 +89,16 @@ class Value(HUID):
        
        def __getitem__(self, key):
                if isinstance(key, int):
+                       if (key < 0):
+                               key += len(self)
                        return _Slice(self, key, key+1)
                elif isinstance(key, slice):
                        start = key.start or 0
                        stop = key.stop or len(self)
+                       if (start < 0):
+                               start += len(self)
+                       if (stop < 0):
+                               stop += len(self)
                        if stop > len(self):
                                stop = len(self)
                        if key.step != None: