bstring.html


001| '''Fixed-Length String (bytearray).
001| 
001| Mutable! Implement lots of string modification methods.
001| 
001| Init as sequence or fill.
001| '''

002| ####################################################################################################
003| from sys import argv
004| ####################################################################################################
005| typename = lambda x: type(x).__name__
006| 
007| ##~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~##
008| class bstring:
009|     '''A basic bstring (bytearray string) class. (Mutable!)'''
010|     verbose = False
011| 
012|     def __init__ (self, text=[], length=None, fill=' ', encoding='utf8'):
013|         '''New bstring instance.'''
014|         if bstring.verbose: print(f'bstring::init({text=},{length=}, {encoding=})')
015| 
016|         self.fill = fill
017|         self.encoding = encoding
018|         if isinstance(text,str):
019|             self.string = bytearray(text, encoding=encoding)
020|         else:
021|             self.string = bytearray(text)
022| 
023|         # If length supplied...
024|         if length is not None:
025|             # If supplied length is less than string...
026|             if length < len(self.string):
027|                 # Truncate...
028|                 del self.string[length:]
029| 
030|             # If supplied length is greater than string...
031|             if len(self.string) < length:
032|                 # Expand...
033|                 extra = length - len(self.string)
034|                 self.string.extend(bytearray(fill * extra, encoding=encoding))
035| 
036|     def __call__ (self, ix):
037|         '''Called for obj(ix). Return an indexed character.
037|            NOTE: Use a range to get a multi-byte Unicode character.
037|            ATTN: return chr(self.string[ix]) # ??
037|            ATTN: change to a visit function?
037|         '''

038|         if self.verbose: print(f'bstring::call({ix=})')
039|         return str(self.string[ix], encoding=self.encoding)
040| 
041|     #NOTE: Done automagically because we define __eq__
042|     __hash__ = None
043| 
044|     def __len__ (self):
045|         '''Called for len(obj). Return length of bstring.'''
046|         if self.verbose: print(f'bstring::len()')
047|         return len(self.string)
048| 
049|     def __iter__ (self):
050|         '''Called for iter(obj). Return an iterator over bstring.'''
051|         if self.verbose: print(f'bstring::iter()')
052|         return iter(self.string)
053| 
054|     def __getitem__ (self, ix):
055|         '''Called for obj[index]. Return an indexed byte from bstring.
055|            NOTE: These functions get ranges like obj[3:-3:2]!
055|         '''

056|         if self.verbose: print(f'bstring::getitem({ix=})')
057|         return self.string[ix]
058| 
059|     def __setitem__ (self, ix, val):
060|         '''Called for obj[index] = value. Change an index byte in bstring.
060|            NOTE: This can be Bad if messing with Unicode characters!
060|         '''

061|         if self.verbose: print(f'bstring::setitem({ix=},{val=})')
062|         self.string[ix] = val
063| 
064|     def __delitem__ (self, ix):
065|         '''Called for del obj[index].
065|            Exception raised -- bstring is fixed length!
065|         '''

066|         if self.verbose: print(f'bstring::delitem({ix=})')
067|         raise NotImplementedError("Can't remove elements in a fixed-length bstring.")
068| 
069|     def __contains__ (self, item):
070|         '''Called for {item in obj}. Return a boolean.'''
071|         if self.verbose: print(f'bstring::contains({item=})')
072|         return (item in self.string)
073| 
074|     def __bool__ (self):
075|         '''Called for if obj. Return a boolean.'''
076|         #ATTN: Test!
077|         if self.verbose: print(f'bstring::bool()')
078|         nz = self.string.count(0)
079|         return (nz == len(self))
080| 
081|     def __int__ (self):
082|         '''Called for int(obj). Return an integer.'''
083|         if self.verbose: print(f'bstring::int()')
084|         val = sum(b*pow(256,n) for n,b in enumerate(reversed(self.string)))
085|         return val
086| 
087|     def __bytes__ (self):
088|         '''Called for bytes(obj). Return a bytes version.'''
089|         if self.verbose: print(f'bstring::bytes()')
090|         return bytes(self.string)
091| 
092|     def __reversed__ (self):
093|         '''Called for reversed(obj). Return reversed copy of bstring.
093|            NOTE: Not called for obj[::-1]! Uses __getitem__.
093|         '''

