Skip to content
Merged
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Next Next commit
Allow users to specify Packer internal buf_size
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 <[email protected]>
  • Loading branch information
rtobar committed Jul 18, 2023
commit edb61db61e6822ebee632b94f6adb281cecdff8e
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