matrix_sdk_indexeddb/serialize_bool_for_indexeddb.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
15//! Booleans don't work as keys in indexeddb (see [ECMA spec]), so instead we
16//! serialize them as `0` or `1`.
17//!
18//! This module implements a custom serializer which can be used on `bool`
19//! struct fields with:
20//!
21//! ```ignore
22//! #[serde(with = "serialize_bool_for_indexeddb")]
23//! ```
24//!
25//! [ECMA spec]: https://w3c.github.io/IndexedDB/#key
26use serde::{Deserializer, Serializer};
27
28pub fn serialize<S>(v: &bool, s: S) -> Result<S::Ok, S::Error>
29where
30 S: Serializer,
31{
32 s.serialize_u8(if *v { 1 } else { 0 })
33}
34
35pub fn deserialize<'de, D>(d: D) -> Result<bool, D::Error>
36where
37 D: Deserializer<'de>,
38{
39 let v: u8 = serde::de::Deserialize::deserialize(d)?;
40 Ok(v != 0)
41}