base: Add serialize/deserialize for Descriptor.

Valid use case for base::Descriptor lists 'You need to serialize a
['RawDescriptor'].

BUG=b:337051928
TEST=tested downstream


Change-Id: Iaf27c4b5ed99c59d6e5d83b11ff76fe858e5c0d7
Reviewed-on: https://chromium-review.googlesource.com/c/crosvm/crosvm/+/5511662
Reviewed-by: Idan Raiter <idanr@google.com>
Reviewed-by: Noah Gold <nkgold@google.com>
Commit-Queue: Shalini Sengupta <shalinisen@google.com>
This commit is contained in:
Shalini Sengupta 2024-04-24 12:44:06 -07:00 committed by crosvm LUCI
parent cf3ef05f67
commit 6b26ac8f4b

View file

@ -9,6 +9,7 @@ use std::sync::Arc;
use serde::Deserialize;
use serde::Serialize;
use serde::Serializer;
use crate::EventToken;
use crate::RawDescriptor;
@ -156,7 +157,7 @@ impl From<File> for SafeDescriptor {
///
/// Note that with the exception of the last use-case (which requires proper error checking against
/// the descriptor being closed), the `Descriptor` instance would be very short-lived.
#[derive(Copy, Clone, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[derive(Copy, Clone, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]
#[repr(transparent)]
pub struct Descriptor(pub RawDescriptor);
impl AsRawDescriptor for Descriptor {
@ -180,3 +181,21 @@ impl EventToken for Descriptor {
Descriptor(data as RawDescriptor)
}
}
impl Serialize for Descriptor {
fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
where
S: Serializer,
{
serializer.serialize_u64(self.0 as u64)
}
}
impl<'de> Deserialize<'de> for Descriptor {
fn deserialize<D>(deserializer: D) -> Result<Descriptor, D::Error>
where
D: serde::Deserializer<'de>,
{
u64::deserialize(deserializer).map(|data| Descriptor(data as RawDescriptor))
}
}