martinkou/bson — Issue #11: encode_cstring accepts invalid input.
Author: rbtcollins
Created: 2011-11-27 21:20:53+00:00
State: open

We found this when this bug report https://bugs.launchpad.net/python-oops-datedir-repo/+bug/896959 was filed, when we found bson documents not decoding, though they encoded without error.

def encode_cstring(value):
if isinstance(value, unicode):
value = value.encode("utf8")
elif isinstance(value, str):
# check value is utf8.
value.decode('utf8')
else:
raise TypeError('Invalid type for cstring %r' % value)
return value + "\x00"

As a replacement encode_cstring would avoid this failure mode, and a related one with non-string types that implement __add__.