Skip to content

Commit

Permalink
ch08 reorganize filePipeOut
Browse files Browse the repository at this point in the history
  • Loading branch information
spamegg1 committed Sep 6, 2024
1 parent cde53db commit f617b44
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 10 deletions.
20 changes: 12 additions & 8 deletions src/main/scala/ch08/filePipe/FilePipe.scala
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@ object FilePipe:
def apply(path: CString): Pipe[String, String] =
val req = stdlib.malloc(uv_req_size(UV_FS_REQ_T)).asInstanceOf[FSReq]
checkError(uv_fs_open(ch07.EventLoop.loop, req, path, 0, 0, null), "uv_fs_open")

println("opening file")
val fd = util.open(path, 0, 0)
stdio.printf(c"open file at %s returned %d\n", path, fd)
Expand All @@ -30,14 +31,14 @@ object FilePipe:
val state = stdlib.malloc(sizeof[FilePipeState]).asInstanceOf[Ptr[FilePipeState]]
val buf = stdlib.malloc(sizeof[Buffer]).asInstanceOf[Ptr[Buffer]]
buf._1 = stdlib.malloc(4096) // 0.5
buf._2 = 4095.toUSize // 0.5
buf._2 = 4095.toCSize // 0.5
state._1 = fd
state._2 = buf
state._3 = 0L
!req = state.asInstanceOf[Ptr[Byte]]

println("about to read")
uv_fs_read(ch07.EventLoop.loop, req, fd, buf, 1, -1, readCB)
uv_fs_read(ch07.EventLoop.loop, req, fd, buf, 1, -1, readCB) // returns only once
println("read started")

val pipe = Pipe.source[String]
Expand All @@ -51,22 +52,25 @@ object FilePipe:
println("read callback fired!")
val res = uv_fs_get_result(req)
println(s"got result: $res")
val state_ptr = (!req).asInstanceOf[Ptr[FilePipeState]]

val statePtr = (!req).asInstanceOf[Ptr[FilePipeState]]
println("inspecting state")
val fd = state_ptr._1
val buf = state_ptr._2
val offset = state_ptr._3
val fd = statePtr._1
val buf = statePtr._2
val offset = statePtr._3
printf("state: fd %d, offset %d\n", fd, offset.toInt)

if res > 0 then
println("producing string")
(buf._1)(res) = 0.toByte // null termination?
val output = fromCString(buf._1)

val pipe = handlers(fd)
pipe.feed(output)

println("continuing")
state_ptr._3 = state_ptr._3 + res
uv_fs_read(ch07.EventLoop.loop, req, fd, state_ptr._2, 1, state_ptr._3, readCB)
statePtr._3 = statePtr._3 + res
uv_fs_read(ch07.EventLoop.loop, req, fd, statePtr._2, 1, statePtr._3, readCB)
else if res == 0 then
println("done")
val pipe = handlers(fd)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ import ch07.LibUV.*, ch07.LibUVConstants.*

case class FileOutputPipe(fd: Int, serial: Int, async: Boolean)
extends Pipe[String, Unit]:
import ch07.LibUV.*, ch07.LibUVConstants.*

var offset = 0L

Expand Down Expand Up @@ -73,7 +72,7 @@ object FileOutputPipe:
// val closeCB = CFunctionPtr.fromFunction1(onClose)

@main
def filePipeOut(args: String*): Unit =
def run: Unit =
given ec: ExecutionContext = ch07.EventLoop

val p = FilePipe(c"./data.txt")
Expand Down

0 comments on commit f617b44

Please sign in to comment.