Skip to content

Commit d4738f1

Browse files
committed
feat: support orjson, ujson, and msgspec
1 parent bffc1cf commit d4738f1

File tree

1 file changed

+29
-8
lines changed

1 file changed

+29
-8
lines changed

interactions/client/utils/input_utils.py

Lines changed: 29 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,21 +1,42 @@
11
import re
2+
from enum import IntFlag
23
from typing import Any, Dict, Union, Optional
34

45
import aiohttp # type: ignore
6+
import msgspec.json
57

68
from interactions.client.const import get_logger
9+
import importlib.util
710

811
__all__ = ("FastJson", "response_decode", "get_args", "get_first_word")
912

10-
try:
13+
json_mode = "builtin"
14+
15+
if importlib.util.find_spec("orjson"):
1116
import orjson as json
1217

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
1738

18-
orjson = False
39+
get_logger().debug(f"Using {json_mode} for JSON encoding and decoding.")
1940

2041

2142
_quotes = {
@@ -46,12 +67,12 @@
4667

4768

4869
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."""
5071

5172
@staticmethod
5273
def dumps(*args, **kwargs) -> str:
5374
data = json.dumps(*args, **kwargs)
54-
if orjson:
75+
if json_mode in ("orjson", "msgspec"):
5576
data = data.decode("utf-8")
5677
return data
5778

0 commit comments

Comments
 (0)