fuchsia_scenic/
sysmem.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 anyhow::Error;
6use fidl::endpoints::{ClientEnd, create_endpoints};
7use fsysmem2::BufferCollectionTokenDuplicateRequest;
8use {fidl_fuchsia_sysmem2 as fsysmem2, fidl_fuchsia_ui_composition as fland};
9
10// Pair of tokens to be used with Scenic Allocator FIDL protocol.
11pub struct BufferCollectionTokenPair {
12    pub export_token: fland::BufferCollectionExportToken,
13    pub import_token: fland::BufferCollectionImportToken,
14}
15
16impl BufferCollectionTokenPair {
17    pub fn new() -> BufferCollectionTokenPair {
18        let (raw_export_token, raw_import_token) = zx::EventPair::create();
19        BufferCollectionTokenPair {
20            export_token: fland::BufferCollectionExportToken { value: raw_export_token },
21            import_token: fland::BufferCollectionImportToken { value: raw_import_token },
22        }
23    }
24}
25
26/// Given a Scenic `BufferCollectionImportToken`, returns a new version which has been duplicated.
27pub fn duplicate_buffer_collection_import_token(
28    import_token: &fland::BufferCollectionImportToken,
29) -> Result<fland::BufferCollectionImportToken, Error> {
30    let handle = import_token.value.as_handle_ref().duplicate(zx::Rights::SAME_RIGHTS)?;
31    Ok(fland::BufferCollectionImportToken { value: handle.into() })
32}
33
34/// Calls `BufferCollectionToken.Duplicate()` on the provided token, passing the server end of a
35/// newly-instantiated channel.  Then, calls `Sync()` on the provided token, so that the returned
36/// token is safe to use immediately (i.e. the server has acknowledged that the duplication has
37/// occurred).
38pub async fn duplicate_buffer_collection_token(
39    token: &mut fsysmem2::BufferCollectionTokenProxy,
40) -> Result<ClientEnd<fsysmem2::BufferCollectionTokenMarker>, Error> {
41    let (duplicate_token, duplicate_token_server_end) =
42        create_endpoints::<fsysmem2::BufferCollectionTokenMarker>();
43
44    token.duplicate(BufferCollectionTokenDuplicateRequest {
45        rights_attenuation_mask: Some(fidl::Rights::SAME_RIGHTS),
46        token_request: Some(duplicate_token_server_end),
47        ..Default::default()
48    })?;
49    token.sync().await?;
50
51    Ok(duplicate_token)
52}