We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Bug: Custom data types with validators cannot be serialized since 1.45
**Describe the bug**
Since version 1.45 custom data types with pydantic validators cannot be serialized anymore. Deserialization works fine.

**To Reproduce**
Example app that works in 1.44, but doesn't in 1.45+:
Note that the print gets executed.
```python
from pydantic import BaseModel
from starlite import Starlite, post, Request, Response, LoggingConfig
from starlite.utils import create_exception_response


class CustomType(str):
    @classmethod
    def __get_validators__(cls):
        yield cls.get_validators_must_yield_something_so_here_we_are

    @classmethod
    def get_validators_must_yield_something_so_here_we_are(cls, value):
        return cls(value)


class Model(BaseModel):
    foo: CustomType


@post('/foo')
def foo(data: Model) -> Model:
    print(data)
    return data


def logging_exception_handler(request: Request, exc: Exception) -> Response:
    request.logger.error("Application Exception", exc_info = exc)
    return create_exception_response(exc)


app = Starlite(
    [foo],
    logging_config = LoggingConfig(),
    exception_handlers={Exception: logging_exception_handler},
)
```

**Additional context**
This is the stacktrace that I got with the example above:
```
Traceback (most recent call last):
  File ".../python3.11/site-packages/starlite/response/base.py", line 216, in render
    return encode_json(content, self.serializer)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/utils/serialization.py", line 59, in encode_json
    return _msgspec_json_encoder.encode(obj)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/utils/serialization.py", line 24, in default_serializer
    raise TypeError(f"Unsupported type: {type(value)!r}")
TypeError: Unsupported type: <class 'app2.CustomType'>

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File ".../python3.11/site-packages/starlite/middleware/exceptions/middleware.py", line 47, in __call__
    await self.app(scope, receive, send)
  File ".../python3.11/site-packages/starlite/routes/http.py", line 75, in handle
    response = await self._get_response_for_request(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/routes/http.py", line 127, in _get_response_for_request
    response = await self._call_handler_function(
               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/routes/http.py", line 163, in _call_handler_function
    else await route_handler.to_response(
         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/handlers/http.py", line 606, in to_response
    return await response_handler(app=app, data=data, plugins=plugins, request=request)  # type: ignore
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/handlers/http.py", line 203, in handler
    response = response_class(
               ^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/response/base.py", line 109, in __init__
    self.body = content if isinstance(content, bytes) else self.render(content)
                                                           ^^^^^^^^^^^^^^^^^^^^
  File ".../python3.11/site-packages/starlite/response/base.py", line 218, in render
    raise ImproperlyConfiguredException("Unable to serialize response content") from e
starlite.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Unable to serialize response content
```


