/* * Copyright 2025 Ry Wiese * * Use of this source code is governed by the Apache 2.0 license * that can be found in the LICENSE.md file. */////// Effect for binding TCP servers, and its functions.///pubmod Net.TcpBind {use IoError.ErrorKinduse IoError.IoErroruse Net.IpAddruse Net.TcpServeruse Net.TcpServer.TcpServerimport java.net.InetAddressimport java.net.ServerSocketimport java.io.IOExceptionimport java.lang.IllegalArgumentException////// Effect for binding TCP servers.///pubeffTcpBind {/// Binds a TCP server to the given `ip` address and `port`.defbind(ip: IpAddr, port: Int16): Result[IoError, TcpServer] }////// Handles the `TcpBind` effect of the given function `f`.////// In other words, re-interprets the `TcpBind` effect using the `IO` effect.///pubdefhandle(f: a -> b \ ef): a -> b \ (ef - TcpBind) + IO = x ->run {f(x) } withhandlerTcpBind {defbind(ip, port, k) = {try {letinet: InetAddress = InetAddress.getByAddress(IpAddr.toBytes(ip));letmaxQueueLength = 50;letsocket = new ServerSocket(Int16.toInt32(port), maxQueueLength, inet);letserver = TcpServer(socket);k(Ok(server)) } catch {caseex: IllegalArgumentException => k(Err(IoError(ErrorKind.InvalidInput, ex.getMessage())))caseex: IOException => k(Err(IoError(ErrorKind.Other, ex.getMessage()))) } } }////// Runs the `TcpBind` effect of the given function `f`.////// In other words, re-interprets the `TcpBind` effect using the `IO` effect.///@DefaultHandlerpubdefrunWithIO(f: Unit -> a \ ef): a \ (ef - TcpBind) + IO = handle(f)()}