Files
synapse/synapse/util/frozenutils.py
T
Erik Johnston c430c16df4 Port event content to Rust (#19725)
Based on #19708.

This is on the path to porting the entire event class to Rust, as
`event.content` will then return the new Rust class `JsonObject`.

This PR adds a pure Rust `JsonObject` class that is a `Mapping`
representing a json-style object. It uses `serde_json::Value` as its
in-memory representation and `pythonize` for conversion when a field is
looked up on the object.

I'm not thrilled with the name, but couldn't think of a better one.

This also adds `JsonObject` handling to the JSON serialisation functions
we use, as well as to the `freeze(..)` function.

Reviewable commit-by-commit.
2026-05-08 14:19:03 +01:00

63 lines
1.5 KiB
Python

#
# This file is licensed under the Affero General Public License (AGPL) version 3.
#
# Copyright 2014-2016 OpenMarket Ltd
# Copyright (C) 2023 New Vector, Ltd
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# See the GNU Affero General Public License for more details:
# <https://www.gnu.org/licenses/agpl-3.0.html>.
#
# Originally licensed under the Apache License, Version 2.0:
# <http://www.apache.org/licenses/LICENSE-2.0>.
#
# [This file includes modifications made by New Vector Limited]
#
#
import collections.abc
from typing import Any
from immutabledict import immutabledict
from synapse.synapse_rust.events import JsonObject
def freeze(o: Any) -> Any:
if isinstance(o, dict):
return immutabledict({k: freeze(v) for k, v in o.items()})
if isinstance(o, immutabledict):
return o
if isinstance(o, JsonObject):
return o
if isinstance(o, (bytes, str)):
return o
try:
return tuple(freeze(i) for i in o)
except TypeError:
pass
return o
def unfreeze(o: Any) -> Any:
if isinstance(o, collections.abc.Mapping):
return {k: unfreeze(v) for k, v in o.items()}
if isinstance(o, (bytes, str)):
return o
try:
return [unfreeze(i) for i in o]
except TypeError:
pass
return o