session_testing/
lib.rs

1// Copyright 2021 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 fidl::endpoints::ServerEnd;
6use fidl_fuchsia_io as fio;
7use fuchsia_async::{self as fasync};
8use futures::TryStreamExt;
9
10/// Spawn a request handler for the provided server end.
11///
12/// This function will spawn a detached Task to handle requests. Requests will be handled using
13/// the provided `handler` function.
14pub fn spawn_server<F: 'static, P>(server_end: fidl::endpoints::ServerEnd<P>, handler: F)
15where
16    P: fidl::endpoints::ProtocolMarker,
17    F: Fn(fidl::endpoints::Request<P>) + Send,
18{
19    let mut stream = server_end.into_stream();
20    fasync::Task::spawn(async move {
21        while let Some(request) = stream.try_next().await.unwrap() {
22            handler(request);
23        }
24    })
25    .detach();
26}
27
28/// Same as below but provides a noop request handler to the provider `directory`.
29/// This is useful if you have to provide an implementation of `fuchsia.io.Directory`
30/// for a test, but don't need to handle any individual method.
31pub fn spawn_noop_directory_server(directory: ServerEnd<fio::DirectoryMarker>) {
32    let handler = move |_request| {};
33    spawn_directory_server(directory, handler);
34}
35
36/// Spawn a request handler for the provided `directory` server end. This
37/// function will spawn a detached Task to handle requests. Requests will be
38/// handled using the provided `handler` function.
39pub fn spawn_directory_server<F: 'static>(directory: ServerEnd<fio::DirectoryMarker>, handler: F)
40where
41    F: Fn(fio::DirectoryRequest) + Send,
42{
43    spawn_server(directory, handler);
44}