refactor: improve resource safety and structure of writer

This commit is contained in:
Jonny
2025-03-02 03:26:28 +00:00
parent 9a5ccea1f6
commit abb43b560d

View File

@@ -13,15 +13,30 @@ import java.nio.file.Path
object writer { object writer {
import assemblyIR._ import assemblyIR._
def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] = // TODO: Judging from documentation it seems as though IO.blocking is the correct choice
Resource // But needs checking
.fromAutoCloseable {
IO(BufferedWriter(FileWriter(outputPath.toFile, StandardCharsets.UTF_8))) /** Creates a resource safe BufferedWriter */
private def bufferedWriter(outputPath: Path): Resource[IO, BufferedWriter] =
Resource.make {
IO.blocking(new BufferedWriter(new FileWriter(outputPath.toFile, StandardCharsets.UTF_8)))
} { writer =>
IO.blocking(writer.close())
.handleErrorWith(_ => IO.unit) // TODO: ensures writer is closed even if an error occurs
} }
.use { writer =>
IO { /** Write line safely into a BufferedWriter */
asmList.iterator.foreach(line => writer.write(line.toString + "\n")) private def writeLines(writer: BufferedWriter, lines: Chain[AsmLine]): IO[Unit] =
writer.flush() // TODO: NECESSARY OR NOT? IO.blocking {
} *> logger.info(s"Success: ${outputPath.toAbsolutePath}") lines.iterator.foreach { line =>
writer.write(line.toString)
writer.newLine()
}
}
/** Main function to write assembly to a file */
def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] =
bufferedWriter(outputPath).use { writer =>
writeLines(writer, asmList) *> logger.info(s"Success: ${outputPath.toAbsolutePath}")
} }
} }