1#[cfg(not(feature = "mock-ffi"))]
2#[link(wasm_import_module = "blockless_socket")]
3extern "C" {
4 #[link_name = "create_tcp_bind_socket"]
5 pub(crate) fn create_tcp_bind_socket_native(
6 addr: *const u8,
7 addr_len: u32,
8 fd: *mut u32,
9 ) -> u32;
10}
11
12#[cfg(feature = "mock-ffi")]
13mod mock_ffi {
14 pub unsafe fn create_tcp_bind_socket_native(
15 _addr: *const u8,
16 _addr_len: u32,
17 _fd: *mut u32,
18 ) -> u32 {
19 unimplemented!()
20 }
21}
22
23#[cfg(feature = "mock-ffi")]
24use mock_ffi::*;
25
26pub fn create_tcp_bind_socket(addr: &str) -> Result<u32, SocketErrorKind> {
27 unsafe {
28 let addr_ptr = addr.as_ptr();
29 let mut fd: u32 = 0;
30 let rs = create_tcp_bind_socket_native(addr_ptr, addr.len() as _, (&mut fd) as *mut u32);
31 if rs == 0 {
32 return Ok(fd);
33 }
34 Err(match rs {
35 1 => SocketErrorKind::ConnectRefused,
36 2 => SocketErrorKind::ParameterError,
37 3 => SocketErrorKind::ConnectionReset,
38 4 => SocketErrorKind::AddressInUse,
39 _ => unreachable!("unreach."),
40 })
41 }
42}
43
44#[derive(Debug)]
45pub enum SocketErrorKind {
46 ConnectRefused,
47 ParameterError,
48 ConnectionReset,
49 AddressInUse,
50}
51
52impl std::fmt::Display for SocketErrorKind {
53 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
54 match *self {
55 SocketErrorKind::ConnectRefused => write!(f, "Connect Refused."),
56 SocketErrorKind::ParameterError => write!(f, "Parameter Error."),
57 SocketErrorKind::ConnectionReset => write!(f, "Connection Reset."),
58 SocketErrorKind::AddressInUse => write!(f, "Address In Use."),
59 }
60 }
61}
62
63impl std::error::Error for SocketErrorKind {}