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 _quote_value(self, b, n): 93 94 "Append to 'b' the quoted form of 'n'." 95 96 if n < 0: 97 n += 256 98 99 if n > 0xffff: 100 b.append("\\U") 101 digits = 8 102 else: 103 b.append("\\u") 104 digits = 4 105 106 x = hex(n, "") 107 i = len(x) 108 109 while i < digits: 110 b.append("0") 111 i += 1 112 113 b.append(x) 114 115 # Operator methods. 116 117 def __iadd__(self, other): 118 119 "Return a string combining this string with 'other'." 120 121 return self._convert(self._binary_op(str_add, other), other) 122 123 __add__ = __iadd__ 124 125 def __radd__(self, other): 126 127 "Return a string combining this string with 'other'." 128 129 return self._convert(self._binary_op_rev(str_add, other), other) 130 131 def __len__(self): 132 133 "Return the length of this string in characters." 134 135 if self.length is None: 136 self.length = unicode_len(self.__data__, self.__size__) 137 138 return self.length 139 140 def __ord__(self): 141 142 "Return the value of the string, if only a single character." 143 144 if self.__len__() == 1: 145 return unicode_ord(self.__data__, self.__size__) 146 else: 147 raise ValueError, self 148 149 def encode(self, encoding=None): 150 151 """ 152 Encode the string to the given 'encoding' or any original encoding if 153 omitted. 154 """ 155 156 encoding = encoding or self.encoding 157 if not encoding: 158 return self 159 160 from_utf8 = Converter("UTF-8", encoding) 161 162 try: 163 from_utf8.feed(self) 164 return str(from_utf8) 165 166 finally: 167 from_utf8.close() 168 169 def join(self, l): 170 171 "Join the elements in 'l' with this string." 172 173 # Empty strings just cause the list elements to be concatenated. 174 175 nonempty = self.__bool__() 176 177 # Non-empty strings join the elements together in a buffer. 178 179 b = buffer() 180 first = True 181 encoding = self.encoding 182 183 for s in l: 184 if first: 185 first = False 186 elif nonempty: 187 b.append(self) 188 189 if _isinstance(s, utf8string): 190 encoding = None 191 192 b.append(s) 193 194 s = str(b) 195 if encoding: 196 s = utf8string(s) 197 s.encoding = encoding 198 return s 199 200 # Special implementation methods. 201 202 def __get_single_item__(self, index): 203 204 "Return the item at the normalised (positive) 'index'." 205 206 self._check_index(index) 207 return utf8string(unicode_substr(self.__data__, self.__size__, index, index + 1, 1), self.encoding) 208 209 def __get_multiple_items__(self, start, end, step): 210 211 """ 212 Return items from 'start' until (but excluding) 'end', at 'step' 213 intervals. 214 """ 215 216 if start == end: 217 return "" 218 219 check_int(step) 220 221 if step == 0: 222 raise ValueError(step) 223 224 l = get_using(basestring.__get_multiple_items__, self)(start, end, step) 225 return utf8string("".join(l), self.encoding) 226 227 def unicode(s, encoding): 228 229 "Convert 's' to a Unicode object, interpreting 's' as using 'encoding'." 230 231 if isinstance(s, utf8string): 232 return s 233 234 # Obtain a string representation. 235 236 s = s.__str__() 237 238 # Convert the string to UTF-8. Even if the stated encoding is UTF-8, it 239 # needs to be validated. 240 241 to_utf8 = Converter(encoding, "UTF-8") 242 243 try: 244 to_utf8.feed(s) 245 return utf8string(str(to_utf8), encoding) 246 247 finally: 248 to_utf8.close() 249 250 # vim: tabstop=4 expandtab shiftwidth=4