serial_core/
resources.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4//! Serial resources, for use with [`vm_resource`].
5
6use super::SerialIo;
7use mesh::MeshPayload;
8use pal_async::driver::Driver;
9use vm_resource::CanResolveTo;
10use vm_resource::Resource;
11use vm_resource::ResourceId;
12use vm_resource::kind::SerialBackendHandle;
13
14impl CanResolveTo<ResolvedSerialBackend> for SerialBackendHandle {
15    type Input<'a> = ResolveSerialBackendParams<'a>;
16}
17
18/// Input parameters for serial backend resolution.
19pub struct ResolveSerialBackendParams<'a> {
20    /// The driver to use for polling IO.
21    pub driver: Box<dyn Driver>,
22    #[doc(hidden)]
23    // Work around for async_trait not working well with GAT input parameters.
24    // Remove once we stop using async_trait for async resolvers.
25    pub _async_trait_workaround: &'a (),
26}
27
28/// A resolved [`SerialBackend`].
29pub struct ResolvedSerialBackend(pub Box<dyn SerialBackend>);
30
31impl<T: 'static + SerialBackend> From<T> for ResolvedSerialBackend {
32    fn from(value: T) -> Self {
33        Self(Box::new(value))
34    }
35}
36
37/// Trait implemented by types that resolve from [`SerialBackendHandle`]. Provides a
38/// [`SerialIo`] implementation but also provides for converting the type back
39/// to a resource.
40pub trait SerialBackend: Send {
41    /// Reclaims the resource.
42    fn into_resource(self: Box<Self>) -> Resource<SerialBackendHandle>;
43    /// Gets the inner IO trait.
44    fn as_io(&self) -> &dyn SerialIo;
45    /// Gets the inner IO trait mutably.
46    fn as_io_mut(&mut self) -> &mut dyn SerialIo;
47    /// Gets the inner IO trait object.
48    fn into_io(self: Box<Self>) -> Box<dyn SerialIo>;
49}
50
51impl<T: 'static + SerialIo + Into<Resource<SerialBackendHandle>>> SerialBackend for T {
52    fn into_resource(self: Box<Self>) -> Resource<SerialBackendHandle> {
53        (*self).into()
54    }
55
56    fn as_io(&self) -> &dyn SerialIo {
57        self
58    }
59
60    fn as_io_mut(&mut self) -> &mut dyn SerialIo {
61        self
62    }
63
64    fn into_io(self: Box<Self>) -> Box<dyn SerialIo> {
65        self
66    }
67}
68
69/// Handle for a disconnected serial backend.
70#[derive(MeshPayload)]
71pub struct DisconnectedSerialBackendHandle;
72
73impl ResourceId<SerialBackendHandle> for DisconnectedSerialBackendHandle {
74    const ID: &'static str = "disconnected";
75}