Skip to content

Commit

Permalink
Fix: PIO implementations no longer return an immediately cancelled fu…
Browse files Browse the repository at this point in the history
…ture
  • Loading branch information
natsukagami committed Feb 27, 2024
1 parent eb17247 commit 01b7d49
Showing 1 changed file with 16 additions and 4 deletions.
20 changes: 16 additions & 4 deletions jvm/src/main/scala/PosixLikeIO/PIO.scala
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,8 @@ import java.nio.file.{Path, StandardOpenOption}
import scala.Tuple.Union
import scala.concurrent.ExecutionContext
import scala.util.{Failure, Success, Try}
import gears.async.Scheduler
import java.util.concurrent.CancellationException

object File:
extension (resolver: Future.Resolver[Int])
Expand Down Expand Up @@ -88,6 +90,7 @@ class File(val path: String) {
}

class SocketUDP() {
import SocketUDP._
private var socket: Option[DatagramSocket] = None

def isOpened: Boolean = socket.isDefined && !socket.get.isClosed
Expand All @@ -110,17 +113,17 @@ class SocketUDP() {
def send(data: ByteBuffer, address: String, port: Int): Future[Unit] =
assert(socket.isDefined)

Async.blocking:
Future:
Future.withResolver: resolver =>
resolver.spawn:
val packet: DatagramPacket =
new DatagramPacket(data.array(), data.limit(), InetAddress.getByName(address), port)
socket.get.send(packet)

def receive(): Future[DatagramPacket] =
assert(socket.isDefined)

Async.blocking:
Future[DatagramPacket]:
Future.withResolver: resolver =>
resolver.spawn:
val buffer = Array.fill[Byte](10 * 1024)(0)
val packet: DatagramPacket = DatagramPacket(buffer, 10 * 1024)
socket.get.receive(packet)
Expand All @@ -133,6 +136,15 @@ class SocketUDP() {
}
}

object SocketUDP:
extension [T](resolver: Future.Resolver[T])
private[SocketUDP] inline def spawn(body: => T)(using s: Scheduler) =
s.execute(() =>
resolver.complete(Try(body).recover { case _: InterruptedException =>
throw CancellationException()
})
)

object PIOHelper {
def withFile[T](path: String, options: StandardOpenOption*)(f: File => T): T =
val file = File(path).open(options*)
Expand Down

0 comments on commit 01b7d49

Please sign in to comment.