1 // Copyright (c) 2023 Huawei Device Co., Ltd. 2 // Licensed under the Apache License, Version 2.0 (the "License"); 3 // you may not use this file except in compliance with the License. 4 // You may obtain a copy of the License at 5 // 6 // http://www.apache.org/licenses/LICENSE-2.0 7 // 8 // Unless required by applicable law or agreed to in writing, software 9 // distributed under the License is distributed on an "AS IS" BASIS, 10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 11 // See the License for the specific language governing permissions and 12 // limitations under the License. 13 14 use std::io; 15 use std::os::unix::io::RawFd; 16 17 use crate::{Fd, Interest, Selector, Source, Token}; 18 19 /// SourceFd allows any type of FD to register with Poll. 20 #[derive(Debug)] 21 pub struct SourceFd<'a>(pub &'a RawFd); 22 23 impl<'a> Source for SourceFd<'a> { register( &mut self, selector: &Selector, token: Token, interests: Interest, ) -> io::Result<()>24 fn register( 25 &mut self, 26 selector: &Selector, 27 token: Token, 28 interests: Interest, 29 ) -> io::Result<()> { 30 selector.register(self.get_fd(), token, interests) 31 } 32 deregister(&mut self, selector: &Selector) -> io::Result<()>33 fn deregister(&mut self, selector: &Selector) -> io::Result<()> { 34 selector.deregister(self.get_fd()) 35 } 36 get_fd(&self) -> Fd37 fn get_fd(&self) -> Fd { 38 *self.0 39 } 40 } 41 42 #[cfg(test)] 43 mod test { 44 use crate::sys::{socket, SourceFd}; 45 46 /// UT cases for debug info of SourceFd. 47 /// 48 /// # Brief 49 /// 1. Create a SourceFd 50 /// 2. Reregister the SourceFd 51 #[test] ut_source_fd_debug_info()52 fn ut_source_fd_debug_info() { 53 let sock = socket::socket_new(libc::AF_UNIX, libc::SOCK_STREAM).unwrap(); 54 let source_fd = SourceFd(&sock); 55 56 let fmt = format!("{:?}", source_fd); 57 assert!(fmt.contains("SourceFd(")); 58 } 59 } 60