1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/simplex/iterators.py Sat Oct 01 19:33:58 2011 +0200
1.3 @@ -0,0 +1,61 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Iterator classes for indexing.
1.8 +
1.9 +Copyright (C) 2011 Paul Boddie <paul@boddie.org.uk>
1.10 +
1.11 +This program is free software; you can redistribute it and/or modify it under
1.12 +the terms of the GNU General Public License as published by the Free Software
1.13 +Foundation; either version 3 of the License, or (at your option) any later
1.14 +version.
1.15 +
1.16 +This program is distributed in the hope that it will be useful, but WITHOUT ANY
1.17 +WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A
1.18 +PARTICULAR PURPOSE. See the GNU General Public License for more details.
1.19 +
1.20 +You should have received a copy of the GNU General Public License along
1.21 +with this program. If not, see <http://www.gnu.org/licenses/>.
1.22 +"""
1.23 +
1.24 +class Iterator:
1.25 +
1.26 + "An iterator over records employing record accessors."
1.27 +
1.28 + def __init__(self, accessor):
1.29 + self.accessor = accessor
1.30 + self.records = None
1.31 + self.iterator = None
1.32 +
1.33 + def set_records(self, records):
1.34 + self.records = records
1.35 +
1.36 + def __iter__(self):
1.37 + self.iterator = iter(self.records)
1.38 + return self
1.39 +
1.40 + def next(self):
1.41 + if self.iterator is None:
1.42 + iter(self)
1.43 + record = self.iterator.next()
1.44 + return self.accessor.get_key(record), record
1.45 +
1.46 +class StatefulIterator(Iterator):
1.47 +
1.48 + "An iterator over records maintaining state."
1.49 +
1.50 + def __init__(self, accessor, state):
1.51 + Iterator.__init__(self, accessor)
1.52 + self.state = state
1.53 +
1.54 + def __iter__(self):
1.55 + Iterator.__iter__(self)
1.56 + self.state.reset()
1.57 + return self
1.58 +
1.59 + def next(self):
1.60 + key, record = Iterator.next(self)
1.61 + self.key = self.state.update(key)
1.62 + return self.key, record
1.63 +
1.64 +# vim: tabstop=4 expandtab shiftwidth=4