1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/simplex/state.py Sat Oct 01 19:33:58 2011 +0200
1.3 @@ -0,0 +1,53 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +State management classes for iterators.
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 +from os.path import commonprefix
1.25 +
1.26 +class CommonPrefixState:
1.27 +
1.28 + "A class whose instances maintain common prefix state."
1.29 +
1.30 + def __init__(self, initial=""):
1.31 + self.initial = initial
1.32 + self.reset()
1.33 +
1.34 + def reset(self):
1.35 + self.value = self.initial
1.36 +
1.37 +class CommonPrefixDecoder(CommonPrefixState):
1.38 +
1.39 + "A class whose instances decode common prefix information."
1.40 +
1.41 + def update(self, common_plus_suffix):
1.42 + common, suffix = common_plus_suffix
1.43 + self.value = self.value[:common] + suffix
1.44 + return self.value
1.45 +
1.46 +class CommonPrefixEncoder(CommonPrefixState):
1.47 +
1.48 + "A class whose instances encode common prefix information."
1.49 +
1.50 + def update(self, value):
1.51 + common = len(commonprefix((self.value, value)))
1.52 + suffix = value[common:]
1.53 + self.value = value
1.54 + return common, suffix
1.55 +
1.56 +# vim: tabstop=4 expandtab shiftwidth=4