Skip to main content

fdomain_local/
lib.rs

1// Copyright 2024 The Fuchsia Authors. All rights reserved.
2// Use of this source code is governed by a BSD-style license that can be
3// found in the LICENSE file.
4
5use fdomain_client::{Client, FDomainTransport};
6use fdomain_container::FDomain;
7use fdomain_container::wire::FDomainCodec;
8use fidl::endpoints::ClientEnd;
9use fidl_fuchsia_io as fio;
10use futures::stream::Stream;
11use std::pin::Pin;
12use std::sync::Arc;
13use std::task::{Context, Poll};
14
15/// An FDomain that is designed to be used in the same process it was created
16/// in. I.e. no networking, just a bucket of handles right here where you can
17/// use them.
18struct LocalFDomain(FDomainCodec);
19
20impl LocalFDomain {
21    /// Create a new FDomain client that points to a new local FDomain.
22    fn new_client(
23        namespace: impl Fn() -> Result<ClientEnd<fio::DirectoryMarker>, fidl::Status> + Send + 'static,
24    ) -> Arc<Client> {
25        let (client, fut) = Client::new(LocalFDomain(FDomainCodec::new(FDomain::new(namespace))));
26        fuchsia_async::Task::spawn(fut).detach();
27        client
28    }
29}
30
31impl FDomainTransport for LocalFDomain {
32    fn poll_send_message(
33        mut self: Pin<&mut Self>,
34        msg: &[u8],
35        _ctx: &mut Context<'_>,
36    ) -> Poll<Result<(), Option<std::io::Error>>> {
37        Poll::Ready(self.0.message(msg).map_err(|x| Some(std::io::Error::other(x))))
38    }
39}
40
41impl Stream for LocalFDomain {
42    type Item = Result<Box<[u8]>, std::io::Error>;
43
44    fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> {
45        Pin::new(&mut self.0).poll_next(cx).map_err(std::io::Error::other)
46    }
47}
48
49/// Create a new FDomain client that points to a new local FDomain.
50pub fn local_client(
51    namespace: impl Fn() -> Result<ClientEnd<fio::DirectoryMarker>, fidl::Status> + Send + 'static,
52) -> Arc<Client> {
53    LocalFDomain::new_client(namespace)
54}
55
56pub fn local_client_empty() -> Arc<Client> {
57    local_client(|| Err(fidl::Status::NOT_SUPPORTED))
58}