Skip to content

Commit

Permalink
Allow users to specify Packer internal buf_size
Browse files Browse the repository at this point in the history
Giving this flexibility to users means that internal reallocations can
be avoided if the buffer size is good enough, at the expense of
potentially allocating more memory than needed. This, together with
reusing a Packer object, means that multiple serialisations can end up
requiring no memory allocations other than the initial buffer creation,
which can be a big win in some situations.

The default value is still 1MB, making this backwards compatible.

Signed-off-by: Rodrigo Tobar <rtobar@icrar.org>
  • Loading branch information
rtobar committed Jul 18, 2023
1 parent c8d0751 commit edb61db
Showing 1 changed file with 7 additions and 3 deletions.
10 changes: 7 additions & 3 deletions msgpack/_packer.pyx
Original file line number Diff line number Diff line change
Expand Up @@ -102,6 +102,11 @@ cdef class Packer(object):
:param str unicode_errors:
The error handler for encoding unicode. (default: 'strict')
DO NOT USE THIS!! This option is kept for very specific usage.
:param int buf_size:
The size of the internal buffer. (default: 1024 * 1024)
Useful if serialisation size can be correctly estimated,
avoid unnecessary reallocations.
"""
cdef msgpack_packer pk
cdef object _default
Expand All @@ -112,8 +117,7 @@ cdef class Packer(object):
cdef bint autoreset
cdef bint datetime

def __cinit__(self):
cdef int buf_size = 1024*1024
def __cinit__(self, buf_size=1024*1024, **_kwargs):
self.pk.buf = <char*> PyMem_Malloc(buf_size)
if self.pk.buf == NULL:
raise MemoryError("Unable to allocate internal buffer.")
Expand All @@ -122,7 +126,7 @@ cdef class Packer(object):

def __init__(self, *, default=None,
bint use_single_float=False, bint autoreset=True, bint use_bin_type=True,
bint strict_types=False, bint datetime=False, unicode_errors=None):
bint strict_types=False, bint datetime=False, unicode_errors=None, buf_size=1024*1024):
self.use_float = use_single_float
self.strict_types = strict_types
self.autoreset = autoreset
Expand Down

0 comments on commit edb61db

Please sign in to comment.