| 1 | |
| 2 | class AbstractShrinkList(object): |
| 3 | """A mixin base class. You should subclass it and add a method |
| 4 | must_keep(). Behaves like a list with the method append(), and |
| 5 | you can read *for reading* the list of items by calling items(). |
| 6 | The twist is that occasionally append() will throw away the |
| 7 | items for which must_keep() returns False. (It does so without |
| 8 | changing the order.) |
| 9 | |
| 10 | See also rpython.rlib.rweaklist. |
| 11 | """ |
| 12 | _mixin_ = True |
| 13 | |
| 14 | def __init__(self): |
| 15 | self._list = [] |
| 16 | self._next_shrink = 16 |
| 17 | |
| 18 | def append(self, x): |
| 19 | self._do_shrink() |
| 20 | self._list.append(x) |
| 21 | |
| 22 | def items(self): |
| 23 | return self._list |
| 24 | |
| 25 | def _do_shrink(self): |
| 26 | if len(self._list) >= self._next_shrink: |
| 27 | rest = 0 |
| 28 | for x in self._list: |
| 29 | if self.must_keep(x): |
| 30 | self._list[rest] = x |
| 31 | rest += 1 |
| 32 | del self._list[rest:] |
| 33 | self._next_shrink = 16 + 2 * rest |
| 34 | |
| 35 | def must_keep(self, x): |
| 36 | raise NotImplementedError |