@@ -75,7 +75,7 @@ def __iter__(self):
75
75
yield self ._array [i ]
76
76
i = self .wrap (i + 1 )
77
77
78
- def __getitem__ (self , index_from_tail ):
78
+ def __getitem__ (self , index ):
79
79
"""
80
80
>>> cb = CircularBuffer(8)
81
81
>>> for i in range(10):
@@ -116,8 +116,29 @@ def __getitem__(self, index_from_tail):
116
116
Traceback (most recent call last):
117
117
...
118
118
IndexError: ...
119
+
120
+ >>> cq[0:2]
121
+ [5, 6]
122
+ >>> cq[1:4]
123
+ [6, 7, 8]
124
+ >>> cq[3:5]
125
+ [8, 9]
119
126
"""
120
127
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 ):
121
142
if not - self .size <= index_from_tail < self .size :
122
143
raise IndexError (
123
144
"%d not in range [%d, %d)" % (index_from_tail , - self .size , self .size )
@@ -126,7 +147,7 @@ def __getitem__(self, index_from_tail):
126
147
index_array = index_from_tail + self ._tail
127
148
else :
128
149
index_array = self ._head + index_from_tail
129
- return self ._array [ self . wrap (index_array )]
150
+ return self .wrap (index_array )
130
151
131
152
def __str__ (self ):
132
153
res = ""
0 commit comments