changeset 13:6acda841a690

Add support for shared substrings.
author David Barts <n5jrn@me.com>
date Fri, 27 Dec 2019 13:23:07 -0800
parents ab7d6e908034
children 152f6aa87d62
files runes.py
diffstat 1 files changed, 15 insertions(+), 6 deletions(-) [+]
line wrap: on
line diff
--- a/runes.py	Fri Dec 27 11:39:21 2019 -0800
+++ b/runes.py	Fri Dec 27 13:23:07 2019 -0800
@@ -25,8 +25,9 @@
     codec = codecs.lookup(encoding)
 
     def __init__(self, based_on=None):
-        if isinstance(based_on, array.array):
-            if based_on.typecode == 'H':
+        if isinstance(based_on, (array.array, memoryview)):
+            format = based_on.typecode if isinstance(based_on, array.array) else based_on.format
+            if format == 'H':
                 self.buffer = based_on
             else:
                 self.buffer = array.array('H', based_on)
@@ -73,7 +74,7 @@
         return self.buffer != other.buffer
 
     def __hash__(self):
-        return hash(self.buffer)
+        raise TypeError("unhashable type")
 
     def __bool__(self):
         return bool(self.buffer)
@@ -99,6 +100,11 @@
     def __delitem__(self, key):
         del self.buffer[key]
 
+    def __del__(self):
+        # Paranoid
+        if isinstance(self.buffer, memoryview):
+            self.buffer.release()
+
     def clear(self):
         del self[:]
 
@@ -146,16 +152,19 @@
             Runes.__setitem__(self, key, value)
 
     def __getitem__(self, key):
+        view = memoryview(self.buffer)
         try:
-            ret = Runes.__getitem__(self, key)
+            ret = view[key]
             if isinstance (ret, int):
                 return chr(ret)
-            elif isinstance(ret, Runes):
-                return str(ret)
+            elif isinstance(ret, memoryview):
+                return self.codec.decode(ret, 'replace')[0]
             else:
                 raise AssertionError("this shouldn't happen")
         except IndexError:
             return ""
+        finally:
+            view.release()
 
     def append(self, value):
         if isinstance(value, str):