Skip to main content

mesa3d_util/sys/stub/
descriptor.rs

1// Copyright 2025 Google
2// SPDX-License-Identifier: MIT
3
4use std::fs::File;
5use std::io::Error;
6use std::io::ErrorKind;
7use std::io::Result;
8use std::os::fd::AsFd;
9use std::os::fd::BorrowedFd;
10use std::os::fd::OwnedFd;
11use std::os::unix::io::AsRawFd;
12use std::os::unix::io::FromRawFd;
13use std::os::unix::io::IntoRawFd;
14use std::os::unix::io::RawFd;
15
16use crate::descriptor::AsRawDescriptor;
17use crate::descriptor::FromRawDescriptor;
18use crate::descriptor::IntoRawDescriptor;
19use crate::DescriptorType;
20
21pub type RawDescriptor = RawFd;
22pub const DEFAULT_RAW_DESCRIPTOR: RawDescriptor = -1;
23
24pub struct OwnedDescriptor {
25    owned: OwnedFd,
26}
27
28impl OwnedDescriptor {
29    pub fn try_clone(&self) -> Result<OwnedDescriptor> {
30        let clone = self.owned.try_clone()?;
31        Ok(OwnedDescriptor { owned: clone })
32    }
33
34    pub fn determine_type(&self) -> Result<DescriptorType> {
35        Err(Error::from(ErrorKind::Unsupported))
36    }
37}
38
39impl AsRawDescriptor for OwnedDescriptor {
40    fn as_raw_descriptor(&self) -> RawDescriptor {
41        self.owned.as_raw_fd()
42    }
43}
44
45impl FromRawDescriptor for OwnedDescriptor {
46    // SAFETY:
47    // It is caller's responsibility to ensure that the descriptor is valid and
48    // stays valid for the lifetime of Self
49    unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self {
50        OwnedDescriptor {
51            owned: OwnedFd::from_raw_fd(descriptor),
52        }
53    }
54}
55
56impl IntoRawDescriptor for OwnedDescriptor {
57    fn into_raw_descriptor(self) -> RawDescriptor {
58        self.owned.into_raw_fd()
59    }
60}
61
62impl AsFd for OwnedDescriptor {
63    fn as_fd(&self) -> BorrowedFd<'_> {
64        self.owned.as_fd()
65    }
66}
67
68impl AsRawDescriptor for File {
69    fn as_raw_descriptor(&self) -> RawDescriptor {
70        self.as_raw_fd()
71    }
72}
73
74impl FromRawDescriptor for File {
75    // SAFETY:
76    // It is caller's responsibility to ensure that the descriptor is valid and
77    // stays valid for the lifetime of Self
78    unsafe fn from_raw_descriptor(descriptor: RawDescriptor) -> Self {
79        File::from_raw_fd(descriptor)
80    }
81}
82
83impl IntoRawDescriptor for File {
84    fn into_raw_descriptor(self) -> RawDescriptor {
85        self.into_raw_fd()
86    }
87}
88
89impl From<File> for OwnedDescriptor {
90    fn from(f: File) -> OwnedDescriptor {
91        OwnedDescriptor { owned: f.into() }
92    }
93}