--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `starlite/utils/serialization.py`
Content:
```
1 from pathlib import PurePosixPath
2 from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union
3 
4 import msgspec
5 from pydantic import (
6     AnyUrl,
7     BaseModel,
8     ByteSize,
9     ConstrainedBytes,
10     ConstrainedDate,
11     ConstrainedDecimal,
12     ConstrainedFloat,
13     ConstrainedFrozenSet,
14     ConstrainedInt,
15     ConstrainedList,
16     ConstrainedSet,
17     ConstrainedStr,
18     EmailStr,
19     NameEmail,
20     PaymentCardNumber,
21     SecretField,
22     StrictBool,
23 )
24 from pydantic.color import Color
25 
26 if TYPE_CHECKING:
27     from starlite.types import TypeEncodersMap
28 
29 DEFAULT_TYPE_ENCODERS: "TypeEncodersMap" = {
30     PurePosixPath: str,
31     # pydantic specific types
32     BaseModel: lambda m: m.dict(),
33     ByteSize: lambda b: b.real,
34     EmailStr: str,
35     NameEmail: str,
36     Color: str,
37     AnyUrl: str,
38     SecretField: str,
39     ConstrainedInt: int,
40     ConstrainedFloat: float,
41     ConstrainedStr: str,
42     ConstrainedBytes: lambda b: b.decode("utf-8"),
43     ConstrainedList: list,
44     ConstrainedSet: set,
45     ConstrainedFrozenSet: frozenset,
46     ConstrainedDecimal: float,
47     ConstrainedDate: lambda d: d.isoformat(),
48     PaymentCardNumber: str,
49     StrictBool: int,  # pydantic compatibility
50 }
51 
52 
53 def default_serializer(value: Any, type_encoders: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any:
54     """Transform values non-natively supported by `msgspec`
55 
56     Args:
57         value: A value to serialize#
58         type_encoders: Mapping of types to callables to transforming types
59     Returns:
60         A serialized value
61     Raises:
62         TypeError: if value is not supported
63     """
64     if type_encoders is None:
65         type_encoders = DEFAULT_TYPE_ENCODERS
66     for base in value.__class__.__mro__[:-1]:
67         try:
68             encoder = type_encoders[base]
69         except KeyError:
70             continue
71         return encoder(value)
72     raise TypeError(f"Unsupported type: {type(value)!r}")
73 
74 
75 def dec_hook(type_: Any, value: Any) -> Any:  # pragma: no cover
76     """Transform values non-natively supported by `msgspec`
77 
78     Args:
79         type_: Encountered type
80         value: Value to coerce
81 
82     Returns:
83         A `msgspec`-supported type
84     """
85     if issubclass(type_, BaseModel):
86         return type_(**value)
87     raise TypeError(f"Unsupported type: {type(value)!r}")
88 
89 
90 _msgspec_json_encoder = msgspec.json.Encoder(enc_hook=default_serializer)
91 _msgspec_json_decoder = msgspec.json.Decoder(dec_hook=dec_hook)
92 _msgspec_msgpack_encoder = msgspec.msgpack.Encoder(enc_hook=default_serializer)
93 _msgspec_msgpack_decoder = msgspec.msgpack.Decoder(dec_hook=dec_hook)
94 
95 
96 def encode_json(obj: Any, default: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:
97     """Encode a value into JSON.
98 
99     Args:
100         obj: Value to encode
101         default: Optional callable to support non-natively supported types.
102 
103     Returns:
104         JSON as bytes
105     """
106     if default is None or default is default_serializer:
107         return _msgspec_json_encoder.encode(obj)
108     return msgspec.json.encode(obj, enc_hook=default)
109 
110 
111 def decode_json(raw: Union[str, bytes]) -> Any:
112     """Decode a JSON string/bytes into an object.
113 
114     Args:
115         raw: Value to decode
116 
117     Returns:
118         An object
119     """
120     return _msgspec_json_decoder.decode(raw)
121 
122 
123 def encode_msgpack(obj: Any, enc_hook: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:
124     """Encode a value into MessagePack.
125 
126     Args:
127         obj: Value to encode
128         enc_hook: Optional callable to support non-natively supported types
129 
130     Returns:
131         MessagePack as bytes
132     """
133     if enc_hook is None or enc_hook is default_serializer:
134         return _msgspec_msgpack_encoder.encode(obj)
135     return msgspec.msgpack.encode(obj, enc_hook=enc_hook)
136 
137 
138 def decode_msgpack(raw: bytes) -> Any:
139     """Decode a MessagePack string/bytes into an object.
140 
141     Args:
142         raw: Value to decode
143 
144     Returns:
145         An object
146     """
147     return _msgspec_msgpack_decoder.decode(raw)
148
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/starlite/utils/serialization.py b/starlite/utils/serialization.py
--- a/starlite/utils/serialization.py
+++ b/starlite/utils/serialization.py
@@ -1,27 +1,30 @@
+from collections import deque
+from decimal import Decimal
+from ipaddress import (
+    IPv4Address,
+    IPv4Interface,
+    IPv4Network,
+    IPv6Address,
+    IPv6Interface,
+    IPv6Network,
+)
 from pathlib import PurePosixPath
+from re import Pattern
 from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union
 
 import msgspec
 from pydantic import (
-    AnyUrl,
     BaseModel,
     ByteSize,
     ConstrainedBytes,
     ConstrainedDate,
     ConstrainedDecimal,
-    ConstrainedFloat,
-    ConstrainedFrozenSet,
-    ConstrainedInt,
-    ConstrainedList,
-    ConstrainedSet,
-    ConstrainedStr,
-    EmailStr,
     NameEmail,
-    PaymentCardNumber,
     SecretField,
     StrictBool,
 )
 from pydantic.color import Color
+from pydantic.json import decimal_encoder
 
 if TYPE_CHECKING:
     from starlite.types import TypeEncodersMap
@@ -31,22 +34,36 @@
     # pydantic specific types
     BaseModel: lambda m: m.dict(),
     ByteSize: lambda b: b.real,
-    EmailStr: str,
     NameEmail: str,
     Color: str,
-    AnyUrl: str,
     SecretField: str,
-    ConstrainedInt: int,
-    ConstrainedFloat: float,
-    ConstrainedStr: str,
     ConstrainedBytes: lambda b: b.decode("utf-8"),
-    ConstrainedList: list,
-    ConstrainedSet: set,
-    ConstrainedFrozenSet: frozenset,
     ConstrainedDecimal: float,
     ConstrainedDate: lambda d: d.isoformat(),
-    PaymentCardNumber: str,
-    StrictBool: int,  # pydantic compatibility
+    IPv4Address: str,
+    IPv4Interface: str,
+    IPv4Network: str,
+    IPv6Address: str,
+    IPv6Interface: str,
+    IPv6Network: str,
+    # pydantic compatibility
+    deque: list,
+    Decimal: decimal_encoder,
+    StrictBool: int,
+    Pattern: lambda o: o.pattern,
+    # support subclasses of stdlib types, e.g. pydantic's constrained types. If no
+    # previous type matched, these will be the last type in the mro, so we use this to
+    # (attempt to) convert a subclass into its base class.
+    # see https://github.com/jcrist/msgspec/issues/248
+    # and https://github.com/starlite-api/starlite/issues/1003
+    str: str,
+    int: int,
+    float: float,
+    list: list,
+    tuple: tuple,
+    set: set,
+    frozenset: frozenset,
+    dict: dict,
 }

{"golden_diff": "diff --git a/starlite/utils/serialization.py b/starlite/utils/serialization.py\n--- a/starlite/utils/serialization.py\n+++ b/starlite/utils/serialization.py\n@@ -1,27 +1,30 @@\n+from collections import deque\n+from decimal import Decimal\n+from ipaddress import (\n+    IPv4Address,\n+    IPv4Interface,\n+    IPv4Network,\n+    IPv6Address,\n+    IPv6Interface,\n+    IPv6Network,\n+)\n from pathlib import PurePosixPath\n+from re import Pattern\n from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union\n \n import msgspec\n from pydantic import (\n-    AnyUrl,\n     BaseModel,\n     ByteSize,\n     ConstrainedBytes,\n     ConstrainedDate,\n     ConstrainedDecimal,\n-    ConstrainedFloat,\n-    ConstrainedFrozenSet,\n-    ConstrainedInt,\n-    ConstrainedList,\n-    ConstrainedSet,\n-    ConstrainedStr,\n-    EmailStr,\n     NameEmail,\n-    PaymentCardNumber,\n     SecretField,\n     StrictBool,\n )\n from pydantic.color import Color\n+from pydantic.json import decimal_encoder\n \n if TYPE_CHECKING:\n     from starlite.types import TypeEncodersMap\n@@ -31,22 +34,36 @@\n     # pydantic specific types\n     BaseModel: lambda m: m.dict(),\n     ByteSize: lambda b: b.real,\n-    EmailStr: str,\n     NameEmail: str,\n     Color: str,\n-    AnyUrl: str,\n     SecretField: str,\n-    ConstrainedInt: int,\n-    ConstrainedFloat: float,\n-    ConstrainedStr: str,\n     ConstrainedBytes: lambda b: b.decode(\"utf-8\"),\n-    ConstrainedList: list,\n-    ConstrainedSet: set,\n-    ConstrainedFrozenSet: frozenset,\n     ConstrainedDecimal: float,\n     ConstrainedDate: lambda d: d.isoformat(),\n-    PaymentCardNumber: str,\n-    StrictBool: int,  # pydantic compatibility\n+    IPv4Address: str,\n+    IPv4Interface: str,\n+    IPv4Network: str,\n+    IPv6Address: str,\n+    IPv6Interface: str,\n+    IPv6Network: str,\n+    # pydantic compatibility\n+    deque: list,\n+    Decimal: decimal_encoder,\n+    StrictBool: int,\n+    Pattern: lambda o: o.pattern,\n+    # support subclasses of stdlib types, e.g. pydantic's constrained types. If no\n+    # previous type matched, these will be the last type in the mro, so we use this to\n+    # (attempt to) convert a subclass into its base class.\n+    # see https://github.com/jcrist/msgspec/issues/248\n+    # and https://github.com/starlite-api/starlite/issues/1003\n+    str: str,\n+    int: int,\n+    float: float,\n+    list: list,\n+    tuple: tuple,\n+    set: set,\n+    frozenset: frozenset,\n+    dict: dict,\n }\n", "issue": "Bug: Custom data types with validators cannot be serialized since 1.45\n**Describe the bug**\r\nSince version 1.45 custom data types with pydantic validators cannot be serialized anymore. Deserialization works fine.\r\n\r\n**To Reproduce**\r\nExample app that works in 1.44, but doesn't in 1.45+:\r\nNote that the print gets executed.\r\n```python\r\nfrom pydantic import BaseModel\r\nfrom starlite import Starlite, post, Request, Response, LoggingConfig\r\nfrom starlite.utils import create_exception_response\r\n\r\n\r\nclass CustomType(str):\r\n    @classmethod\r\n    def __get_validators__(cls):\r\n        yield cls.get_validators_must_yield_something_so_here_we_are\r\n\r\n    @classmethod\r\n    def get_validators_must_yield_something_so_here_we_are(cls, value):\r\n        return cls(value)\r\n\r\n\r\nclass Model(BaseModel):\r\n    foo: CustomType\r\n\r\n\r\n@post('/foo')\r\ndef foo(data: Model) -> Model:\r\n    print(data)\r\n    return data\r\n\r\n\r\ndef logging_exception_handler(request: Request, exc: Exception) -> Response:\r\n    request.logger.error(\"Application Exception\", exc_info = exc)\r\n    return create_exception_response(exc)\r\n\r\n\r\napp = Starlite(\r\n    [foo],\r\n    logging_config = LoggingConfig(),\r\n    exception_handlers={Exception: logging_exception_handler},\r\n)\r\n```\r\n\r\n**Additional context**\r\nThis is the stacktrace that I got with the example above:\r\n```\r\nTraceback (most recent call last):\r\n  File \".../python3.11/site-packages/starlite/response/base.py\", line 216, in render\r\n    return encode_json(content, self.serializer)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/utils/serialization.py\", line 59, in encode_json\r\n    return _msgspec_json_encoder.encode(obj)\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/utils/serialization.py\", line 24, in default_serializer\r\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\r\nTypeError: Unsupported type: <class 'app2.CustomType'>\r\n\r\nThe above exception was the direct cause of the following exception:\r\n\r\nTraceback (most recent call last):\r\n  File \".../python3.11/site-packages/starlite/middleware/exceptions/middleware.py\", line 47, in __call__\r\n    await self.app(scope, receive, send)\r\n  File \".../python3.11/site-packages/starlite/routes/http.py\", line 75, in handle\r\n    response = await self._get_response_for_request(\r\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/routes/http.py\", line 127, in _get_response_for_request\r\n    response = await self._call_handler_function(\r\n               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/routes/http.py\", line 163, in _call_handler_function\r\n    else await route_handler.to_response(\r\n         ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/handlers/http.py\", line 606, in to_response\r\n    return await response_handler(app=app, data=data, plugins=plugins, request=request)  # type: ignore\r\n           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/handlers/http.py\", line 203, in handler\r\n    response = response_class(\r\n               ^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/response/base.py\", line 109, in __init__\r\n    self.body = content if isinstance(content, bytes) else self.render(content)\r\n                                                           ^^^^^^^^^^^^^^^^^^^^\r\n  File \".../python3.11/site-packages/starlite/response/base.py\", line 218, in render\r\n    raise ImproperlyConfiguredException(\"Unable to serialize response content\") from e\r\nstarlite.exceptions.http_exceptions.ImproperlyConfiguredException: 500: Unable to serialize response content\r\n```\r\n\n", "before_files": [{"content": "from pathlib import PurePosixPath\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union\n\nimport msgspec\nfrom pydantic import (\n    AnyUrl,\n    BaseModel,\n    ByteSize,\n    ConstrainedBytes,\n    ConstrainedDate,\n    ConstrainedDecimal,\n    ConstrainedFloat,\n    ConstrainedFrozenSet,\n    ConstrainedInt,\n    ConstrainedList,\n    ConstrainedSet,\n    ConstrainedStr,\n    EmailStr,\n    NameEmail,\n    PaymentCardNumber,\n    SecretField,\n    StrictBool,\n)\nfrom pydantic.color import Color\n\nif TYPE_CHECKING:\n    from starlite.types import TypeEncodersMap\n\nDEFAULT_TYPE_ENCODERS: \"TypeEncodersMap\" = {\n    PurePosixPath: str,\n    # pydantic specific types\n    BaseModel: lambda m: m.dict(),\n    ByteSize: lambda b: b.real,\n    EmailStr: str,\n    NameEmail: str,\n    Color: str,\n    AnyUrl: str,\n    SecretField: str,\n    ConstrainedInt: int,\n    ConstrainedFloat: float,\n    ConstrainedStr: str,\n    ConstrainedBytes: lambda b: b.decode(\"utf-8\"),\n    ConstrainedList: list,\n    ConstrainedSet: set,\n    ConstrainedFrozenSet: frozenset,\n    ConstrainedDecimal: float,\n    ConstrainedDate: lambda d: d.isoformat(),\n    PaymentCardNumber: str,\n    StrictBool: int,  # pydantic compatibility\n}\n\n\ndef default_serializer(value: Any, type_encoders: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any:\n    \"\"\"Transform values non-natively supported by `msgspec`\n\n    Args:\n        value: A value to serialize#\n        type_encoders: Mapping of types to callables to transforming types\n    Returns:\n        A serialized value\n    Raises:\n        TypeError: if value is not supported\n    \"\"\"\n    if type_encoders is None:\n        type_encoders = DEFAULT_TYPE_ENCODERS\n    for base in value.__class__.__mro__[:-1]:\n        try:\n            encoder = type_encoders[base]\n        except KeyError:\n            continue\n        return encoder(value)\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\n\n\ndef dec_hook(type_: Any, value: Any) -> Any:  # pragma: no cover\n    \"\"\"Transform values non-natively supported by `msgspec`\n\n    Args:\n        type_: Encountered type\n        value: Value to coerce\n\n    Returns:\n        A `msgspec`-supported type\n    \"\"\"\n    if issubclass(type_, BaseModel):\n        return type_(**value)\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\n\n\n_msgspec_json_encoder = msgspec.json.Encoder(enc_hook=default_serializer)\n_msgspec_json_decoder = msgspec.json.Decoder(dec_hook=dec_hook)\n_msgspec_msgpack_encoder = msgspec.msgpack.Encoder(enc_hook=default_serializer)\n_msgspec_msgpack_decoder = msgspec.msgpack.Decoder(dec_hook=dec_hook)\n\n\ndef encode_json(obj: Any, default: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:\n    \"\"\"Encode a value into JSON.\n\n    Args:\n        obj: Value to encode\n        default: Optional callable to support non-natively supported types.\n\n    Returns:\n        JSON as bytes\n    \"\"\"\n    if default is None or default is default_serializer:\n        return _msgspec_json_encoder.encode(obj)\n    return msgspec.json.encode(obj, enc_hook=default)\n\n\ndef decode_json(raw: Union[str, bytes]) -> Any:\n    \"\"\"Decode a JSON string/bytes into an object.\n\n    Args:\n        raw: Value to decode\n\n    Returns:\n        An object\n    \"\"\"\n    return _msgspec_json_decoder.decode(raw)\n\n\ndef encode_msgpack(obj: Any, enc_hook: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:\n    \"\"\"Encode a value into MessagePack.\n\n    Args:\n        obj: Value to encode\n        enc_hook: Optional callable to support non-natively supported types\n\n    Returns:\n        MessagePack as bytes\n    \"\"\"\n    if enc_hook is None or enc_hook is default_serializer:\n        return _msgspec_msgpack_encoder.encode(obj)\n    return msgspec.msgpack.encode(obj, enc_hook=enc_hook)\n\n\ndef decode_msgpack(raw: bytes) -> Any:\n    \"\"\"Decode a MessagePack string/bytes into an object.\n\n    Args:\n        raw: Value to decode\n\n    Returns:\n        An object\n    \"\"\"\n    return _msgspec_msgpack_decoder.decode(raw)\n", "path": "starlite/utils/serialization.py"}], "after_files": [{"content": "from collections import deque\nfrom decimal import Decimal\nfrom ipaddress import (\n    IPv4Address,\n    IPv4Interface,\n    IPv4Network,\n    IPv6Address,\n    IPv6Interface,\n    IPv6Network,\n)\nfrom pathlib import PurePosixPath\nfrom re import Pattern\nfrom typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Union\n\nimport msgspec\nfrom pydantic import (\n    BaseModel,\n    ByteSize,\n    ConstrainedBytes,\n    ConstrainedDate,\n    ConstrainedDecimal,\n    NameEmail,\n    SecretField,\n    StrictBool,\n)\nfrom pydantic.color import Color\nfrom pydantic.json import decimal_encoder\n\nif TYPE_CHECKING:\n    from starlite.types import TypeEncodersMap\n\nDEFAULT_TYPE_ENCODERS: \"TypeEncodersMap\" = {\n    PurePosixPath: str,\n    # pydantic specific types\n    BaseModel: lambda m: m.dict(),\n    ByteSize: lambda b: b.real,\n    NameEmail: str,\n    Color: str,\n    SecretField: str,\n    ConstrainedBytes: lambda b: b.decode(\"utf-8\"),\n    ConstrainedDecimal: float,\n    ConstrainedDate: lambda d: d.isoformat(),\n    IPv4Address: str,\n    IPv4Interface: str,\n    IPv4Network: str,\n    IPv6Address: str,\n    IPv6Interface: str,\n    IPv6Network: str,\n    # pydantic compatibility\n    deque: list,\n    Decimal: decimal_encoder,\n    StrictBool: int,\n    Pattern: lambda o: o.pattern,\n    # support subclasses of stdlib types, e.g. pydantic's constrained types. If no\n    # previous type matched, these will be the last type in the mro, so we use this to\n    # (attempt to) convert a subclass into its base class.\n    # see https://github.com/jcrist/msgspec/issues/248\n    # and https://github.com/starlite-api/starlite/issues/1003\n    str: str,\n    int: int,\n    float: float,\n    list: list,\n    tuple: tuple,\n    set: set,\n    frozenset: frozenset,\n    dict: dict,\n}\n\n\ndef default_serializer(value: Any, type_encoders: Optional[Dict[Any, Callable[[Any], Any]]] = None) -> Any:\n    \"\"\"Transform values non-natively supported by `msgspec`\n\n    Args:\n        value: A value to serialize#\n        type_encoders: Mapping of types to callables to transforming types\n    Returns:\n        A serialized value\n    Raises:\n        TypeError: if value is not supported\n    \"\"\"\n    if type_encoders is None:\n        type_encoders = DEFAULT_TYPE_ENCODERS\n    for base in value.__class__.__mro__[:-1]:\n        try:\n            encoder = type_encoders[base]\n        except KeyError:\n            continue\n        return encoder(value)\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\n\n\ndef dec_hook(type_: Any, value: Any) -> Any:  # pragma: no cover\n    \"\"\"Transform values non-natively supported by `msgspec`\n\n    Args:\n        type_: Encountered type\n        value: Value to coerce\n\n    Returns:\n        A `msgspec`-supported type\n    \"\"\"\n    if issubclass(type_, BaseModel):\n        return type_(**value)\n    raise TypeError(f\"Unsupported type: {type(value)!r}\")\n\n\n_msgspec_json_encoder = msgspec.json.Encoder(enc_hook=default_serializer)\n_msgspec_json_decoder = msgspec.json.Decoder(dec_hook=dec_hook)\n_msgspec_msgpack_encoder = msgspec.msgpack.Encoder(enc_hook=default_serializer)\n_msgspec_msgpack_decoder = msgspec.msgpack.Decoder(dec_hook=dec_hook)\n\n\ndef encode_json(obj: Any, default: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:\n    \"\"\"Encode a value into JSON.\n\n    Args:\n        obj: Value to encode\n        default: Optional callable to support non-natively supported types.\n\n    Returns:\n        JSON as bytes\n    \"\"\"\n    if default is None or default is default_serializer:\n        return _msgspec_json_encoder.encode(obj)\n    return msgspec.json.encode(obj, enc_hook=default)\n\n\ndef decode_json(raw: Union[str, bytes]) -> Any:\n    \"\"\"Decode a JSON string/bytes into an object.\n\n    Args:\n        raw: Value to decode\n\n    Returns:\n        An object\n    \"\"\"\n    return _msgspec_json_decoder.decode(raw)\n\n\ndef encode_msgpack(obj: Any, enc_hook: Optional[Callable[[Any], Any]] = default_serializer) -> bytes:\n    \"\"\"Encode a value into MessagePack.\n\n    Args:\n        obj: Value to encode\n        enc_hook: Optional callable to support non-natively supported types\n\n    Returns:\n        MessagePack as bytes\n    \"\"\"\n    if enc_hook is None or enc_hook is default_serializer:\n        return _msgspec_msgpack_encoder.encode(obj)\n    return msgspec.msgpack.encode(obj, enc_hook=enc_hook)\n\n\ndef decode_msgpack(raw: bytes) -> Any:\n    \"\"\"Decode a MessagePack string/bytes into an object.\n\n    Args:\n        raw: Value to decode\n\n    Returns:\n        An object\n    \"\"\"\n    return _msgspec_msgpack_decoder.decode(raw)\n", "path": "starlite/utils/serialization.py"}]}