1 #!/usr/bin/env python 2 3 """ 4 POSIX character set conversion functions. 5 6 Copyright (C) 2016 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 14 ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 15 FOR A PARTICULAR PURPOSE. See the GNU General Public License for more 16 details. 17 18 You should have received a copy of the GNU General Public License along with 19 this program. If not, see <http://www.gnu.org/licenses/>. 20 """ 21 22 from __builtins__.types import check_int, check_string 23 from native import iconv_close, iconv_open, iconv 24 25 class ConverterError(Exception): 26 27 "An error indicating a failure involving a character set converter." 28 29 pass 30 31 E2BIG = 7 32 EINVAL = 22 33 EILSEQ = 84 34 35 class Converter: 36 37 "A character set converter." 38 39 def __init__(self, from_encoding, to_encoding): 40 41 "Initialise conversion between 'from_encoding' and 'to_encoding'." 42 43 check_string(from_encoding) 44 check_string(to_encoding) 45 self.__data__ = iconv_open(to_encoding, from_encoding) 46 47 def close(self): 48 49 "Close this converter." 50 51 iconv_close(self.__data__) 52 self.__data__ = None 53 54 def convert(self, s): 55 56 "Convert 's' between the converter's encodings." 57 58 if self.__data__ is None: 59 raise ConverterError 60 61 check_string(s) 62 63 result = [] 64 state = [0, len(s)] 65 66 while True: 67 68 # Obtain converted text and update the state. 69 70 out = iconv(self.__data__, s, state) 71 result.append(out) 72 73 # Test for the end of the conversion. 74 75 start, remaining = state 76 if not remaining: 77 return "".join(result) 78 79 # vim: tabstop=4 expandtab shiftwidth=4