Last active
November 20, 2017 16:56
-
-
Save scr/c6aed73a18e2acc12715f1f59ae35ee2 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package tinker.scalazEffect | |
| import java.nio.ByteBuffer | |
| import java.nio.channels.{AsynchronousChannel, AsynchronousFileChannel, CompletionHandler} | |
| import java.nio.charset.{Charset, StandardCharsets} | |
| import java.nio.file.{Path, Paths, StandardOpenOption} | |
| import scalaz.data.Disjunction.{-\/, \/-} | |
| import scalaz.effect.console._ | |
| import scalaz.effect.{IO, SafeApp} | |
| object FileMain extends SafeApp { | |
| def closeAC(ac: AsynchronousChannel): IO[Unit] = { | |
| ac.close() | |
| IO.unit | |
| } | |
| def readAllBytes(path: Path): IO[Array[Byte]] = { | |
| IO.sync(AsynchronousFileChannel.open(path, StandardOpenOption.READ)).bracket(closeAC) { afc => | |
| for { | |
| afcSize <- IO.sync { | |
| val size = afc.size() | |
| require(size <= Int.MaxValue) | |
| size.asInstanceOf[Int] | |
| } | |
| bufferSize <- IO.now(1024 * 1024) | |
| range <- IO.point(0 until afcSize by bufferSize) | |
| buffer <- IO.sync(ByteBuffer.allocate(1024 * 1024)) | |
| bytes <- IO.sync(new Array[Byte](afcSize)) | |
| ret <- IO.async[Array[Byte]] { cb => | |
| // TODO(scr): How can this be more IO-savvy? | |
| val completionHandler: CompletionHandler[Integer, Integer] = new CompletionHandler[Integer, Integer] { | |
| override def failed(exc: Throwable, attachment: Integer): Unit = cb(-\/(exc)) | |
| override def completed(numRead: Integer, position: Integer): Unit = { | |
| buffer.flip() | |
| buffer.get(bytes, position, numRead) | |
| val nextPosition = position + numRead | |
| if (nextPosition >= afcSize) { | |
| cb(\/-(bytes)) | |
| } else { | |
| buffer.clear() | |
| afc.read[Integer](buffer, nextPosition, nextPosition, this) | |
| } | |
| } | |
| } | |
| afc.read[Integer](buffer, 0, 0, completionHandler) | |
| } | |
| } yield ret | |
| } | |
| } | |
| def bytesToString(bytes: Array[Byte], charset: Charset = StandardCharsets.UTF_8): IO[String] = { | |
| IO.sync(new String(bytes, charset)) | |
| } | |
| override def run(args: List[String]): IO[Unit] = { | |
| for { | |
| fooPath <- IO.point(Paths.get("foo.txt")) | |
| bytes <- readAllBytes(fooPath) | |
| s <- bytesToString(bytes) | |
| _ <- putStrLn(s"out $s") | |
| } yield () | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment