Back to Fpinscala

05.Answer

answerkey/iomonad/05.answer.md

latest632 B
Original Source
scala
import java.nio.*
import java.nio.channels.*

def read(file: AsynchronousFileChannel,
          fromPosition: Long,
          numBytes: Int): Free[Par, Either[Throwable, Array[Byte]]] =
  Suspend(Par.async: (cb: Either[Throwable, Array[Byte]] => Unit) =>
    val buf = ByteBuffer.allocate(numBytes)
    file.read(buf, fromPosition, (), new CompletionHandler[Integer, Unit]:
      def completed(bytesRead: Integer, ignore: Unit) =
        val arr = new Array[Byte](bytesRead)
        buf.slice.get(arr, 0, bytesRead)
        cb(Right(arr))
      def failed(err: Throwable, ignore: Unit) =
        cb(Left(err))
    )
  )