@@ -75,7 +75,7 @@ def __iter__(self):
7575 yield self ._array [i ]
7676 i = self .wrap (i + 1 )
7777
78- def __getitem__ (self , index_from_tail ):
78+ def __getitem__ (self , index ):
7979 """
8080 >>> cb = CircularBuffer(8)
8181 >>> for i in range(10):
@@ -116,8 +116,29 @@ def __getitem__(self, index_from_tail):
116116 Traceback (most recent call last):
117117 ...
118118 IndexError: ...
119+
120+ >>> cq[0:2]
121+ [5, 6]
122+ >>> cq[1:4]
123+ [6, 7, 8]
124+ >>> cq[3:5]
125+ [8, 9]
119126 """
120127
128+ if isinstance (index , slice ):
129+ if index .step is not None :
130+ raise NotImplementedError
131+ start = index .start if index .start is not None else 0
132+ stop = (index .stop ) if index .stop is not None else self .size
133+ from_array = self ._map_index (start )
134+ to_array = self ._map_index (stop ) if stop != self .size else self ._head
135+ if to_array >= from_array :
136+ return self ._array [from_array : to_array ]
137+ return self ._array [from_array :] + self ._array [:to_array ]
138+
139+ return self ._array [self ._map_index (index )]
140+
141+ def _map_index (self , index_from_tail ):
121142 if not - self .size <= index_from_tail < self .size :
122143 raise IndexError (
123144 "%d not in range [%d, %d)" % (index_from_tail , - self .size , self .size )
@@ -126,7 +147,7 @@ def __getitem__(self, index_from_tail):
126147 index_array = index_from_tail + self ._tail
127148 else :
128149 index_array = self ._head + index_from_tail
129- return self ._array [ self . wrap (index_array )]
150+ return self .wrap (index_array )
130151
131152 def __str__ (self ):
132153 res = ""
0 commit comments