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_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 encode(self, encoding=None): 116 117 """ 118 Encode the string to the given 'encoding' or any original encoding if 119 omitted. 120 """ 121 122 encoding = encoding or self.encoding 123 if not encoding: 124 return self 125 126 from_utf8 = Converter("UTF-8", encoding) 127 128 try: 129 from_utf8.feed(self) 130 return str(from_utf8) 131 132 finally: 133 from_utf8.close() 134 135 def join(self, l): 136 137 "Join the elements in 'l' with this string." 138 139 # Empty strings just cause the list elements to be concatenated. 140 141 nonempty = self.__bool__() 142 143 # Non-empty strings join the elements together in a buffer. 144 145 b = buffer() 146 first = True 147 encoding = self.encoding 148 149 for s in l: 150 if first: 151 first = False 152 elif nonempty: 153 b.append(self) 154 155 if _isinstance(s, utf8string): 156 encoding = None 157 158 b.append(s) 159 160 s = str(b) 161 if encoding: 162 s = utf8string(s) 163 s.encoding = encoding 164 return s 165 166 # Special implementation methods. 167 168 def __get_single_item__(self, index): 169 170 "Return the item at the normalised (positive) 'index'." 171 172 self._check_index(index) 173 return utf8string(unicode_substr(self.__data__, index, index + 1, 1), self.encoding) 174 175 def __get_multiple_items__(self, start, end, step): 176 177 """ 178 Return items from 'start' until (but excluding) 'end', at 'step' 179 intervals. 180 """ 181 182 start = self._confine_index(start) 183 end = self._confine_index(end) 184 check_int(step) 185 186 if step == 0: 187 raise ValueError(step) 188 189 if start == end: 190 return "" 191 192 return utf8string(unicode_substr(self.__data__, start, end, step), self.encoding) 193 194 def unicode(s, encoding): 195 196 "Convert 's' to a Unicode object, interpreting 's' as using 'encoding'." 197 198 if isinstance(s, utf8string): 199 return s 200 201 # Obtain a string representation. 202 203 s = s.__str__() 204 205 # Convert the string to UTF-8. Even if the stated encoding is UTF-8, it 206 # needs to be validated. 207 208 to_utf8 = Converter(encoding, "UTF-8") 209 210 try: 211 to_utf8.feed(s) 212 return utf8string(str(to_utf8), encoding) 213 214 finally: 215 to_utf8.close() 216 217 # vim: tabstop=4 expandtab shiftwidth=4