1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/simplex/converters.py Sun Oct 02 00:19:49 2011 +0200
1.3 @@ -0,0 +1,70 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +Converters for use with accessors.
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 Converter:
1.27 +
1.28 + "A generic converter."
1.29 +
1.30 + def reset(self):
1.31 + pass
1.32 +
1.33 + def convert(self, value):
1.34 + return value
1.35 +
1.36 +class CommonPrefixState(Converter):
1.37 +
1.38 + "A class whose instances maintain common prefix state."
1.39 +
1.40 + def __init__(self, initial=""):
1.41 + self.initial = initial
1.42 + self.reset()
1.43 +
1.44 + def reset(self):
1.45 + self.value = self.initial
1.46 +
1.47 +class CommonPrefixDecoder(CommonPrefixState):
1.48 +
1.49 + "A class whose instances decode common prefix information."
1.50 +
1.51 + def convert(self, common_plus_suffix):
1.52 + common, suffix = common_plus_suffix
1.53 + self.value = self.value[:common] + suffix
1.54 + return self.value
1.55 +
1.56 +class CommonPrefixEncoder(CommonPrefixState):
1.57 +
1.58 + "A class whose instances encode common prefix information."
1.59 +
1.60 + def convert(self, value):
1.61 + common = len(commonprefix((self.value, value)))
1.62 + suffix = value[common:]
1.63 + self.value = value
1.64 + return common, suffix
1.65 +
1.66 +class NumericDecoder(Converter):
1.67 +
1.68 + "A class which decodes numbers."
1.69 +
1.70 + def convert(self, value):
1.71 + return int(value)
1.72 +
1.73 +# vim: tabstop=4 expandtab shiftwidth=4