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._
// TODO: Judging from documentation it seems as though IO.blocking is the correct choice
// But needs checking
/** 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
}
/** Write line safely into a BufferedWriter */
private def writeLines(writer: BufferedWriter, lines: Chain[AsmLine]): IO[Unit] =
IO.blocking {
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] = def writeTo(asmList: Chain[AsmLine], outputPath: Path)(using logger: Logger[IO]): IO[Unit] =
Resource bufferedWriter(outputPath).use { writer =>
.fromAutoCloseable { writeLines(writer, asmList) *> logger.info(s"Success: ${outputPath.toAbsolutePath}")
IO(BufferedWriter(FileWriter(outputPath.toFile, StandardCharsets.UTF_8))) }
}
.use { writer =>
IO {
asmList.iterator.foreach(line => writer.write(line.toString + "\n"))
writer.flush() // TODO: NECESSARY OR NOT?
} *> logger.info(s"Success: ${outputPath.toAbsolutePath}")
}
} }