Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

add Bytes object to enable passing around raw bytes

  • Loading branch information...
commit 976a168f50c2ba47dfa415b5d9a45bd845f23b89 1 parent bcd8ab1
Klaas Bosteels authored
Showing with 27 additions and 5 deletions.
  1. +2 −1  tests/testio.py
  2. +25 −4 typedbytes.py
View
3  tests/testio.py
@@ -9,7 +9,8 @@ class TestIO(unittest.TestCase):
objects = [True, 1234, 3000000000, 12345L, 1.23, "trala", u'trala',
(1,2,3), [1,2,3,4], {1:2,3:4}, set([1,2,3]),
- decimal.Decimal("123.456"), datetime.datetime.now()]
+ decimal.Decimal("123.456"), datetime.datetime.now(),
+ typedbytes.Bytes("abc123\x01")]
def testio(self):
objects = TestIO.objects
View
29 typedbytes.py
@@ -40,6 +40,7 @@ def classes():
from cPickle import dumps, loads, UnpicklingError, HIGHEST_PROTOCOL
from struct import pack, unpack, error as StructError
+ from array import array
try:
from struct import Struct
except ImportError:
@@ -67,6 +68,19 @@ def pack(self, *args):
_len = len
+
+ class Bytes(array):
+
+ def __new__(cls, size):
+ return array.__new__(cls, 'c')
+
+ def __init__(self, bytes):
+ self.extend(bytes)
+
+ def __str__(self):
+ return "Bytes(" + repr(self.tostring()) + ")"
+
+
class Input(object):
def __init__(self, file, unicode_errors='strict'):
@@ -105,7 +119,7 @@ def read_bytes(self):
value = self.file.read(count)
if _len(value) != count:
raise StructError("EOF before reading all of bytes type")
- return value
+ return Bytes(value)
def read_byte(self):
return unpack_byte(self.file.read(1))[0]
@@ -317,6 +331,11 @@ def write_pickle(self, obj):
self.file.write(pack_int(_PICKLE, _len(bytes)))
self.file.write(bytes)
+ def write_array(self, arr):
+ bytes = arr.tostring()
+ self.file.write(pack_int(_BYTES, _len(bytes)))
+ self.file.write(bytes)
+
TYPE_HANDLER_MAP = {
BooleanType: write_bool,
IntType: write_int,
@@ -327,9 +346,11 @@ def write_pickle(self, obj):
ListType: write_list,
DictType: write_map,
UnicodeType: write_unicode,
+ Bytes: write_bytes,
datetime: write_pickle,
date: write_pickle,
- Decimal: write_pickle
+ Decimal: write_pickle,
+ array: write_array
}
def _make_handler_map(self):
@@ -382,7 +403,7 @@ def writes(self, iterable):
self._writes(flatten(iterable))
- return Input, Output, PairedInput, PairedOutput
+ return Input, Output, PairedInput, PairedOutput, Bytes
-Input, Output, PairedInput, PairedOutput = classes()
+Input, Output, PairedInput, PairedOutput, Bytes = classes()
Please sign in to comment.
Something went wrong with that request. Please try again.