QuLab 2.10.10__cp313-cp313-win_amd64.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (107) hide show
  1. qulab/__init__.py +33 -0
  2. qulab/__main__.py +4 -0
  3. qulab/cli/__init__.py +0 -0
  4. qulab/cli/commands.py +30 -0
  5. qulab/cli/config.py +170 -0
  6. qulab/cli/decorators.py +28 -0
  7. qulab/dicttree.py +523 -0
  8. qulab/executor/__init__.py +5 -0
  9. qulab/executor/analyze.py +188 -0
  10. qulab/executor/cli.py +434 -0
  11. qulab/executor/load.py +563 -0
  12. qulab/executor/registry.py +185 -0
  13. qulab/executor/schedule.py +543 -0
  14. qulab/executor/storage.py +615 -0
  15. qulab/executor/template.py +259 -0
  16. qulab/executor/utils.py +194 -0
  17. qulab/expression.py +827 -0
  18. qulab/fun.cp313-win_amd64.pyd +0 -0
  19. qulab/monitor/__init__.py +1 -0
  20. qulab/monitor/__main__.py +8 -0
  21. qulab/monitor/config.py +41 -0
  22. qulab/monitor/dataset.py +77 -0
  23. qulab/monitor/event_queue.py +54 -0
  24. qulab/monitor/mainwindow.py +234 -0
  25. qulab/monitor/monitor.py +115 -0
  26. qulab/monitor/ploter.py +123 -0
  27. qulab/monitor/qt_compat.py +16 -0
  28. qulab/monitor/toolbar.py +265 -0
  29. qulab/scan/__init__.py +2 -0
  30. qulab/scan/curd.py +221 -0
  31. qulab/scan/models.py +554 -0
  32. qulab/scan/optimize.py +76 -0
  33. qulab/scan/query.py +387 -0
  34. qulab/scan/record.py +603 -0
  35. qulab/scan/scan.py +1166 -0
  36. qulab/scan/server.py +450 -0
  37. qulab/scan/space.py +213 -0
  38. qulab/scan/utils.py +234 -0
  39. qulab/storage/__init__.py +0 -0
  40. qulab/storage/__main__.py +51 -0
  41. qulab/storage/backend/__init__.py +0 -0
  42. qulab/storage/backend/redis.py +204 -0
  43. qulab/storage/base_dataset.py +352 -0
  44. qulab/storage/chunk.py +60 -0
  45. qulab/storage/dataset.py +127 -0
  46. qulab/storage/file.py +273 -0
  47. qulab/storage/models/__init__.py +22 -0
  48. qulab/storage/models/base.py +4 -0
  49. qulab/storage/models/config.py +28 -0
  50. qulab/storage/models/file.py +89 -0
  51. qulab/storage/models/ipy.py +58 -0
  52. qulab/storage/models/models.py +88 -0
  53. qulab/storage/models/record.py +161 -0
  54. qulab/storage/models/report.py +22 -0
  55. qulab/storage/models/tag.py +93 -0
  56. qulab/storage/storage.py +95 -0
  57. qulab/sys/__init__.py +2 -0
  58. qulab/sys/chat.py +688 -0
  59. qulab/sys/device/__init__.py +3 -0
  60. qulab/sys/device/basedevice.py +255 -0
  61. qulab/sys/device/loader.py +86 -0
  62. qulab/sys/device/utils.py +79 -0
  63. qulab/sys/drivers/FakeInstrument.py +68 -0
  64. qulab/sys/drivers/__init__.py +0 -0
  65. qulab/sys/ipy_events.py +125 -0
  66. qulab/sys/net/__init__.py +0 -0
  67. qulab/sys/net/bencoder.py +205 -0
  68. qulab/sys/net/cli.py +169 -0
  69. qulab/sys/net/dhcp.py +543 -0
  70. qulab/sys/net/dhcpd.py +176 -0
  71. qulab/sys/net/kad.py +1142 -0
  72. qulab/sys/net/kcp.py +192 -0
  73. qulab/sys/net/nginx.py +194 -0
  74. qulab/sys/progress.py +190 -0
  75. qulab/sys/rpc/__init__.py +0 -0
  76. qulab/sys/rpc/client.py +0 -0
  77. qulab/sys/rpc/exceptions.py +96 -0
  78. qulab/sys/rpc/msgpack.py +1052 -0
  79. qulab/sys/rpc/msgpack.pyi +41 -0
  80. qulab/sys/rpc/router.py +35 -0
  81. qulab/sys/rpc/rpc.py +412 -0
  82. qulab/sys/rpc/serialize.py +139 -0
  83. qulab/sys/rpc/server.py +29 -0
  84. qulab/sys/rpc/socket.py +29 -0
  85. qulab/sys/rpc/utils.py +25 -0
  86. qulab/sys/rpc/worker.py +0 -0
  87. qulab/sys/rpc/zmq_socket.py +227 -0
  88. qulab/tools/__init__.py +0 -0
  89. qulab/tools/connection_helper.py +39 -0
  90. qulab/typing.py +2 -0
  91. qulab/utils.py +95 -0
  92. qulab/version.py +1 -0
  93. qulab/visualization/__init__.py +188 -0
  94. qulab/visualization/__main__.py +71 -0
  95. qulab/visualization/_autoplot.py +464 -0
  96. qulab/visualization/plot_circ.py +319 -0
  97. qulab/visualization/plot_layout.py +408 -0
  98. qulab/visualization/plot_seq.py +242 -0
  99. qulab/visualization/qdat.py +152 -0
  100. qulab/visualization/rot3d.py +23 -0
  101. qulab/visualization/widgets.py +86 -0
  102. qulab-2.10.10.dist-info/METADATA +110 -0
  103. qulab-2.10.10.dist-info/RECORD +107 -0
  104. qulab-2.10.10.dist-info/WHEEL +5 -0
  105. qulab-2.10.10.dist-info/entry_points.txt +2 -0
  106. qulab-2.10.10.dist-info/licenses/LICENSE +21 -0
  107. qulab-2.10.10.dist-info/top_level.txt +1 -0
