Skip to content

Instantly share code, notes, and snippets.

@drakedevel
Created May 9, 2013 00:00
Show Gist options
  • Save drakedevel/5544600 to your computer and use it in GitHub Desktop.
Save drakedevel/5544600 to your computer and use it in GitHub Desktop.
Efficient mutable bytestrings for Python 2 and 3 in less than 20 lines of code!
from ctypes import CDLL, cast, c_char, c_char_p, c_void_p, c_int
from ctypes.util import find_library
libc = CDLL(find_library('c'))
class mutable_bytes(bytes):
def __setitem__(self, idx, val):
if isinstance(idx, slice):
indices = range(*idx.indices(len(self)))
else:
indices = [idx]
assert len(indices) <= len(val)
si = 0
for i in indices:
dest = c_void_p(cast(c_char_p(self), c_void_p).value + i)
libc.memset(dest, c_char(val[si]), c_int(1))
si += 1
x = mutable_bytes(b'hello world')
print("%d: %s" % (id(x), x.decode('utf-8')))
x[0:5] = b' bye'
print("%d: %s" % (id(x), x.decode('utf-8')))
x[7] = b'y'
print("%d: %s" % (id(x), x.decode('utf-8')))
x[1:10:2] = b'xxxxx'
print("%d: %s" % (id(x), x.decode('utf-8')))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment