Skip to main content

matrix_sdk_indexeddb/serializer/
foreign.rs

1// Copyright 2023 The Matrix.org Foundation C.I.C.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7//     http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15pub mod bool {
16    //! Booleans don't work as keys in indexeddb (see [ECMA spec]), so instead
17    //! we serialize them as `0` or `1`.
18    //!
19    //! This module implements a custom serializer which can be used on `bool`
20    //! struct fields with:
21    //!
22    //! ```ignore
23    //! #[serde(with = "crate::serializer::foreign::bool")]
24    //! ```
25    //!
26    //! [ECMA spec]: https://w3c.github.io/IndexedDB/#key
27    use serde::{Deserializer, Serializer};
28
29    pub fn serialize<S>(v: &bool, s: S) -> Result<S::Ok, S::Error>
30    where
31        S: Serializer,
32    {
33        s.serialize_u8(if *v { 1 } else { 0 })
34    }
35
36    pub fn deserialize<'de, D>(d: D) -> Result<bool, D::Error>
37    where
38        D: Deserializer<'de>,
39    {
40        let v: u8 = serde::de::Deserialize::deserialize(d)?;
41        Ok(v != 0)
42    }
43}