1.1 --- /dev/null Thu Jan 01 00:00:00 1970 +0000
1.2 +++ b/lib/posix/iconv.py Mon Dec 12 00:40:54 2016 +0100
1.3 @@ -0,0 +1,79 @@
1.4 +#!/usr/bin/env python
1.5 +
1.6 +"""
1.7 +POSIX character set conversion functions.
1.8 +
1.9 +Copyright (C) 2016 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
1.17 +ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
1.18 +FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
1.19 +details.
1.20 +
1.21 +You should have received a copy of the GNU General Public License along with
1.22 +this program. If not, see <http://www.gnu.org/licenses/>.
1.23 +"""
1.24 +
1.25 +from __builtins__.types import check_int, check_string
1.26 +from native import iconv_close, iconv_open, iconv
1.27 +
1.28 +class ConverterError(Exception):
1.29 +
1.30 + "An error indicating a failure involving a character set converter."
1.31 +
1.32 + pass
1.33 +
1.34 +E2BIG = 7
1.35 +EINVAL = 22
1.36 +EILSEQ = 84
1.37 +
1.38 +class Converter:
1.39 +
1.40 + "A character set converter."
1.41 +
1.42 + def __init__(self, from_encoding, to_encoding):
1.43 +
1.44 + "Initialise conversion between 'from_encoding' and 'to_encoding'."
1.45 +
1.46 + check_string(from_encoding)
1.47 + check_string(to_encoding)
1.48 + self.__data__ = iconv_open(to_encoding, from_encoding)
1.49 +
1.50 + def close(self):
1.51 +
1.52 + "Close this converter."
1.53 +
1.54 + iconv_close(self.__data__)
1.55 + self.__data__ = None
1.56 +
1.57 + def convert(self, s):
1.58 +
1.59 + "Convert 's' between the converter's encodings."
1.60 +
1.61 + if self.__data__ is None:
1.62 + raise ConverterError
1.63 +
1.64 + check_string(s)
1.65 +
1.66 + result = []
1.67 + state = [0, len(s)]
1.68 +
1.69 + while True:
1.70 +
1.71 + # Obtain converted text and update the state.
1.72 +
1.73 + out = iconv(self.__data__, s, state)
1.74 + result.append(out)
1.75 +
1.76 + # Test for the end of the conversion.
1.77 +
1.78 + start, remaining = state
1.79 + if not remaining:
1.80 + return "".join(result)
1.81 +
1.82 +# vim: tabstop=4 expandtab shiftwidth=4