1 use ida::IdAllocator; 2 use smoltcp::iface::SocketHandle; 3 4 use crate::libs::spinlock::SpinLock; 5 6 int_like!(KernelHandle, usize); 7 8 /// # socket的句柄管理组件 9 /// 它在smoltcp的SocketHandle上封装了一层,增加更多的功能。 10 /// 比如,在socket被关闭时,自动释放socket的资源,通知系统的其他组件。 11 #[derive(Debug, Hash, Eq, PartialEq, Clone, Copy)] 12 pub enum GlobalSocketHandle { 13 Smoltcp(SocketHandle), 14 Kernel(KernelHandle), 15 } 16 17 static KERNEL_HANDLE_IDA: SpinLock<IdAllocator> = 18 SpinLock::new(IdAllocator::new(0, usize::MAX).unwrap()); 19 20 impl GlobalSocketHandle { 21 pub fn new_smoltcp_handle(handle: SocketHandle) -> Self { 22 return Self::Smoltcp(handle); 23 } 24 25 pub fn new_kernel_handle() -> Self { 26 return Self::Kernel(KernelHandle::new(KERNEL_HANDLE_IDA.lock().alloc().unwrap())); 27 } 28 29 pub fn smoltcp_handle(&self) -> Option<SocketHandle> { 30 if let Self::Smoltcp(sh) = *self { 31 return Some(sh); 32 } 33 None 34 } 35 36 pub fn kernel_handle(&self) -> Option<KernelHandle> { 37 if let Self::Kernel(kh) = *self { 38 return Some(kh); 39 } 40 None 41 } 42 } 43