paul@11 | 1 | #!/usr/bin/env python |
paul@11 | 2 | |
paul@11 | 3 | """ |
paul@11 | 4 | Iterator classes for indexing. |
paul@11 | 5 | |
paul@11 | 6 | Copyright (C) 2011 Paul Boddie <paul@boddie.org.uk> |
paul@11 | 7 | |
paul@11 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@11 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@11 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@11 | 11 | version. |
paul@11 | 12 | |
paul@11 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT ANY |
paul@11 | 14 | WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A |
paul@11 | 15 | PARTICULAR PURPOSE. See the GNU General Public License for more details. |
paul@11 | 16 | |
paul@11 | 17 | You should have received a copy of the GNU General Public License along |
paul@11 | 18 | with this program. If not, see <http://www.gnu.org/licenses/>. |
paul@11 | 19 | """ |
paul@11 | 20 | |
paul@11 | 21 | class Iterator: |
paul@11 | 22 | |
paul@11 | 23 | "An iterator over records employing record accessors." |
paul@11 | 24 | |
paul@11 | 25 | def __init__(self, accessor): |
paul@11 | 26 | self.accessor = accessor |
paul@11 | 27 | self.records = None |
paul@11 | 28 | self.iterator = None |
paul@11 | 29 | |
paul@11 | 30 | def set_records(self, records): |
paul@11 | 31 | self.records = records |
paul@11 | 32 | |
paul@11 | 33 | def __iter__(self): |
paul@11 | 34 | self.iterator = iter(self.records) |
paul@11 | 35 | return self |
paul@11 | 36 | |
paul@11 | 37 | def next(self): |
paul@11 | 38 | if self.iterator is None: |
paul@11 | 39 | iter(self) |
paul@11 | 40 | record = self.iterator.next() |
paul@11 | 41 | return self.accessor.get_key(record), record |
paul@11 | 42 | |
paul@11 | 43 | class StatefulIterator(Iterator): |
paul@11 | 44 | |
paul@11 | 45 | "An iterator over records maintaining state." |
paul@11 | 46 | |
paul@11 | 47 | def __init__(self, accessor, state): |
paul@11 | 48 | Iterator.__init__(self, accessor) |
paul@11 | 49 | self.state = state |
paul@11 | 50 | |
paul@11 | 51 | def __iter__(self): |
paul@11 | 52 | Iterator.__iter__(self) |
paul@11 | 53 | self.state.reset() |
paul@11 | 54 | return self |
paul@11 | 55 | |
paul@11 | 56 | def next(self): |
paul@11 | 57 | key, record = Iterator.next(self) |
paul@11 | 58 | self.key = self.state.update(key) |
paul@11 | 59 | return self.key, record |
paul@11 | 60 | |
paul@11 | 61 | # vim: tabstop=4 expandtab shiftwidth=4 |