1 #!/usr/bin/env python 2 3 """ 4 Unicode objects. 5 6 Copyright (C) 2015, 2016, 2017 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__.str import basestring 23 from __builtins__.types import check_int 24 from posix.iconv import Converter 25 from native import str_add, unicode_len, unicode_ord, unicode_substr, \ 26 isinstance as _isinstance 27 28 class utf8string(basestring): 29 30 "A character string representation based on UTF-8." 31 32 def __init__(self, other=None, encoding=None): 33 34 """ 35 Initialise the string, perhaps from 'other', with any original 36 'encoding' indicated. 37 """ 38 39 get_using(basestring.__init__, self)(other) 40 self.encoding = encoding 41 self.length = None 42 43 def _binary_op(self, op, other): 44 45 "Perform 'op' on this object and 'other' if appropriate." 46 47 # Reject non-strings. 48 49 if not _isinstance(other, basestring): 50 return NotImplemented 51 52 # Combining text with bytes. 53 54 elif not _isinstance(other, utf8string): 55 s = self.encode() 56 return op(s.__data__, other.__data__) 57 58 # Otherwise, perform the operation on the operands' data. 59 60 else: 61 return op(self.__data__, other.__data__) 62 63 def _binary_op_rev(self, op, other): 64 65 "Perform 'op' on 'other' and this object if appropriate." 66 67 # Reject non-strings. 68 69 if not _isinstance(other, basestring): 70 return NotImplemented 71 72 # Combining text with bytes. 73 74 elif not _isinstance(other, utf8string): 75 s = self.encode() 76 return op(other.__data__, s.__data__) 77 78 # Otherwise, perform the operation on the operands' data. 79 80 else: 81 return op(other.__data__, self.__data__) 82 83 def _convert(self, result, other): 84 85 "Convert 'result' to a Unicode object if 'other' already is." 86 87 if _isinstance(other, utf8string): 88 return utf8string(result, self.encoding) 89 else: 90 return result 91 92 def __iadd__(self, other): 93 94 "Return a string combining this string with 'other'." 95 96 return self._convert(self._binary_op(str_add, other), other) 97 98 __add__ = __iadd__ 99 100 def __radd__(self, other): 101 102 "Return a string combining this string with 'other'." 103 104 return self._convert(self._binary_op_rev(str_add, other), other) 105 106 def __len__(self): 107 108 "Return the length of this string in characters." 109 110 if self.length is None: 111 self.length = unicode_len(self.__data__) 112 113 return self.length 114 115 def __ord__(self): 116 117 "Return the value of the string, if only a single character." 118 119 if self.__len__() == 1: 120 return unicode_ord(self.__data__) 121 else: 122 raise ValueError, self 123 124 def encode(self, encoding=None): 125 126 """ 127 Encode the string to the given 'encoding' or any original encoding if 128 omitted. 129 """ 130 131 encoding = encoding or self.encoding 132 if not encoding: 133 return self 134 135 from_utf8 = Converter("UTF-8", encoding) 136 137 try: 138 from_utf8.feed(self) 139 return str(from_utf8) 140 141 finally: 142 from_utf8.close() 143 144 def join(self, l): 145 146 "Join the elements in 'l' with this string." 147 148 # Empty strings just cause the list elements to be concatenated. 149 150 nonempty = self.__bool__() 151 152 # Non-empty strings join the elements together in a buffer. 153 154 b = buffer() 155 first = True 156 encoding = self.encoding 157 158 for s in l: 159 if first: 160 first = False 161 elif nonempty: 162 b.append(self) 163 164 if _isinstance(s, utf8string): 165 encoding = None 166 167 b.append(s) 168 169 s = str(b) 170 if encoding: 171 s = utf8string(s) 172 s.encoding = encoding 173 return s 174 175 # Special implementation methods. 176 177 def __get_single_item__(self, index): 178 179 "Return the item at the normalised (positive) 'index'." 180 181 self._check_index(index) 182 return utf8string(unicode_substr(self.__data__, index, index + 1, 1), self.encoding) 183 184 def __get_multiple_items__(self, start, end, step): 185 186 """ 187 Return items from 'start' until (but excluding) 'end', at 'step' 188 intervals. 189 """ 190 191 if start == end: 192 return "" 193 194 check_int(step) 195 196 if step == 0: 197 raise ValueError(step) 198 199 l = get_using(basestring.__get_multiple_items__, self)(start, end, step) 200 return utf8string("".join(l), self.encoding) 201 202 def unicode(s, encoding): 203 204 "Convert 's' to a Unicode object, interpreting 's' as using 'encoding'." 205 206 if isinstance(s, utf8string): 207 return s 208 209 # Obtain a string representation. 210 211 s = s.__str__() 212 213 # Convert the string to UTF-8. Even if the stated encoding is UTF-8, it 214 # needs to be validated. 215 216 to_utf8 = Converter(encoding, "UTF-8") 217 218 try: 219 to_utf8.feed(s) 220 return utf8string(str(to_utf8), encoding) 221 222 finally: 223 to_utf8.close() 224 225 # vim: tabstop=4 expandtab shiftwidth=4