Skip to main content

membacking/mapping_manager/
mappable.rs

1// Copyright (c) Microsoft Corporation.
2// Licensed under the MIT License.
3
4use mesh::payload::DefaultEncoding;
5use mesh::payload::encoding::ResourceField;
6use std::sync::Arc;
7
8cfg_select! {
9    windows => {
10        /// A section handle.
11        type OwnedType = std::os::windows::io::OwnedHandle;
12    }
13    unix => {
14        /// A file descriptor.
15        type OwnedType = std::os::fd::OwnedFd;
16    }
17}
18
19/// A handle/fd to an OS object that can be mapped into memory.
20///
21/// This uses `Arc` to make `clone` cheap and reliable.
22#[derive(Debug, Clone)]
23pub struct Mappable(Arc<OwnedType>);
24
25impl From<OwnedType> for Mappable {
26    fn from(value: OwnedType) -> Self {
27        Self(Arc::new(value))
28    }
29}
30
31impl From<Arc<OwnedType>> for Mappable {
32    fn from(value: Arc<OwnedType>) -> Self {
33        Self(value)
34    }
35}
36
37impl From<Mappable> for OwnedType {
38    fn from(value: Mappable) -> Self {
39        // Currently there is no way to avoid the unwrap here. Mesh improvements
40        // to how resources are handled could make this unnecessary.
41        Arc::try_unwrap(value.0).unwrap_or_else(|v| v.try_clone().expect("out of fds/handles"))
42    }
43}
44
45#[cfg(unix)]
46impl std::os::fd::AsFd for Mappable {
47    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
48        self.0.as_fd()
49    }
50}
51
52#[cfg(windows)]
53impl std::os::windows::io::AsHandle for Mappable {
54    fn as_handle(&self) -> std::os::windows::io::BorrowedHandle<'_> {
55        self.0.as_handle()
56    }
57}
58
59impl Mappable {
60    /// Returns a clone of the inner `Arc`, avoiding an OS-level `dup()`.
61    pub fn inner_arc(&self) -> Arc<OwnedType> {
62        self.0.clone()
63    }
64}
65
66impl DefaultEncoding for Mappable {
67    type Encoding = ResourceField<OwnedType>;
68}