| 1 | module net |
| 2 | |
| 3 | // Well defined errors that are returned from socket functions |
| 4 | pub const errors_base = 0 |
| 5 | pub const err_new_socket_failed = error_with_code('net: new_socket failed to create socket', |
| 6 | |
| 7 | errors_base + 1) |
| 8 | pub const err_option_not_settable = error_with_code('net: set_option_xxx option not settable', |
| 9 | |
| 10 | errors_base + 2) |
| 11 | pub const err_option_wrong_type = error_with_code('net: set_option_xxx option wrong type', |
| 12 | |
| 13 | errors_base + 3) |
| 14 | pub const err_port_out_of_range = error_with_code('net: port out of range', errors_base + 5) |
| 15 | pub const err_no_udp_remote = error_with_code('net: no udp remote', errors_base + 6) |
| 16 | pub const err_connect_failed = error_with_code('net: connect failed', errors_base + 7) |
| 17 | pub const err_connect_timed_out = error_with_code('net: connect timed out', errors_base + 8) |
| 18 | pub const err_timed_out = error_with_code('net: op timed out', errors_base + 9) |
| 19 | pub const err_timed_out_code = errors_base + 9 |
| 20 | pub const err_connection_refused = error_with_code('net: connection refused', errors_base + 10) |
| 21 | |
| 22 | pub fn socket_error_message(potential_code int, s string) !int { |
| 23 | return socket_error(potential_code) or { return error('${err.msg()}; ${s}') } |
| 24 | } |
| 25 | |
| 26 | pub fn socket_error(potential_code int) !int { |
| 27 | $if windows { |
| 28 | if potential_code < 0 { |
| 29 | last_error_int := C.WSAGetLastError() |
| 30 | last_error := wsa_error(last_error_int) |
| 31 | return error_with_code('net: socket error: (${last_error_int}) ${last_error}', |
| 32 | int(last_error)) |
| 33 | } |
| 34 | } $else { |
| 35 | if potential_code < 0 { |
| 36 | last_error := error_code() |
| 37 | return error_with_code('net: socket error: ${last_error}', last_error) |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | return potential_code |
| 42 | } |
| 43 | |
| 44 | pub fn wrap_error(error_code int) ! { |
| 45 | if error_code == 0 { |
| 46 | return |
| 47 | } |
| 48 | $if windows { |
| 49 | enum_error := wsa_error(error_code) |
| 50 | return error_with_code('net: socket error: ${enum_error}', error_code) |
| 51 | } $else { |
| 52 | return error_with_code('net: socket error: ${error_code}', error_code) |
| 53 | } |
| 54 | } |
| 55 | |
| 56 | // wrap_read_result takes a read result and sees if it is 0 for graceful |
| 57 | // connection termination and returns none |
| 58 | // e.g. res := wrap_read_result(C.recv(c.sock.handle, voidptr(buf_ptr), len, 0))? |
| 59 | @[inline] |
| 60 | fn wrap_read_result(result int) !int { |
| 61 | if result == 0 { |
| 62 | return error('none') |
| 63 | } |
| 64 | return result |
| 65 | } |
| 66 | |
| 67 | @[inline] |
| 68 | fn wrap_write_result(result int) !int { |
| 69 | if result == 0 { |
| 70 | return error('none') |
| 71 | } |
| 72 | return result |
| 73 | } |
| 74 | |