094|         if self.verbose: print(f'bstring::reversed()')
095|         return reversed(self.string)
096| 
097|     def __eq__ (self, other):
098|         '''Called for obj1==obj2. Return a boolean.'''
099|         self._other_type_check(other)
100|         return self.string == other.string
101| 
102|     def __ne__ (self, other):
103|         '''Called for obj1!=obj2. Return a boolean.'''
104|         self._other_type_check(other)
105|         return self.string != other.string
106| 
107|     def __lt__ (self, other):
108|         '''Called for obj1<obj2. Return a boolean.'''
109|         self._other_type_check(other)
110|         return self.string < other.string
111| 
112|     def __le__ (self, other):
113|         '''Called for obj1<=obj2. Return a boolean.'''
114|         self._other_type_check(other)
115|         return self.string <= other.string
116| 
117|     def __ge__ (self, other):
118|         '''Called for obj1>=obj2. Return a boolean.'''
119|         self._other_type_check(other)
120|         return self.string >= other.string
121| 
122|     def __gt__ (self, other):
123|         '''Called for obj1>obj2. Return a boolean.'''
124|         self._other_type_check(other)
125|         return self.string > other.string
126| 
127|     def __add__ (self, other):
128|         '''Add (concatenate) two bstrings. (radd not needed)'''
129|         #ATTN: Test these!
130|         if self.verbose: print(f'bstring::add({other})')
131|         self._other_type_check(other)
132|         #TODO: Check encoding; match if necesary.
133|         return bstring(self.string + other.string, encoding=self.encoding)
134| 
135|     def __mul__ (self, other):
136|         '''Multiply by integer for bstring with N copies.'''
137|         if self.verbose: print(f'bstring::multiply(n)')
138|         if not isinstance(other, int):
139|             raise TypeError(f'Multiplier must be an integer, not {typename(other)}')
140|         return bstring(self.string * other, encoding=self.encoding)
141| 
142|     def __rmul__ (self, other):
143|         '''Multiply by integer for bstring with N copies.'''
144|         if self.verbose: print(f'bstring::multiply(n) [Reversed]')
145|         if not isinstance(other, int):
146|             raise TypeError(f'Multiplier must be an integer, not {typename(other)}')
147|         return bstring(self.string * other, encoding=self.encoding)
148| 
149|     def _left_shift_ (self, n):
150|         '''Shift data N bytes to left..'''
151|         if self.verbose: print(f'bstring::lshift({n})')
152|         if not isinstance(n, int):
153|             raise TypeError(f'Shift value must be an integer, not {typename(other)}')
154|         pad = bytearray(self.fill * n, encoding=self.encoding)
155|         return bstring(self.string[n:]+pad, length=len(self), encoding=self.encoding)
156| 
157|     def _right_shift_ (self, n):
158|         '''Shift data N bytes to right.'''
159|         if self.verbose: print(f'bstring::rshift({n})')
160|         if not isinstance(n, int):
161|             raise TypeError(f'Shift value must be an integer, not {typename(other)}')
162|         pad = bytearray(self.fill * n, encoding=self.encoding)
163|         return bstring(pad+self.string[:-n], length=len(self), encoding=self.encoding)
164| 
165|     #TODO: Add __ilshift__ and __irshift__ (and rotate(direction, count)?)
166| 
167|     def __lshift__ (self, other): return self._left_shift_(other)
168|     def __rlshift__ (self, other): return self._left_shift_(other)
169| 
170|     def __rshift__ (self, other): return self._right_shift_(other)
171|     def __rrshift__ (self, other): return self._right_shift_(other)
172| 
173|     def _and_ (self, other):
174|         '''AND two bstrings.'''
175|         if self.verbose: print(f'bstring::and({other})')
176|         self._other_type_check(other)
177|         self._other_length_check(other)
178|         res = [(a & b) for a,b in zip(self.string,other.string)]
179|         return bstring(res, encoding=self.encoding)
180| 
181|     def _or_ (self, other):
182|         '''OR two bstrings.'''
183|         if self.verbose: print(f'bstring::or({other})')
184|         self._other_type_check(other)
185|         self._other_length_check(other)
186|         res = [(a | b) for a,b in zip(self.string,other.string)]
187|         return bstring(res, encoding=self.encoding)
188| 
189|     def _xor_ (self, other):
190|         '''XOR two bstrings.'''
191|         if self.verbose: print(f'bstring::xor({other})')
192|         self._other_type_check(other)
193|         self._other_length_check(other)
194|         res = [(a ^ b) for a,b in zip(self.string,other.string)]
195|         return bstring(res, encoding=self.encoding)
196| 
197|     def __and__ (self, other): return self._and_(other)
198|     def __rand__ (self, other): return self._and_(other)
199| 
200|     def __or__ (self, other): return self._or_(other)
201|     def __ord__ (self, other): return self._or_(other)
202| 
203|     def __xor__ (self, other): return self._xor_(other)
204|     def __rxor__ (self, other): return self._xor_(other)
205| 
206|     def _other_type_check (self, other):
207|         '''Ensure that other is the right type.'''
208|         if not isinstance(other, type(self)):
209|             raise TypeError(f'Invalid comparison type. ({typename(other)})')
210| 
211|     def _other_length_check (self, other):
212|         '''Ensure two bstrings are same length. (Assumes other has same type!)'''
213|         if len(self) != len(other):
214|             raise TypeError(f'Length of other bstring must match. ({len(self)}!={len(other)})')
215| 
216|     def hexstr (self):
217|         '''Return string of hex values.'''
218|         return '.'.join(f'{b:02x}' for b in self.string)
219| 
220|     def __repr__ (self):
221|         return f'<{typename(self)} len={len(self)} encoding={self.encoding} @{id(self):08x}>'
222| 
223|     def __str__ (self):
224|         try:
225|             return str(self.string, encoding=self.encoding)
226|         except:
227|             pass
228|         return self.hexstr()
229| 
230| 
231| ##================================================================================================##
232| def main ():
233|     #bstring.verbose = True
234| 
235|     bs0 = bstring([ord(ch) for ch in 'Foo'])
236|     print(f'bs0 is type {typename(bs0)} with length {len(bs0)}')
237|     print(bs0)
238|     print(bs0.hexstr())
239|     print(list(bs0))
240|     print()
241|     v = bs0 + bs0
242|     print(f'bs0+bs0={v!s} ({typename(v)})')
243|     v = bs0 + bstring("--") + bs0
244|     print(f'bs0+bstring()+bs0={v!s} ({typename(v)})')
245|     v = bs0 * 4
246|     print(f'bs0*4={v!s} ({typename(v)})')
247|     v = 5 * bs0
248|     print(f'5*bs0={v!s} ({typename(v)})')
249|     print()
250| 
251|     bs1 = bstring("Héllö, Wõrld! ¿Hôw yå døîñg?")
252|     print(f'bs1 is type {typename(bs1)} with length {len(bs1)}')
253|     print(bs1)
254|     print(bs1.hexstr())
255|     print(list(bs1))
256|     print()
257|     print(f'{bs1(slice(0,7))=}')
258|     print(f'{bs1[slice(0,7)]=}')
259|     print()
260| 
261|     rbs1a = reversed(bs1)
262|     print(f'rbs1a is type {typename(rbs1a)}')
263|     rbs1a = list(rbs1a)
264|     print(f'rbs1a is type {typename(rbs1a)} with length {len(rbs1a)}')
265|     print('.'.join(f'{b:02x}' for b in rbs1a))
266|     print()
267| 
268|     rbs1b = bs1[::-1]
269|     print(f'rbs1b is type {typename(rbs1b)} with length {len(rbs1b)}')
270|     print('.'.join(f'{b:02x}' for b in rbs1b))
271|     print()
272| 
273|     bs2 = bstring('Ćĥŕíş Ω Śóññáćķ', encoding='utf16')
274|     print(f'{bs2} ({len(bs2)} bytes, {bs2.encoding}) [{bs2[0:2]}]')
275|     print(bs2.hexstr())
276|     print()
277| 
278|     bs3 = bstring('Now is the time for all good people to come to the party!')
279|     print(f'bs3 is type {typename(bs3)} with length {len(bs3)}')
280|     print(f'|{bs3}|')
281|     print(f'|{bs3 << 8}|')
282|     print(f'|{bs3 >> 8}|')
283|     print()
284| 
285|     bs3m = bstring(length=len(bs3), fill=chr(0xAA), encoding='latin_1')
286|     print(f'bs3m is type {typename(bs3m)} with length {len(bs3m)}')
287|     print(bs3m.hexstr())
288|     bs3e = bs3 ^ bs3m
289|     bs3d = bs3e ^ bs3m
290|     print(f'{bs3m=!s}')
291|     print(f'{bs3e=!s}')
292|     print(f'{bs3d=!s}')
293|     print()
294| 
295|     return (bs0, bs1, bs2, bs3, bs3m, bs3e)
296| 
297| ####################################################################################################
298| if __name__ == '__main__':
299|     print(argv[0])
300|     print()
301|     bss = main()
302|     print()
303| ####################################################################################################
304| '''eof'''
305|