diff --git a/docs/source/supported-types.rst b/docs/source/supported-types.rst index 0f0fe9de..1eb6b93f 100644 --- a/docs/source/supported-types.rst +++ b/docs/source/supported-types.rst @@ -487,10 +487,9 @@ as total seconds. See :ref:`strict-vs-lax` for more information. ``uuid`` -------- -`uuid.UUID` values are serialized as RFC4122_ encoded strings in all protocols. -Subclasses of `uuid.UUID` are also supported for encoding only. - -When decoding, both hyphenated and unhyphenated forms are supported. +`uuid.UUID` values are serialized as RFC4122_ encoded canonical strings in all +protocols by default. Subclasses of `uuid.UUID` are also supported for encoding +only. .. code-block:: python @@ -504,14 +503,60 @@ When decoding, both hyphenated and unhyphenated forms are supported. >>> msgspec.json.decode(b'"c4524ac0-e81e-4aa8-a595-0aec605a659a"', type=uuid.UUID) UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a') - >>> msgspec.json.decode(b'"c4524ac0e81e4aa8a5950aec605a659a"', type=uuid.UUID) - UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a') - >>> msgspec.json.decode(b'"oops"', type=uuid.UUID) Traceback (most recent call last): File "", line 1, in msgspec.ValidationError: Invalid UUID +Alternative formats are also supported by the JSON and MessagePack encoders. +The format may be selected by passing it to ``uuid_format`` when creating an +``Encoder``. The following options are supported: + +- ``canonical``: UUIDs are encoded as RFC4122_ canonical strings (same as + ``str(uuid)``). This is the default. +- ``hex``: UUIDs are encoded as RFC4122_ hex strings (same as ``uuid.hex``). +- ``bytes``: UUIDs are encoded as binary values of the uuid's big-endian + 128-bit integer representation (same as ``uuid.bytes``). This is only supported + by the MessagePack encoder. + +When decoding, both ``canonical`` and ``hex`` formats are supported by all +protocols. + +.. code-block:: python + + >>> enc = msgspec.json.Encoder(uuid_format="hex") + + >>> enc.encode(u) + b'"c4524ac0e81e4aa8a5950aec605a659a"' + + >>> u.hex + "c4524ac0e81e4aa8a5950aec605a659a" + + >>> msgspec.json.decode(b'"c4524ac0e81e4aa8a5950aec605a659a"', type=uuid.UUID) + UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a') + +Additionally, if ``strict=False`` is specified, the ``bytes`` format may be +decoded by the MessagePack decoder. See :ref:`strict-vs-lax` for more +information. + +.. code-block:: python + + >>> enc = msgspec.msgpack.Encoder(uuid_format="bytes") + + >>> msg = enc.encode(u) + + >>> msg + b'\xc4\x10\xc4RJ\xc0\xe8\x1eJ\xa8\xa5\x95\n\xec`Ze\x9a' + + >>> msgspec.msgpack.decode(msg, type=uuid.UUID) + Traceback (most recent call last): + File "", line 1, in + msgspec.ValidationError: Expected `uuid`, got `bytes` + + >>> msgspec.msgpack.decode(msg, type=uuid.UUID, strict=False) + UUID('c4524ac0-e81e-4aa8-a595-0aec605a659a') + + ``decimal`` -----------