Skip to content

Commit

Permalink
[utils] Fix slicing of reversed LazyList
Browse files Browse the repository at this point in the history
Closes yt-dlp#589
  • Loading branch information
pukkandan committed Aug 1, 2021
1 parent eca330c commit e0f2b4b
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 9 deletions.
4 changes: 4 additions & 0 deletions test/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1537,8 +1537,11 @@ def test_LazyList(self):
self.assertEqual(LazyList(it).exhaust(), it)
self.assertEqual(LazyList(it)[5], it[5])

self.assertEqual(LazyList(it)[5:], it[5:])
self.assertEqual(LazyList(it)[:5], it[:5])
self.assertEqual(LazyList(it)[::2], it[::2])
self.assertEqual(LazyList(it)[1::2], it[1::2])
self.assertEqual(LazyList(it)[5::-1], it[5::-1])
self.assertEqual(LazyList(it)[6:2:-2], it[6:2:-2])
self.assertEqual(LazyList(it)[::-1], it[::-1])

Expand All @@ -1550,6 +1553,7 @@ def test_LazyList(self):

self.assertEqual(list(LazyList(it).reverse()), it[::-1])
self.assertEqual(list(LazyList(it).reverse()[1:3:7]), it[::-1][1:3:7])
self.assertEqual(list(LazyList(it).reverse()[::-1]), it)

def test_LazyList_laziness(self):

Expand Down
17 changes: 8 additions & 9 deletions yt_dlp/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -3993,28 +3993,27 @@ def exhaust(self):

@staticmethod
def __reverse_index(x):
return -(x + 1)
return None if x is None else -(x + 1)

def __getitem__(self, idx):
if isinstance(idx, slice):
step = idx.step or 1
start = idx.start if idx.start is not None else 0 if step > 0 else -1
stop = idx.stop if idx.stop is not None else -1 if step > 0 else 0
if self.__reversed:
(start, stop), step = map(self.__reverse_index, (start, stop)), -step
idx = slice(start, stop, step)
idx = slice(self.__reverse_index(idx.start), self.__reverse_index(idx.stop), -(idx.step or 1))
start, stop, step = idx.start, idx.stop, idx.step or 1
elif isinstance(idx, int):
if self.__reversed:
idx = self.__reverse_index(idx)
start = stop = idx
start, stop, step = idx, idx, 0
else:
raise TypeError('indices must be integers or slices')
if start < 0 or stop < 0:
if ((start or 0) < 0 or (stop or 0) < 0
or (start is None and step < 0)
or (stop is None and step > 0)):
# We need to consume the entire iterable to be able to slice from the end
# Obviously, never use this with infinite iterables
return self.__exhaust()[idx]

n = max(start, stop) - len(self.__cache) + 1
n = max(start or 0, stop or 0) - len(self.__cache) + 1
if n > 0:
self.__cache.extend(itertools.islice(self.__iterable, n))
return self.__cache[idx]
Expand Down

0 comments on commit e0f2b4b

Please sign in to comment.