• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2023 The ChromiumOS Authors
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4 
5 //! Library for custom implementations of serialize/deserialize.
6 
7 use std::result::Result;
8 use std::sync::Arc;
9 
10 use serde::de::Error;
11 use serde::Deserialize;
12 use serde::Deserializer;
13 use serde::Serialize;
14 use serde::Serializer;
15 use sync::Mutex;
16 
17 /// Serialize data T inside an Arc<Mutex<T>>. T must be serializable.
18 ///
19 /// NOTE: This does not validate already serialized Mutexes and data. If multiple structs contain a
20 /// clone of the Arc, and they are all being serialized, this will result in the same data being
21 /// serialized, once per clone.
serialize_arc_mutex<S, T: ?Sized>( item: &Arc<Mutex<T>>, serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer, T: Serialize,22 pub fn serialize_arc_mutex<S, T: ?Sized>(
23     item: &Arc<Mutex<T>>,
24     serializer: S,
25 ) -> Result<S::Ok, S::Error>
26 where
27     S: Serializer,
28     T: Serialize,
29 {
30     let lock = item.lock();
31     serde::Serialize::serialize(&*lock, serializer)
32 }
33 
34 /// Serialize data T inside arrays as a seq instead of a tuple. T must be serializable.
35 /// When deserializing, an array size validation is required to transform the slice to an array.
36 ///
37 /// This approach is used to go around serde's limitation of serializable array sizes.
serialize_arr<S, T: Sized + Serialize, const SIZE: usize>( data: &[T; SIZE], serializer: S, ) -> Result<S::Ok, S::Error> where S: Serializer,38 pub fn serialize_arr<S, T: Sized + Serialize, const SIZE: usize>(
39     data: &[T; SIZE],
40     serializer: S,
41 ) -> Result<S::Ok, S::Error>
42 where
43     S: Serializer,
44 {
45     serde::Serialize::serialize(&data[..], serializer)
46 }
47 
48 /// Deserialize sequence of T into an Array of SIZE == Size of sequence.
49 /// This function is a workaround to the serde limitation on array size (32) deserialization.
deserialize_seq_to_arr< 'de, D, T: Sized + Deserialize<'de> + std::fmt::Debug, const SIZE: usize, >( deserializer: D, ) -> Result<[T; SIZE], D::Error> where D: Deserializer<'de>,50 pub fn deserialize_seq_to_arr<
51     'de,
52     D,
53     T: Sized + Deserialize<'de> + std::fmt::Debug,
54     const SIZE: usize,
55 >(
56     deserializer: D,
57 ) -> Result<[T; SIZE], D::Error>
58 where
59     D: Deserializer<'de>,
60 {
61     let vals_vec: Vec<T> = serde::Deserialize::deserialize(deserializer)?;
62     let vals_arr: [T; SIZE] = vals_vec.try_into().map_err(|_| {
63         <D as Deserializer>::Error::custom("failed to convert vector to array while deserializing")
64     })?;
65     Ok(vals_arr)
66 }
67