@@ -0,0 +1,1052 @@
1
+ # u-msgpack-python v2.8.0 - v at sergeev.io
2
+ # https://github.com/vsergeev/u-msgpack-python
3
+ #
4
+ # u-msgpack-python is a lightweight MessagePack serializer and deserializer
5
+ # module, compatible with both Python 2 and 3, as well CPython and PyPy
6
+ # implementations of Python. u-msgpack-python is fully compliant with the
7
+ # latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
8
+ # particular, it supports the new binary, UTF-8 string, and application ext
9
+ # types.
10
+ #
11
+ # MIT License
12
+ #
13
+ # Copyright (c) 2013-2023 vsergeev / Ivan (Vanya) A. Sergeev
14
+ #
15
+ # Permission is hereby granted, free of charge, to any person obtaining a copy
16
+ # of this software and associated documentation files (the "Software"), to deal
17
+ # in the Software without restriction, including without limitation the rights
18
+ # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
19
+ # copies of the Software, and to permit persons to whom the Software is
20
+ # furnished to do so, subject to the following conditions:
21
+ #
22
+ # The above copyright notice and this permission notice shall be included in
23
+ # all copies or substantial portions of the Software.
24
+ #
25
+ # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
26
+ # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
27
+ # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
28
+ # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
29
+ # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
30
+ # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
31
+ # THE SOFTWARE.
32
+ #
33
+ """
34
+ u-msgpack-python v2.8.0 - v at sergeev.io
35
+ https://github.com/vsergeev/u-msgpack-python
36
+
37
+ u-msgpack-python is a lightweight MessagePack serializer and deserializer
38
+ module, compatible with both Python 2 and 3, as well CPython and PyPy
39
+ implementations of Python. u-msgpack-python is fully compliant with the
40
+ latest MessagePack specification.com/msgpack/msgpack/blob/master/spec.md). In
41
+ particular, it supports the new binary, UTF-8 string, and application ext
42
+ types.
43
+
44
+ License: MIT
45
+ """
46
+ import collections
47
+ import datetime
48
+ import io
49
+ import struct
50
+ import sys
51
+ from collections.abc import Hashable
52
+
53
+ __version__ = "2.8.0"
54
+ "Module version string"
55
+
56
+ version = (2, 8, 0)
57
+ "Module version tuple"
58
+
59
+ ##############################################################################
60
+ # Ext Class
61
+ ##############################################################################
62
+
63
+
64
+ # Extension type for application-defined types and data
65
+ class Ext(object):
66
+ """
67
+ The Ext class facilitates creating a serializable extension object to store
68
+ an application-defined type and data byte array.
69
+ """
70
+
71
+ def __init__(self, type, data):
72
+ """
73
+ Construct a new Ext object.
74
+
75
+ Args:
76
+ type (int): application-defined type integer
77
+ data (bytes): application-defined data byte array
78
+
79
+ Raises:
80
+ TypeError:
81
+ Type is not an integer.
82
+ ValueError:
83
+ Type is out of range of -128 to 127.
84
+ TypeError:
85
+ Data is not type 'bytes' (Python 3) or not type 'str' (Python 2).
86
+
87
+ Example:
88
+ >>> foo = umsgpack.Ext(5, b"\\x01\\x02\\x03")
89
+ >>> umsgpack.packb({u"special stuff": foo, u"awesome": True})
90
+ '\\x82\\xa7awesome\\xc3\\xadspecial stuff\\xc7\\x03\\x05\\x01\\x02\\x03'
91
+ >>> bar = umsgpack.unpackb(_)
92
+ >>> print(bar["special stuff"])
93
+ Ext Object (Type: 5, Data: 01 02 03)
94
+ """
95
+ # Check type is type int and in range
96
+ if not isinstance(type, int):
97
+ raise TypeError("ext type is not type integer")
98
+ elif not (-2**7 <= type <= 2**7 - 1):
99
+ raise ValueError(
100
+ "ext type value {:d} is out of range (-128 to 127)".format(
101
+ type))
102
+ # Check data is type bytes or str
103
+ elif sys.version_info[0] == 3 and not isinstance(data, bytes):
104
+ raise TypeError("ext data is not type \'bytes\'")
105
+ elif sys.version_info[0] == 2 and not isinstance(data, str):
106
+ raise TypeError("ext data is not type \'str\'")
107
+
108
+ self.type = type
109
+ self.data = data
110
+
111
+ def __eq__(self, other):
112
+ """
113
+ Compare this Ext object with another for equality.
114
+ """
115
+ return isinstance(other, self.__class__) \
116
+ and self.type == other.type and self.data == other.data
117
+
118
+ def __ne__(self, other):
119
+ """
120
+ Compare this Ext object with another for inequality.
121
+ """
122
+ return not self.__eq__(other)
123
+
124
+ def __str__(self):
125
+ """
126
+ String representation of this Ext object.
127
+ """
128
+ s = "Ext Object (Type: {:d}, Data: ".format(self.type)
129
+ s += " ".join([
130
+ "0x{:02x}".format(ord(self.data[i:i + 1]))
131
+ for i in range(min(len(self.data), 8))
132
+ ])
133
+ if len(self.data) > 8:
134
+ s += " ..."
135
+ s += ")"
136
+ return s
137
+
138
+ def __hash__(self):
139
+ """
140
+ Provide a hash of this Ext object.
141
+ """
142
+ return hash((self.type, self.data))
143
+
144
+
145
+ class InvalidString(bytes):
146
+ """Subclass of bytes to hold invalid UTF-8 strings."""
147
+
148
+
149
+ ##############################################################################
150
+ # Ext Serializable Decorator
151
+ ##############################################################################
152
+
153
+ _ext_class_to_type = {}
154
+ _ext_type_to_class = {}
155
+
156
+
157
+ def ext_serializable(ext_type):
158
+ """
159
+ Return a decorator to register a class for automatic packing and unpacking
160
+ with the specified Ext type code. The application class should implement a
161
+ `packb()` method that returns serialized bytes, and an `unpackb()` class
162
+ method or static method that accepts serialized bytes and returns an
163
+ instance of the application class.
164
+
165
+ Args:
166
+ ext_type (int): application-defined Ext type code
167
+
168
+ Raises:
169
+ TypeError:
170
+ Ext type is not an integer.
171
+ ValueError:
172
+ Ext type is out of range of -128 to 127.
173
+ ValueError:
174
+ Ext type or class already registered.
175
+ """
176
+
177
+ def wrapper(cls):
178
+ if not isinstance(ext_type, int):
179
+ raise TypeError("Ext type is not type integer")
180
+ elif not (-2**7 <= ext_type <= 2**7 - 1):
181
+ raise ValueError(
182
+ "Ext type value {:d} is out of range of -128 to 127".format(
183
+ ext_type))
184
+ elif ext_type in _ext_type_to_class:
185
+ raise ValueError(
186
+ "Ext type {:d} already registered with class {:s}".format(
187
+ ext_type, repr(_ext_type_to_class[ext_type])))
188
+ elif cls in _ext_class_to_type:
189
+ raise ValueError(
190
+ "Class {:s} already registered with Ext type {:d}".format(
191
+ repr(cls), ext_type))
192
+
193
+ _ext_type_to_class[ext_type] = cls
194
+ _ext_class_to_type[cls] = ext_type
195
+
196
+ return cls
197
+
198
+ return wrapper
199
+
200
+
201
+ ##############################################################################
202
+ # Exceptions
203
+ ##############################################################################
204
+
205
+
206
+ # Base Exception classes
207
+ class PackException(Exception):
208
+ "Base class for exceptions encountered during packing."
209
+
210
+
211
+ class UnpackException(Exception):
212
+ "Base class for exceptions encountered during unpacking."
213
+
214
+
215
+ # Packing error
216
+ class UnsupportedTypeException(PackException):
217
+ "Object type not supported for packing."
218
+
219
+
220
+ # Unpacking error
221
+ class InsufficientDataException(UnpackException):
222
+ "Insufficient data to unpack the serialized object."
223
+
224
+
225
+ class InvalidStringException(UnpackException):
226
+ "Invalid UTF-8 string encountered during unpacking."
227
+
228
+
229
+ class UnsupportedTimestampException(UnpackException):
230
+ "Unsupported timestamp format encountered during unpacking."
231
+
232
+
233
+ class ReservedCodeException(UnpackException):
234
+ "Reserved code encountered during unpacking."
235
+
236
+
237
+ class UnhashableKeyException(UnpackException):
238
+ """
239
+ Unhashable key encountered during map unpacking.
240
+ The serialized map cannot be deserialized into a Python dictionary.
241
+ """
242
+
243
+
244
+ class DuplicateKeyException(UnpackException):
245
+ "Duplicate key encountered during map unpacking."
246
+
247
+
248
+ # Backwards compatibility
249
+ KeyNotPrimitiveException = UnhashableKeyException
250
+ KeyDuplicateException = DuplicateKeyException
251
+
252
+ #############################################################################
253
+ # Exported Functions and Glob
254
+ #############################################################################
255
+
256
+ # Exported functions and variables, set up in __init()
257
+ pack = None
258
+ packb = None
259
+ unpack = None
260
+ unpackb = None
261
+ dump = None
262
+ dumps = None
263
+ load = None
264
+ loads = None
265
+
266
+ compatibility = False
267
+ """
268
+ Compatibility mode boolean.
269
+
270
+ When compatibility mode is enabled, u-msgpack-python will serialize both
271
+ unicode strings and bytes into the old "raw" msgpack type, and deserialize the
272
+ "raw" msgpack type into bytes. This provides backwards compatibility with the
273
+ old MessagePack specification.
274
+
275
+ Example:
276
+ >>> umsgpack.compatibility = True
277
+ >>> umsgpack.packb([u"some string", b"some bytes"])
278
+ b'\\x92\\xabsome string\\xaasome bytes'
279
+ >>> umsgpack.unpackb(_)
280
+ [b'some string', b'some bytes']
281
+ """
282
+
283
+ ##############################################################################
284
+ # Packing
285
+ ##############################################################################
286
+
287
+ # You may notice struct.pack("B", obj) instead of the simpler chr(obj) in the
288
+ # code below. This is to allow for seamless Python 2 and 3 compatibility, as
289
+ # chr(obj) has a str return type instead of bytes in Python 3, and
290
+ # struct.pack(...) has the right return type in both versions.
291
+
292
+
293
+ def _pack_integer(obj, fp, options):
294
+ if obj < 0:
295
+ if obj >= -32:
296
+ fp.write(struct.pack("b", obj))
297
+ elif obj >= -2**(8 - 1):
298
+ fp.write(b"\xd0" + struct.pack("b", obj))
299
+ elif obj >= -2**(16 - 1):
300
+ fp.write(b"\xd1" + struct.pack(">h", obj))
301
+ elif obj >= -2**(32 - 1):
302
+ fp.write(b"\xd2" + struct.pack(">i", obj))
303
+ elif obj >= -2**(64 - 1):
304
+ fp.write(b"\xd3" + struct.pack(">q", obj))
305
+ else:
306
+ raise UnsupportedTypeException("huge signed int")
307
+ else:
308
+ if obj < 128:
309
+ fp.write(struct.pack("B", obj))
310
+ elif obj < 2**8:
311
+ fp.write(b"\xcc" + struct.pack("B", obj))
312
+ elif obj < 2**16:
313
+ fp.write(b"\xcd" + struct.pack(">H", obj))
314
+ elif obj < 2**32:
315
+ fp.write(b"\xce" + struct.pack(">I", obj))
316
+ elif obj < 2**64:
317
+ fp.write(b"\xcf" + struct.pack(">Q", obj))
318
+ else:
319
+ raise UnsupportedTypeException("huge unsigned int")
320
+
321
+
322
+ def _pack_nil(obj, fp, options):
323
+ fp.write(b"\xc0")
324
+
325
+
326
+ def _pack_boolean(obj, fp, options):
327
+ fp.write(b"\xc3" if obj else b"\xc2")
328
+
329
+
330
+ def _pack_float(obj, fp, options):
331
+ float_precision = options.get('force_float_precision', _float_precision)
332
+
333
+ if float_precision == "double":
334
+ fp.write(b"\xcb" + struct.pack(">d", obj))
335
+ elif float_precision == "single":
336
+ fp.write(b"\xca" + struct.pack(">f", obj))
337
+ else:
338
+ raise ValueError("invalid float precision")
339
+
340
+
341
+ def _pack_string(obj, fp, options):
342
+ obj = obj.encode('utf-8')
343
+ obj_len = len(obj)
344
+ if obj_len < 32:
345
+ fp.write(struct.pack("B", 0xa0 | obj_len) + obj)
346
+ elif obj_len < 2**8:
347
+ fp.write(b"\xd9" + struct.pack("B", obj_len) + obj)
348
+ elif obj_len < 2**16:
349
+ fp.write(b"\xda" + struct.pack(">H", obj_len) + obj)
350
+ elif obj_len < 2**32:
351
+ fp.write(b"\xdb" + struct.pack(">I", obj_len) + obj)
352
+ else:
353
+ raise UnsupportedTypeException("huge string")
354
+
355
+
356
+ def _pack_binary(obj, fp, options):
357
+ obj_len = len(obj)
358
+ if obj_len < 2**8:
359
+ fp.write(b"\xc4" + struct.pack("B", obj_len) + obj)
360
+ elif obj_len < 2**16:
361
+ fp.write(b"\xc5" + struct.pack(">H", obj_len) + obj)
362
+ elif obj_len < 2**32:
363
+ fp.write(b"\xc6" + struct.pack(">I", obj_len) + obj)
364
+ else:
365
+ raise UnsupportedTypeException("huge binary string")
366
+
367
+
368
+ def _pack_oldspec_raw(obj, fp, options):
369
+ obj_len = len(obj)
370
+ if obj_len < 32:
371
+ fp.write(struct.pack("B", 0xa0 | obj_len) + obj)
372
+ elif obj_len < 2**16:
373
+ fp.write(b"\xda" + struct.pack(">H", obj_len) + obj)
374
+ elif obj_len < 2**32:
375
+ fp.write(b"\xdb" + struct.pack(">I", obj_len) + obj)
376
+ else:
377
+ raise UnsupportedTypeException("huge raw string")
378
+
379
+
380
+ def _pack_ext(obj, fp, options):
381
+ obj_len = len(obj.data)
382
+ if obj_len == 1:
383
+ fp.write(b"\xd4" + struct.pack("B", obj.type & 0xff) + obj.data)
384
+ elif obj_len == 2:
385
+ fp.write(b"\xd5" + struct.pack("B", obj.type & 0xff) + obj.data)
386
+ elif obj_len == 4:
387
+ fp.write(b"\xd6" + struct.pack("B", obj.type & 0xff) + obj.data)
388
+ elif obj_len == 8:
389
+ fp.write(b"\xd7" + struct.pack("B", obj.type & 0xff) + obj.data)
390
+ elif obj_len == 16:
391
+ fp.write(b"\xd8" + struct.pack("B", obj.type & 0xff) + obj.data)
392
+ elif obj_len < 2**8:
393
+ fp.write(b"\xc7" + struct.pack("BB", obj_len, obj.type & 0xff) +
394
+ obj.data)
395
+ elif obj_len < 2**16:
396
+ fp.write(b"\xc8" + struct.pack(">HB", obj_len, obj.type & 0xff) +
397
+ obj.data)
398
+ elif obj_len < 2**32:
399
+ fp.write(b"\xc9" + struct.pack(">IB", obj_len, obj.type & 0xff) +
400
+ obj.data)
401
+ else:
402
+ raise UnsupportedTypeException("huge ext data")
403
+
404
+
405
+ def _pack_ext_timestamp(obj, fp, options):
406
+ if not obj.tzinfo:
407
+ # Object is naive datetime, convert to aware date time,
408
+ # assuming UTC timezone
409
+ delta = obj.replace(tzinfo=_utc_tzinfo) - _epoch
410
+ else:
411
+ # Object is aware datetime
412
+ delta = obj - _epoch
413
+
414
+ seconds = delta.seconds + delta.days * 86400
415
+ microseconds = delta.microseconds
416
+
417
+ if microseconds == 0 and 0 <= seconds <= 2**32 - 1:
418
+ # 32-bit timestamp
419
+ fp.write(b"\xd6\xff" + struct.pack(">I", seconds))
420
+ elif 0 <= seconds <= 2**34 - 1:
421
+ # 64-bit timestamp
422
+ value = ((microseconds * 1000) << 34) | seconds
423
+ fp.write(b"\xd7\xff" + struct.pack(">Q", value))
424
+ elif -2**63 <= abs(seconds) <= 2**63 - 1:
425
+ # 96-bit timestamp
426
+ fp.write(b"\xc7\x0c\xff" +
427
+ struct.pack(">Iq", microseconds * 1000, seconds))
428
+ else:
429
+ raise UnsupportedTypeException("huge timestamp")
430
+
431
+
432
+ def _pack_array(obj, fp, options):
433
+ obj_len = len(obj)
434
+ if obj_len < 16:
435
+ fp.write(struct.pack("B", 0x90 | obj_len))
436
+ elif obj_len < 2**16:
437
+ fp.write(b"\xdc" + struct.pack(">H", obj_len))
438
+ elif obj_len < 2**32:
439
+ fp.write(b"\xdd" + struct.pack(">I", obj_len))
440
+ else:
441
+ raise UnsupportedTypeException("huge array")
442
+
443
+ for e in obj:
444
+ pack(e, fp, **options)
445
+
446
+
447
+ def _pack_map(obj, fp, options):
448
+ obj_len = len(obj)
449
+ if obj_len < 16:
450
+ fp.write(struct.pack("B", 0x80 | obj_len))
451
+ elif obj_len < 2**16:
452
+ fp.write(b"\xde" + struct.pack(">H", obj_len))
453
+ elif obj_len < 2**32:
454
+ fp.write(b"\xdf" + struct.pack(">I", obj_len))
455
+ else:
456
+ raise UnsupportedTypeException("huge array")
457
+
458
+ for k, v in obj.items():
459
+ pack(k, fp, **options)
460
+ pack(v, fp, **options)
461
+
462
+
463
+ ########################################
464
+
465
+
466
+ # Pack for Python 3, with unicode 'str' type, 'bytes' type, and no 'long' type
467
+ def _pack3(obj, fp, **options):
468
+ """
469
+ Serialize a Python object into MessagePack bytes.
470
+
471
+ Args:
472
+ obj: a Python object
473
+ fp: a .write()-supporting file-like object
474
+
475
+ Keyword Args:
476
+ ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
477
+ to a callable that packs an instance of the type
478
+ into an Ext object
479
+ force_float_precision (str): "single" to force packing floats as
480
+ IEEE-754 single-precision floats,
481
+ "double" to force packing floats as
482
+ IEEE-754 double-precision floats
483
+
484
+ Returns:
485
+ None
486
+
487
+ Raises:
488
+ UnsupportedTypeException(PackException):
489
+ Object type not supported for packing.
490
+
491
+ Example:
492
+ >>> f = open('test.bin', 'wb')
493
+ >>> umsgpack.pack({u"compact": True, u"schema": 0}, f)
494
+ """
495
+ global compatibility
496
+
497
+ ext_handlers = options.get("ext_handlers")
498
+
499
+ if obj is None:
500
+ _pack_nil(obj, fp, options)
501
+ elif ext_handlers and obj.__class__ in ext_handlers:
502
+ _pack_ext(ext_handlers[obj.__class__](obj), fp, options)
503
+ elif obj.__class__ in _ext_class_to_type:
504
+ try:
505
+ _pack_ext(Ext(_ext_class_to_type[obj.__class__], obj.packb()), fp,
506
+ options)
507
+ except AttributeError:
508
+ raise NotImplementedError(
509
+ "Ext serializable class {:s} is missing implementation of packb()"
510
+ .format(repr(obj.__class__)))
511
+ elif isinstance(obj, bool):
512
+ _pack_boolean(obj, fp, options)
513
+ elif isinstance(obj, int):
514
+ _pack_integer(obj, fp, options)
515
+ elif isinstance(obj, float):
516
+ _pack_float(obj, fp, options)
517
+ elif compatibility and isinstance(obj, str):
518
+ _pack_oldspec_raw(obj.encode('utf-8'), fp, options)
519
+ elif compatibility and isinstance(obj, bytes):
520
+ _pack_oldspec_raw(obj, fp, options)
521
+ elif isinstance(obj, str):
522
+ _pack_string(obj, fp, options)
523
+ elif isinstance(obj, bytes):
524
+ _pack_binary(obj, fp, options)
525
+ elif isinstance(obj, (list, tuple)):
526
+ _pack_array(obj, fp, options)
527
+ elif isinstance(obj, dict):
528
+ _pack_map(obj, fp, options)
529
+ elif isinstance(obj, datetime.datetime):
530
+ _pack_ext_timestamp(obj, fp, options)
531
+ elif isinstance(obj, Ext):
532
+ _pack_ext(obj, fp, options)
533
+ elif ext_handlers:
534
+ # Linear search for superclass
535
+ t = next((t for t in ext_handlers.keys() if isinstance(obj, t)), None)
536
+ if t:
537
+ _pack_ext(ext_handlers[t](obj), fp, options)
538
+ else:
539
+ raise UnsupportedTypeException("unsupported type: {:s}".format(
540
+ str(type(obj))))
541
+ elif _ext_class_to_type:
542
+ # Linear search for superclass
543
+ t = next((t for t in _ext_class_to_type if isinstance(obj, t)), None)
544
+ if t:
545
+ try:
546
+ _pack_ext(Ext(_ext_class_to_type[t], obj.packb()), fp, options)
547
+ except AttributeError:
548
+ raise NotImplementedError(
549
+ "Ext serializable class {:s} is missing implementation of packb()"
550
+ .format(repr(t)))
551
+ else:
552
+ raise UnsupportedTypeException("unsupported type: {:s}".format(
553
+ str(type(obj))))
554
+ else:
555
+ raise UnsupportedTypeException("unsupported type: {:s}".format(
556
+ str(type(obj))))
557
+
558
+
559
+ def _packb3(obj, **options):
560
+ """
561
+ Serialize a Python object into MessagePack bytes.
562
+
563
+ Args:
564
+ obj: a Python object
565
+
566
+ Keyword Args:
567
+ ext_handlers (dict): dictionary of Ext handlers, mapping a custom type
568
+ to a callable that packs an instance of the type
569
+ into an Ext object
570
+ force_float_precision (str): "single" to force packing floats as
571
+ IEEE-754 single-precision floats,
572
+ "double" to force packing floats as
573
+ IEEE-754 double-precision floats
574
+
575
+ Returns:
576
+ bytes: Serialized MessagePack bytes
577
+
578
+ Raises:
579
+ UnsupportedTypeException(PackException):
580
+ Object type not supported for packing.
581
+
582
+ Example:
583
+ >>> umsgpack.packb({u"compact": True, u"schema": 0})
584
+ b'\\x82\\xa7compact\\xc3\\xa6schema\\x00'
585
+ """
586
+ fp = io.BytesIO()
587
+ _pack3(obj, fp, **options)
588
+ return fp.getvalue()
589
+
590
+
591
+ #############################################################################
592
+ # Unpacking
593
+ #############################################################################
594
+
595
+
596
+ def _read_except(fp, n):
597
+ if n == 0:
598
+ return b""
599
+
600
+ data = fp.read(n)
601
+ if len(data) == 0:
602
+ raise InsufficientDataException()
603
+
604
+ while len(data) < n:
605
+ chunk = fp.read(n - len(data))
606
+ if len(chunk) == 0:
607
+ raise InsufficientDataException()
608
+
609
+ data += chunk
610
+
611
+ return data
612
+
613
+
614
+ def _unpack_integer(code, fp, options):
615
+ if (ord(code) & 0xe0) == 0xe0:
616
+ return struct.unpack("b", code)[0]
617
+ elif code == b'\xd0':
618
+ return struct.unpack("b", _read_except(fp, 1))[0]
619
+ elif code == b'\xd1':
620
+ return struct.unpack(">h", _read_except(fp, 2))[0]
621
+ elif code == b'\xd2':
622
+ return struct.unpack(">i", _read_except(fp, 4))[0]
623
+ elif code == b'\xd3':
624
+ return struct.unpack(">q", _read_except(fp, 8))[0]
625
+ elif (ord(code) & 0x80) == 0x00:
626
+ return struct.unpack("B", code)[0]
627
+ elif code == b'\xcc':
628
+ return struct.unpack("B", _read_except(fp, 1))[0]
629
+ elif code == b'\xcd':
630
+ return struct.unpack(">H", _read_except(fp, 2))[0]
631
+ elif code == b'\xce':
632
+ return struct.unpack(">I", _read_except(fp, 4))[0]
633
+ elif code == b'\xcf':
634
+ return struct.unpack(">Q", _read_except(fp, 8))[0]
635
+ raise Exception("logic error, not int: 0x{:02x}".format(ord(code)))
636
+
637
+
638
+ def _unpack_reserved(code, fp, options):
639
+ if code == b'\xc1':
640
+ raise ReservedCodeException(
641
+ "encountered reserved code: 0x{:02x}".format(ord(code)))
642
+ raise Exception("logic error, not reserved code: 0x{:02x}".format(
643
+ ord(code)))
644
+
645
+
646
+ def _unpack_nil(code, fp, options):
647
+ if code == b'\xc0':
648
+ return None
649
+ raise Exception("logic error, not nil: 0x{:02x}".format(ord(code)))
650
+
651
+
652
+ def _unpack_boolean(code, fp, options):
653
+ if code == b'\xc2':
654
+ return False
655
+ elif code == b'\xc3':
656
+ return True
657
+ raise Exception("logic error, not boolean: 0x{:02x}".format(ord(code)))
658
+
659
+
660
+ def _unpack_float(code, fp, options):
661
+ if code == b'\xca':
662
+ return struct.unpack(">f", _read_except(fp, 4))[0]
663
+ elif code == b'\xcb':
664
+ return struct.unpack(">d", _read_except(fp, 8))[0]
665
+ raise Exception("logic error, not float: 0x{:02x}".format(ord(code)))
666
+
667
+
668
+ def _unpack_string(code, fp, options):
669
+ if (ord(code) & 0xe0) == 0xa0:
670
+ length = ord(code) & ~0xe0
671
+ elif code == b'\xd9':
672
+ length = struct.unpack("B", _read_except(fp, 1))[0]
673
+ elif code == b'\xda':
674
+ length = struct.unpack(">H", _read_except(fp, 2))[0]
675
+ elif code == b'\xdb':
676
+ length = struct.unpack(">I", _read_except(fp, 4))[0]
677
+ else:
678
+ raise Exception("logic error, not string: 0x{:02x}".format(ord(code)))
679
+
680
+ # Always return raw bytes in compatibility mode
681
+ global compatibility
682
+ if compatibility:
683
+ return _read_except(fp, length)
684
+
685
+ data = _read_except(fp, length)
686
+ try:
687
+ return bytes.decode(data, 'utf-8')
688
+ except UnicodeDecodeError:
689
+ if options.get("allow_invalid_utf8"):
690
+ return InvalidString(data)
691
+ raise InvalidStringException("unpacked string is invalid utf-8")
692
+
693
+
694
+ def _unpack_binary(code, fp, options):
695
+ if code == b'\xc4':
696
+ length = struct.unpack("B", _read_except(fp, 1))[0]
697
+ elif code == b'\xc5':
698
+ length = struct.unpack(">H", _read_except(fp, 2))[0]
699
+ elif code == b'\xc6':
700
+ length = struct.unpack(">I", _read_except(fp, 4))[0]
701
+ else:
702
+ raise Exception("logic error, not binary: 0x{:02x}".format(ord(code)))
703
+
704
+ return _read_except(fp, length)
705
+
706
+
707
+ def _unpack_ext(code, fp, options):
708
+ if code == b'\xd4':
709
+ length = 1
710
+ elif code == b'\xd5':
711
+ length = 2
712
+ elif code == b'\xd6':
713
+ length = 4
714
+ elif code == b'\xd7':
715
+ length = 8
716
+ elif code == b'\xd8':
717
+ length = 16
718
+ elif code == b'\xc7':
719
+ length = struct.unpack("B", _read_except(fp, 1))[0]
720
+ elif code == b'\xc8':
721
+ length = struct.unpack(">H", _read_except(fp, 2))[0]
722
+ elif code == b'\xc9':
723
+ length = struct.unpack(">I", _read_except(fp, 4))[0]
724
+ else:
725
+ raise Exception("logic error, not ext: 0x{:02x}".format(ord(code)))
726
+
727
+ ext_type = struct.unpack("b", _read_except(fp, 1))[0]
728
+ ext_data = _read_except(fp, length)
729
+
730
+ # Unpack with ext handler, if we have one
731
+ ext_handlers = options.get("ext_handlers")
732
+ if ext_handlers and ext_type in ext_handlers:
733
+ return ext_handlers[ext_type](Ext(ext_type, ext_data))
734
+
735
+ # Unpack with ext classes, if type is registered
736
+ if ext_type in _ext_type_to_class:
737
+ try:
738
+ return _ext_type_to_class[ext_type].unpackb(ext_data)
739
+ except AttributeError:
740
+ raise NotImplementedError(
741
+ "Ext serializable class {:s} is missing implementation of unpackb()"
742
+ .format(repr(_ext_type_to_class[ext_type])))
743
+
744
+ # Timestamp extension
745
+ if ext_type == -1:
746
+ return _unpack_ext_timestamp(ext_data, options)
747
+
748
+ return Ext(ext_type, ext_data)
749
+
750
+
751
+ def _unpack_ext_timestamp(ext_data, options):
752
+ obj_len = len(ext_data)
753
+ if obj_len == 4:
754
+ # 32-bit timestamp
755
+ seconds = struct.unpack(">I", ext_data)[0]
756
+ microseconds = 0
757
+ elif obj_len == 8:
758
+ # 64-bit timestamp
759
+ value = struct.unpack(">Q", ext_data)[0]
760
+ seconds = value & 0x3ffffffff
761
+ microseconds = (value >> 34) // 1000
762
+ elif obj_len == 12:
763
+ # 96-bit timestamp
764
+ seconds = struct.unpack(">q", ext_data[4:12])[0]
765
+ microseconds = struct.unpack(">I", ext_data[0:4])[0] // 1000
766
+ else:
767
+ raise UnsupportedTimestampException(
768
+ "unsupported timestamp with data length {:d}".format(
769
+ len(ext_data)))
770
+
771
+ return _epoch + datetime.timedelta(seconds=seconds,
772
+ microseconds=microseconds)
773
+
774
+
775
+ def _unpack_array(code, fp, options):
776
+ if (ord(code) & 0xf0) == 0x90:
777
+ length = (ord(code) & ~0xf0)
778
+ elif code == b'\xdc':
779
+ length = struct.unpack(">H", _read_except(fp, 2))[0]
780
+ elif code == b'\xdd':
781
+ length = struct.unpack(">I", _read_except(fp, 4))[0]
782
+ else:
783
+ raise Exception("logic error, not array: 0x{:02x}".format(ord(code)))
784
+
785
+ if options.get('use_tuple'):
786
+ return tuple((_unpack(fp, options) for i in range(length)))
787
+
788
+ return [_unpack(fp, options) for i in range(length)]
789
+
790
+
791
+ def _deep_list_to_tuple(obj):
792
+ if isinstance(obj, list):
793
+ return tuple([_deep_list_to_tuple(e) for e in obj])
794
+ return obj
795
+
796
+
797
+ def _unpack_map(code, fp, options):
798
+ if (ord(code) & 0xf0) == 0x80:
799
+ length = (ord(code) & ~0xf0)
800
+ elif code == b'\xde':
801
+ length = struct.unpack(">H", _read_except(fp, 2))[0]
802
+ elif code == b'\xdf':
803
+ length = struct.unpack(">I", _read_except(fp, 4))[0]
804
+ else:
805
+ raise Exception("logic error, not map: 0x{:02x}".format(ord(code)))
806
+
807
+ d = {} if not options.get('use_ordered_dict') else collections.OrderedDict(
808
+ )
809
+ for _ in range(length):
810
+ # Unpack key
811
+ k = _unpack(fp, options)
812
+
813
+ if isinstance(k, list):
814
+ # Attempt to convert list into a hashable tuple
815
+ k = _deep_list_to_tuple(k)
816
+ elif not isinstance(k, Hashable):
817
+ raise UnhashableKeyException(
818
+ "encountered unhashable key: \"{:s}\" ({:s})".format(
819
+ str(k), str(type(k))))
820
+ elif k in d:
821
+ raise DuplicateKeyException(
822
+ "encountered duplicate key: \"{:s}\" ({:s})".format(
823
+ str(k), str(type(k))))
824
+
825
+ # Unpack value
826
+ v = _unpack(fp, options)
827
+
828
+ try:
829
+ d[k] = v
830
+ except TypeError:
831
+ raise UnhashableKeyException(
832
+ "encountered unhashable key: \"{:s}\"".format(str(k)))
833
+ return d
834
+
835
+
836
+ def _unpack(fp, options):
837
+ code = _read_except(fp, 1)
838
+ return _unpack_dispatch_table[code](code, fp, options)
839
+
840
+
841
+ ########################################
842
+
843
+
844
+ def _unpack3(fp, **options):
845
+ """
846
+ Deserialize MessagePack bytes into a Python object.
847
+
848
+ Args:
849
+ fp: a .read()-supporting file-like object
850
+
851
+ Keyword Args:
852
+ ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext
853
+ type to a callable that unpacks an instance of
854
+ Ext into an object
855
+ use_ordered_dict (bool): unpack maps into OrderedDict, instead of dict
856
+ (default False)
857
+ use_tuple (bool): unpacks arrays into tuples, instead of lists (default
858
+ False)
859
+ allow_invalid_utf8 (bool): unpack invalid strings into instances of
860
+ :class:`InvalidString`, for access to the
861
+ bytes (default False)
862
+
863
+ Returns:
864
+ Python object
865
+
866
+ Raises:
867
+ InsufficientDataException(UnpackException):
868
+ Insufficient data to unpack the serialized object.
869
+ InvalidStringException(UnpackException):
870
+ Invalid UTF-8 string encountered during unpacking.
871
+ UnsupportedTimestampException(UnpackException):
872
+ Unsupported timestamp format encountered during unpacking.
873
+ ReservedCodeException(UnpackException):
874
+ Reserved code encountered during unpacking.
875
+ UnhashableKeyException(UnpackException):
876
+ Unhashable key encountered during map unpacking.
877
+ The serialized map cannot be deserialized into a Python dictionary.
878
+ DuplicateKeyException(UnpackException):
879
+ Duplicate key encountered during map unpacking.
880
+
881
+ Example:
882
+ >>> f = open('test.bin', 'rb')
883
+ >>> umsgpack.unpackb(f)
884
+ {'compact': True, 'schema': 0}
885
+ """
886
+ return _unpack(fp, options)
887
+
888
+
889
+ # For Python 3, expects a bytes object
890
+ def _unpackb3(s, **options):
891
+ """
892
+ Deserialize MessagePack bytes into a Python object.
893
+
894
+ Args:
895
+ s (bytes, bytearray): serialized MessagePack bytes
896
+
897
+ Keyword Args:
898
+ ext_handlers (dict): dictionary of Ext handlers, mapping integer Ext
899
+ type to a callable that unpacks an instance of
900
+ Ext into an object
901
+ use_ordered_dict (bool): unpack maps into OrderedDict, instead of dict
902
+ (default False)
903
+ use_tuple (bool): unpacks arrays into tuples, instead of lists (default
904
+ False)
905
+ allow_invalid_utf8 (bool): unpack invalid strings into instances of
906
+ :class:`InvalidString`, for access to the
907
+ bytes (default False)
908
+
909
+ Returns:
910
+ Python object
911
+
912
+ Raises:
913
+ TypeError:
914
+ Packed data type is neither 'bytes' nor 'bytearray'.
915
+ InsufficientDataException(UnpackException):
916
+ Insufficient data to unpack the serialized object.
917
+ InvalidStringException(UnpackException):
918
+ Invalid UTF-8 string encountered during unpacking.
919
+ UnsupportedTimestampException(UnpackException):
920
+ Unsupported timestamp format encountered during unpacking.
921
+ ReservedCodeException(UnpackException):
922
+ Reserved code encountered during unpacking.
923
+ UnhashableKeyException(UnpackException):
924
+ Unhashable key encountered during map unpacking.
925
+ The serialized map cannot be deserialized into a Python dictionary.
926
+ DuplicateKeyException(UnpackException):
927
+ Duplicate key encountered during map unpacking.
928
+
929
+ Example:
930
+ >>> umsgpack.unpackb(b'\\x82\\xa7compact\\xc3\\xa6schema\\x00')
931
+ {'compact': True, 'schema': 0}
932
+ """
933
+ if not isinstance(s, (bytes, bytearray)):
934
+ raise TypeError("packed data must be type 'bytes' or 'bytearray'")
935
+ return _unpack(io.BytesIO(s), options)
936
+
937
+
938
+ #############################################################################
939
+ # Module Initialization
940
+ #############################################################################
941
+
942
+
943
+ def __init():
944
+ global pack
945
+ global packb
946
+ global unpack
947
+ global unpackb
948
+ global dump
949
+ global dumps
950
+ global load
951
+ global loads
952
+ global compatibility
953
+ global _epoch
954
+ global _utc_tzinfo
955
+ global _float_precision
956
+ global _unpack_dispatch_table
957
+
958
+ # Compatibility mode for handling strings/bytes with the old specification
959
+ compatibility = False
960
+
961
+ if sys.version_info[0] == 3:
962
+ _utc_tzinfo = datetime.timezone.utc
963
+ else:
964
+
965
+ class UTC(datetime.tzinfo):
966
+ ZERO = datetime.timedelta(0)
967
+
968
+ def utcoffset(self, dt):
969
+ return UTC.ZERO
970
+
971
+ def tzname(self, dt):
972
+ return "UTC"
973
+
974
+ def dst(self, dt):
975
+ return UTC.ZERO
976
+
977
+ _utc_tzinfo = UTC()
978
+
979
+ # Calculate an aware epoch datetime
980
+ _epoch = datetime.datetime(1970, 1, 1, tzinfo=_utc_tzinfo)
981
+
982
+ # Auto-detect system float precision
983
+ if sys.float_info.mant_dig == 53:
984
+ _float_precision = "double"
985
+ else:
986
+ _float_precision = "single"
987
+
988
+ # Map packb and unpackb to the appropriate version
989
+ pack = _pack3
990
+ packb = _packb3
991
+ dump = _pack3
992
+ dumps = _packb3
993
+ unpack = _unpack3
994
+ unpackb = _unpackb3
995
+ load = _unpack3
996
+ loads = _unpackb3
997
+
998
+ # Build a dispatch table for fast lookup of unpacking function
999
+
1000
+ _unpack_dispatch_table = {}
1001
+ # Fix uint
1002
+ for code in range(0, 0x7f + 1):
1003
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
1004
+ # Fix map
1005
+ for code in range(0x80, 0x8f + 1):
1006
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_map
1007
+ # Fix array
1008
+ for code in range(0x90, 0x9f + 1):
1009
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_array
1010
+ # Fix str
1011
+ for code in range(0xa0, 0xbf + 1):
1012
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
1013
+ # Nil
1014
+ _unpack_dispatch_table[b'\xc0'] = _unpack_nil
1015
+ # Reserved
1016
+ _unpack_dispatch_table[b'\xc1'] = _unpack_reserved
1017
+ # Boolean
1018
+ _unpack_dispatch_table[b'\xc2'] = _unpack_boolean
1019
+ _unpack_dispatch_table[b'\xc3'] = _unpack_boolean
1020
+ # Bin
1021
+ for code in range(0xc4, 0xc6 + 1):
1022
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_binary
1023
+ # Ext
1024
+ for code in range(0xc7, 0xc9 + 1):
1025
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
1026
+ # Float
1027
+ _unpack_dispatch_table[b'\xca'] = _unpack_float
1028
+ _unpack_dispatch_table[b'\xcb'] = _unpack_float
1029
+ # Uint
1030
+ for code in range(0xcc, 0xcf + 1):
1031
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
1032
+ # Int
1033
+ for code in range(0xd0, 0xd3 + 1):
1034
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
1035
+ # Fixext
1036
+ for code in range(0xd4, 0xd8 + 1):
1037
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_ext
1038
+ # String
1039
+ for code in range(0xd9, 0xdb + 1):
1040
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_string
1041
+ # Array
1042
+ _unpack_dispatch_table[b'\xdc'] = _unpack_array
1043
+ _unpack_dispatch_table[b'\xdd'] = _unpack_array
1044
+ # Map
1045
+ _unpack_dispatch_table[b'\xde'] = _unpack_map
1046
+ _unpack_dispatch_table[b'\xdf'] = _unpack_map
1047
+ # Negative fixint
1048
+ for code in range(0xe0, 0xff + 1):
1049
+ _unpack_dispatch_table[struct.pack("B", code)] = _unpack_integer
1050
+
1051
+
1052
+ __init()