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