Skip to content

Commit

Permalink
add a test
Browse files Browse the repository at this point in the history
  • Loading branch information
spytheman committed Sep 26, 2024
1 parent 57b87aa commit 7f0f475
Show file tree
Hide file tree
Showing 2 changed files with 31 additions and 5 deletions.
11 changes: 6 additions & 5 deletions vlib/net/util.v
Original file line number Diff line number Diff line change
@@ -1,11 +1,12 @@
module net

const socket_max_port = u16(0xFFFF)

// validate_port checks whether a port is valid
// and returns the port or an error
// validate_port checks whether a port is valid and returns the port or an error.
// The valid ports numbers are between 0 and 0xFFFF.
// For TCP, port number 0 is reserved and cannot be used, while for UDP, the source port
// is optional and a value of zero means no port.
// See also https://en.wikipedia.org/wiki/Port_%28computer_networking%29 .
pub fn validate_port(port int) !u16 {
if port <= socket_max_port {
if port >= 0 && port <= 0xFFFF {
return u16(port)
} else {
return err_port_out_of_range
Expand Down
25 changes: 25 additions & 0 deletions vlib/net/utils_test.v
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import net

fn test_validate() {
assert net.validate_port(0)! == 0
assert net.validate_port(1)! == 1
assert net.validate_port(0xFFFF)! == 0xFFFF
if _ := net.validate_port(0xFFFF + 1) {
assert false
} else {
assert true
}
if x := net.validate_port(-2) {
dump(x)
assert false
} else {
assert true
}
}

fn test_resolve() {
x := net.resolve_addrs_fuzzy('[::1]:10093', .udp)!
assert x.len > 0
assert x[0].str() == '[::1]:10093'
assert x[0].port()! == 10093
}

0 comments on commit 7f0f475

Please sign in to comment.