浏览代码

aya-log: Implement `AsFd` for `EbpfLogger`

This change implements the `AsFd` trait for the `EbpfLogger` struct.
This allows obtaining a `BorrowedFd` from an `EbpfLogger` instance, which is safer than using `AsRawFd`.

This improves the ergonomics of using `EbpfLogger` with APIs that accept file descriptors.

Signed-off-by: Xiaobo Liu <cppcoffee@gmail.com>
Xiaobo Liu 3 天之前
父节点
当前提交
44ec978bd3
共有 2 个文件被更改,包括 13 次插入1 次删除
  1. 11 1
      aya-log/src/lib.rs
  2. 2 0
      xtask/public-api/aya-log.txt

+ 11 - 1
aya-log/src/lib.rs

@@ -61,7 +61,7 @@ use std::{
     fmt::{LowerHex, UpperHex},
     mem,
     net::{Ipv4Addr, Ipv6Addr},
-    os::fd::AsRawFd,
+    os::fd::{AsFd, AsRawFd},
     ptr, str,
 };
 
@@ -98,6 +98,16 @@ pub struct EbpfLogger<T> {
     logger: T,
 }
 
+impl<T> AsFd for EbpfLogger<T> {
+    fn as_fd(&self) -> std::os::fd::BorrowedFd<'_> {
+        let Self {
+            ring_buf,
+            logger: _,
+        } = self;
+        ring_buf.as_fd()
+    }
+}
+
 impl<T> AsRawFd for EbpfLogger<T> {
     fn as_raw_fd(&self) -> std::os::unix::prelude::RawFd {
         let Self {

+ 2 - 0
xtask/public-api/aya-log.txt

@@ -71,6 +71,8 @@ impl<T: log::Log> aya_log::EbpfLogger<T>
 pub fn aya_log::EbpfLogger<T>::flush(&mut self)
 pub fn aya_log::EbpfLogger<T>::init_from_id_with_logger(program_id: u32, logger: T) -> core::result::Result<Self, aya_log::Error>
 pub fn aya_log::EbpfLogger<T>::init_with_logger(bpf: &mut aya::bpf::Ebpf, logger: T) -> core::result::Result<Self, aya_log::Error>
+impl<T> std::os::fd::owned::AsFd for aya_log::EbpfLogger<T>
+pub fn aya_log::EbpfLogger<T>::as_fd(&self) -> std::os::fd::owned::BorrowedFd<'_>
 impl<T> std::os::fd::raw::AsRawFd for aya_log::EbpfLogger<T>
 pub fn aya_log::EbpfLogger<T>::as_raw_fd(&self) -> std::os::fd::raw::RawFd
 impl<T> core::marker::Freeze for aya_log::EbpfLogger<T> where T: core::marker::Freeze