paul@390 | 1 | #!/usr/bin/env python |
paul@390 | 2 | |
paul@390 | 3 | """ |
paul@390 | 4 | Unicode objects. |
paul@390 | 5 | |
paul@390 | 6 | Copyright (C) 2015, 2016 Paul Boddie <paul@boddie.org.uk> |
paul@390 | 7 | |
paul@390 | 8 | This program is free software; you can redistribute it and/or modify it under |
paul@390 | 9 | the terms of the GNU General Public License as published by the Free Software |
paul@390 | 10 | Foundation; either version 3 of the License, or (at your option) any later |
paul@390 | 11 | version. |
paul@390 | 12 | |
paul@390 | 13 | This program is distributed in the hope that it will be useful, but WITHOUT |
paul@390 | 14 | ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS |
paul@390 | 15 | FOR A PARTICULAR PURPOSE. See the GNU General Public License for more |
paul@390 | 16 | details. |
paul@390 | 17 | |
paul@390 | 18 | You should have received a copy of the GNU General Public License along with |
paul@390 | 19 | this program. If not, see <http://www.gnu.org/licenses/>. |
paul@390 | 20 | """ |
paul@390 | 21 | |
paul@390 | 22 | from __builtins__.str import basestring |
paul@390 | 23 | from posix.iconv import Converter |
paul@390 | 24 | |
paul@390 | 25 | class utf8string(basestring): |
paul@390 | 26 | |
paul@390 | 27 | "A character string representation based on UTF-8." |
paul@390 | 28 | |
paul@390 | 29 | def encode(self, encoding): |
paul@390 | 30 | |
paul@390 | 31 | "Encode the string to the given 'encoding'." |
paul@390 | 32 | |
paul@390 | 33 | from_utf8 = Converter("UTF-8", encoding) |
paul@392 | 34 | |
paul@390 | 35 | try: |
paul@390 | 36 | from_utf8.feed(self) |
paul@390 | 37 | return str(from_utf8) |
paul@392 | 38 | |
paul@390 | 39 | finally: |
paul@390 | 40 | from_utf8.close() |
paul@390 | 41 | |
paul@390 | 42 | def unicode(s, encoding): |
paul@390 | 43 | |
paul@390 | 44 | "Convert 's' to a Unicode object, interpreting 's' as using 'encoding'." |
paul@390 | 45 | |
paul@390 | 46 | if isinstance(s, utf8string): |
paul@390 | 47 | return s |
paul@390 | 48 | |
paul@390 | 49 | # Obtain a string representation. |
paul@390 | 50 | |
paul@390 | 51 | s = s.__str__() |
paul@390 | 52 | |
paul@390 | 53 | # Convert the string to UTF-8. |
paul@390 | 54 | |
paul@390 | 55 | to_utf8 = Converter(encoding, "UTF-8") |
paul@392 | 56 | |
paul@390 | 57 | try: |
paul@390 | 58 | to_utf8.feed(s) |
paul@390 | 59 | return utf8string(str(to_utf8)) |
paul@392 | 60 | |
paul@390 | 61 | finally: |
paul@390 | 62 | to_utf8.close() |
paul@390 | 63 | |
paul@390 | 64 | # vim: tabstop=4 expandtab shiftwidth=4 |