1 #!/usr/bin/env python 2 3 """ 4 Converters for use with accessors. 5 6 Copyright (C) 2011 Paul Boddie <paul@boddie.org.uk> 7 8 This program is free software; you can redistribute it and/or modify it under 9 the terms of the GNU General Public License as published by the Free Software 10 Foundation; either version 3 of the License, or (at your option) any later 11 version. 12 13 This program is distributed in the hope that it will be useful, but WITHOUT ANY 14 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A 15 PARTICULAR PURPOSE. See the GNU General Public License for more details. 16 17 You should have received a copy of the GNU General Public License along 18 with this program. If not, see <http://www.gnu.org/licenses/>. 19 """ 20 21 from os.path import commonprefix 22 23 class Converter: 24 25 "A generic converter." 26 27 def reset(self): 28 pass 29 30 def convert(self, value): 31 return value 32 33 class CommonPrefixState(Converter): 34 35 "A class whose instances maintain common prefix state." 36 37 def __init__(self, initial=""): 38 self.initial = initial 39 self.reset() 40 41 def reset(self): 42 self.value = self.initial 43 44 class CommonPrefixDecoder(CommonPrefixState): 45 46 "A class whose instances decode common prefix information." 47 48 def convert(self, common_plus_suffix): 49 common, suffix = common_plus_suffix 50 self.value = self.value[:common] + suffix 51 return self.value 52 53 class CommonPrefixEncoder(CommonPrefixState): 54 55 "A class whose instances encode common prefix information." 56 57 def convert(self, value): 58 common = len(commonprefix((self.value, value))) 59 suffix = value[common:] 60 self.value = value 61 return common, suffix 62 63 class NumericDecoder(Converter): 64 65 "A class which decodes numbers." 66 67 def convert(self, value): 68 return int(value) 69 70 # vim: tabstop=4 expandtab shiftwidth=4