File.buffered
func File.buffered(f: File.Handle, size: int = 4096): File.HandleFile.buffered returns a handle over f whose writes collect in a buffer of size bytes, written to f when a write does not fit, at File.flush, and at File.close, and at nothing else: a buffered handle neither flushed nor closed when the run ends loses what it holds. It is for a loop of many small writes. A write is Err at once when f cannot be written, such as a handle from File.open. f itself is returned when it is buffered with at least size bytes; a size below 1 gives the default. Reads of the handle read f. The first error writing the buffer out is kept and returned by every later write and flush, and by the first close. A write to f itself goes past the buffer.
Details
File.closeof the buffered handle writes the buffer out and closesf. Check its result: a deferred close cannot report an error. Over a standard stream,File.closewrites the buffer out and leaves the stream open.- A flush or a close hands the buffer to the OS but does not wait for the disk. File.sync writes the buffer out and then has the OS write the file to storage, for data that must survive a crash.
Basic examples
Buffer the lines written to a file, and close it to write them out:
func save(path: string, lines: Array[string]): Result[void, Error] {
let out = File.buffered(try File.create(path))
defer { out.close() }
for line in lines { try out.writeLine(line) }
out.close()
}
println(save("notes.txt", ["first", "second"]))
println(File.read("notes.txt"))Ok{ value: void }
Ok{ value: "first\nsecond\n" }Buffer standard output for a loop of many small writes, and flush it at the end:
let out = File.buffered(Os.stdout())
for i in Iter.range(1, 4) {
try out.writeLine("line ${i}")
}
try out.flush()line 1
line 2
line 3Scope
The file stays empty until the buffer is written out:
let out = File.buffered(Result.unwrap(File.create("log.txt")))
try out.writeLine("started")
println(File.read("log.txt"))
try out.flush()
println(File.read("log.txt"))
try out.close()Ok{ value: "" }
Ok{ value: "started\n" }Closing a buffered standard output writes it out and leaves standard output open:
let out = File.buffered(Os.stdout())
try out.writeLine("buffered")
println(out.close())
println("stdout still open")buffered
Ok{ value: void }
stdout still openReads of a buffered handle read f, so one handle can serve both:
let names = File.buffered(Result.unwrap(File.open("names.txt")))
defer { names.close() }
println(names.readLine())
println(names.readLine())Ok{ value: "Ann" }
Ok{ value: "Bob" }Buffering a buffered handle again with no larger size returns the same handle:
let out = File.buffered(Result.unwrap(File.create("twice.txt")))
println(File.buffered(out) == out)
println(File.buffered(out, size: 8192) == out)
try out.close()true
falseNamed arguments
size sets how many bytes the buffer holds. A write that does not fit writes the buffer out:
let out = File.buffered(Result.unwrap(File.create("small.txt")), size: 8)
try out.writeText("abc")
println(File.read("small.txt"))
try out.writeText("defghijk")
println(Result.unwrap(File.read("small.txt")).startsWith("abc"))
try out.close()
println(File.read("small.txt"))Ok{ value: "" }
true
Ok{ value: "abcdefghijk" }A size below 1 gives the default:
let out = File.buffered(Os.stdout(), size: 0)
try out.writeText("held until flush\n")
try out.flush()held until flushApplications
Write a CSV report row by row, and report a failure to finish it:
type Sale = { item: string, amount: int }
func writeReport(path: string, sales: Array[Sale]): Result[void, Error] {
let out = File.buffered(try File.create(path))
defer { out.close() }
try out.writeLine("item,amount")
for sale in sales { try out.writeLine("${sale.item},${sale.amount}") }
out.close() | Result.wrapErr("write ${path}")
}
let sales = [Sale{ item: "tea", amount: 3 }, Sale{ item: "cake", amount: 5 }]
println(writeReport("sales.csv", sales))
println(File.read("sales.csv"))Ok{ value: void }
Ok{ value: "item,amount\ntea,3\ncake,5\n" }Accept any handle and flush it without knowing whether it is buffered:
func greet(out: File.Handle, names: Array[string]): Result[void, Error] {
for name in names { try out.writeLine("Hello, ${name}") }
out.flush()
}
println(greet(Os.stdout(), ["Ann"]))
println(greet(File.buffered(Os.stdout()), ["Bob"]))Hello, Ann
Ok{ value: void }
Hello, Bob
Ok{ value: void }Properties and relations
File.flush and File.close on the buffered handle are Ok; File.flush on a handle that is not buffered does nothing and is Ok:
let f = Result.unwrap(File.create("props.txt"))
let out = File.buffered(f)
assert(out.writeText("x") is Ok)
assert(f.flush() is Ok)
assert(Result.unwrap(File.read("props.txt")) == "")
assert(out.flush() is Ok)
assert(Result.unwrap(File.read("props.txt")) == "x")
assert(out.close() is Ok)
assert(out.close() is Ok)Possible issues
A buffered handle neither flushed nor closed loses what it holds when the program ends. This program prints nothing:
let out = File.buffered(Os.stdout())
try out.writeLine("lost")A println goes past the buffer of a buffered standard output, so it comes out first:
let out = File.buffered(Os.stdout())
try out.writeLine("written first")
println("printed second")
try out.flush()printed second
written firstA write after the close is Err, and a second close does nothing:
let out = File.buffered(Result.unwrap(File.create("closed.txt")))
println(out.close())
println(out.writeLine("late"))
println(out.close())Ok{ value: void }
Err{ error: Error{ message: "the file is closed" } }
Ok{ value: void }See also
File.flush · File.close · File.sync · File.create · File.writeLine · File.writeText · Os.stdout
