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
8/// A section handle.
9#[cfg(windows)]
10type OwnedType = std::os::windows::io::OwnedHandle;
11
12/// A file descriptor.
13#[cfg(unix)]
14type OwnedType = std::os::fd::OwnedFd;
15
16/// A handle/fd to an OS object that can be mapped into memory.
17///
18/// This uses `Arc` to make `clone` cheap and reliable.
19#[derive(Debug, Clone)]
20pub struct Mappable(Arc<OwnedType>);
21
22impl From<OwnedType> for Mappable {
23    fn from(value: OwnedType) -> Self {
24        Self(Arc::new(value))
25    }
26}
27
28impl From<Arc<OwnedType>> for Mappable {
29    fn from(value: Arc<OwnedType>) -> Self {
30        Self(value)
31    }
32}
33
34impl From<Mappable> for OwnedType {
35    fn from(value: Mappable) -> Self {
36        // Currently there is no way to avoid the unwrap here. Mesh improvements
37        // to how resources are handled could make this unnecessary.
38        Arc::try_unwrap(value.0).unwrap_or_else(|v| v.try_clone().expect("out of fds/handles"))
39    }
40}
41
42#[cfg(unix)]
43impl std::os::fd::AsFd for Mappable {
44    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
45        self.0.as_fd()
46    }
47}
48
49#[cfg(windows)]
50impl std::os::windows::io::AsHandle for Mappable {
51    fn as_handle(&self) -> std::os::windows::io::BorrowedHandle<'_> {
52        self.0.as_handle()
53    }
54}
55
56impl DefaultEncoding for Mappable {
57    type Encoding = ResourceField<OwnedType>;
58}