|
1 | 1 | import re
|
| 2 | +from enum import IntFlag |
2 | 3 | from typing import Any, Dict, Union, Optional
|
3 | 4 |
|
4 | 5 | import aiohttp # type: ignore
|
| 6 | +import msgspec.json |
5 | 7 |
|
6 | 8 | from interactions.client.const import get_logger
|
| 9 | +import importlib.util |
7 | 10 |
|
8 | 11 | __all__ = ("FastJson", "response_decode", "get_args", "get_first_word")
|
9 | 12 |
|
10 |
| -try: |
| 13 | +json_mode = "builtin" |
| 14 | + |
| 15 | +if importlib.util.find_spec("orjson"): |
11 | 16 | import orjson as json
|
12 | 17 |
|
13 |
| - orjson = True |
14 |
| -except ImportError: |
15 |
| - get_logger().warning("orjson not installed, built-in json library will be used") |
16 |
| - import json as json |
| 18 | + json_mode = "orjson" |
| 19 | +elif importlib.util.find_spec("ujson"): |
| 20 | + import ujson as json |
| 21 | + |
| 22 | + json_mode = "ujson" |
| 23 | +elif importlib.util.find_spec("msgspec"): |
| 24 | + import msgspec.json as json |
| 25 | + |
| 26 | + def enc_hook(obj: Any) -> int: |
| 27 | + # msgspec doesnt support IntFlags |
| 28 | + if isinstance(obj, IntFlag): |
| 29 | + return int(obj) |
| 30 | + raise TypeError(f"Object of type {type(obj)} is not JSON serializable") |
| 31 | + |
| 32 | + json.dumps = msgspec.json.Encoder(enc_hook=enc_hook).encode |
| 33 | + json.loads = msgspec.json.Decoder().decode |
| 34 | + |
| 35 | + json_mode = "msgspec" |
| 36 | +else: |
| 37 | + import json |
17 | 38 |
|
18 |
| - orjson = False |
| 39 | +get_logger().debug(f"Using {json_mode} for JSON encoding and decoding.") |
19 | 40 |
|
20 | 41 |
|
21 | 42 | _quotes = {
|
|
46 | 67 |
|
47 | 68 |
|
48 | 69 | class FastJson:
|
49 |
| - """Provides a fast way to encode and decode JSON data, using the orjson library if available, otherwise falls back to built-in json library.""" |
| 70 | + """Provides a fast way to encode and decode JSON data, using the fastest available library on the system.""" |
50 | 71 |
|
51 | 72 | @staticmethod
|
52 | 73 | def dumps(*args, **kwargs) -> str:
|
53 | 74 | data = json.dumps(*args, **kwargs)
|
54 |
| - if orjson: |
| 75 | + if json_mode in ("orjson", "msgspec"): |
55 | 76 | data = data.decode("utf-8")
|
56 | 77 | return data
|
57 | 78 |
|
|
0 commit comments