-
-
Notifications
You must be signed in to change notification settings - Fork 1.6k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add Crystal.print_buffered(io) and Crystal.print_error_buffered (#15343)
Writes a message to a growable, in-memory buffer, before writing to a standard IO (e.g. STDERR) in a single write (possibly atomic, depending on PIPE_BUF) instead of having many individual writes to the IO which will be intermingled with other writes and be completely unintelligible.
- Loading branch information
1 parent
5b20837
commit 7135b1d
Showing
2 changed files
with
45 additions
and
12 deletions.
There are no files selected for viewing
This file contains 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,42 @@ | ||
module Crystal | ||
# Prepares an error message, with an optional exception or backtrace, to an | ||
# in-memory buffer, before writing to an IO, usually STDERR, in a single write | ||
# operation. | ||
# | ||
# Avoids intermingled messages caused by multiple threads writing to a STDIO | ||
# in parallel. This may still happen, since writes may not be atomic when the | ||
# overall size is larger than PIPE_BUF, buf it should at least write 512 bytes | ||
# atomically. | ||
def self.print_buffered(message : String, *args, to io : IO, exception = nil, backtrace = nil) : Nil | ||
buf = buffered_message(message, *args, exception: exception, backtrace: backtrace) | ||
io.write(buf.to_slice) | ||
io.flush unless io.sync? | ||
end | ||
|
||
# Identical to `#print_buffered` but eventually calls `System.print_error(bytes)` | ||
# to write to stderr without going through the event loop. | ||
def self.print_error_buffered(message : String, *args, exception = nil, backtrace = nil) : Nil | ||
buf = buffered_message(message, *args, exception: exception, backtrace: backtrace) | ||
System.print_error(buf.to_slice) | ||
end | ||
|
||
private def self.buffered_message(message : String, *args, exception = nil, backtrace = nil) | ||
buf = IO::Memory.new(4096) | ||
|
||
if args.empty? | ||
buf << message | ||
else | ||
System.printf(message, *args) { |bytes| buf.write(bytes) } | ||
end | ||
|
||
if exception | ||
buf << ": " | ||
exception.inspect_with_backtrace(buf) | ||
else | ||
buf.puts | ||
backtrace.try(&.each { |line| buf << " from " << line << '\n' }) | ||
end | ||
|
||
buf | ||
end | ||
end |
This file contains 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