summaryrefslogtreecommitdiff
path: root/msgpack/__init__.py
blob: 56a0b36c30dfca3b89b38b672d504d5a38f50124 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
# coding: utf-8
from msgpack._version import version
from msgpack.exceptions import *


class ExtType(object):
    __slots__ = ('code', 'data')

    def __init__(self, code, data):
        if not isinstance(code, int):
            raise TypeError("code must be int")
        if not isinstance(data, bytes):
            raise TypeError("data must be bytes")
        if not 0 <= code <= 127:
            raise ValueError("code must be 0~127")
        self.code = code
        self.data = data

    def __eq__(self, other):
        if not isinstance(other, ExtType):
            return NotImplemented
        return self.code == other.code and self.data == other.data

    def __hash__(self):
        return self.code ^ hash(self.data)

    def __repr__(self):
        return "msgpack.ExtType(%r, %r)" % (self.code, self.data)


import os
if os.environ.get('MSGPACK_PUREPYTHON'):
    from msgpack.fallback import Packer, unpack, unpackb, Unpacker
else:
    try:
        from msgpack._packer import Packer
        from msgpack._unpacker import unpack, unpackb, Unpacker
    except ImportError:
        from msgpack.fallback import Packer, unpack, unpackb, Unpacker


def pack(o, stream, **kwargs):
    """
    Pack object `o` and write it to `stream`

    See :class:`Packer` for options.
    """
    packer = Packer(**kwargs)
    stream.write(packer.pack(o))


def packb(o, **kwargs):
    """
    Pack object `o` and return packed bytes

    See :class:`Packer` for options.
    """
    return Packer(**kwargs).pack(o)

# alias for compatibility to simplejson/marshal/pickle.
load = unpack
loads = unpackb

dump = pack
dumps = packb