paul@11 | 1 | #!/usr/bin/env python |
paul@11 | 2 | |
paul@11 | 3 | """ |
paul@11 | 4 | State management classes for iterators. |
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 | from os.path import commonprefix |
paul@11 | 22 | |
paul@11 | 23 | class CommonPrefixState: |
paul@11 | 24 | |
paul@11 | 25 | "A class whose instances maintain common prefix state." |
paul@11 | 26 | |
paul@11 | 27 | def __init__(self, initial=""): |
paul@11 | 28 | self.initial = initial |
paul@11 | 29 | self.reset() |
paul@11 | 30 | |
paul@11 | 31 | def reset(self): |
paul@11 | 32 | self.value = self.initial |
paul@11 | 33 | |
paul@11 | 34 | class CommonPrefixDecoder(CommonPrefixState): |
paul@11 | 35 | |
paul@11 | 36 | "A class whose instances decode common prefix information." |
paul@11 | 37 | |
paul@11 | 38 | def update(self, common_plus_suffix): |
paul@11 | 39 | common, suffix = common_plus_suffix |
paul@11 | 40 | self.value = self.value[:common] + suffix |
paul@11 | 41 | return self.value |
paul@11 | 42 | |
paul@11 | 43 | class CommonPrefixEncoder(CommonPrefixState): |
paul@11 | 44 | |
paul@11 | 45 | "A class whose instances encode common prefix information." |
paul@11 | 46 | |
paul@11 | 47 | def update(self, value): |
paul@11 | 48 | common = len(commonprefix((self.value, value))) |
paul@11 | 49 | suffix = value[common:] |
paul@11 | 50 | self.value = value |
paul@11 | 51 | return common, suffix |
paul@11 | 52 | |
paul@11 | 53 | # vim: tabstop=4 expandtab shiftwidth=4 |