std.stdio.File 和 std.stream 之间的相互兼容性。*
Intercompatibility between std.stdio.File and std.stream.*
有什么好的方法可以将 std.stdio.File
转换为来自 std.stream
的流的实例吗?
原因:我发现自己想要一个在流上工作的通用日志实用程序,我想传递它 std.stdio.stderr
,这是一个 std.stdio.File
.
示例:
import std.stream;
import std.cstream;
void main() {
ubyte[] data = cast(ubyte[])"someData";
OutputStream stream = derr;
stream.write(data);
}
顺便说一句。 D标准库中有一个logging module
使用范围代替已弃用的 std.stream
模块。
import std.stdio;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
// Log levels
enum LEVEL {
DEBUG,
INFO,
WARN
};
alias LogMsg = Tuple!(LEVEL, string); // Should be a struct, but I'm lazy
void main() {
// Get a writer, which is an OutputRange
auto writer = stderr.lockingTextWriter();
// Some messages. Can be any InputRange, not just an array
auto messages = [
LogMsg(LEVEL.DEBUG, "Log message 1"),
LogMsg(LEVEL.INFO, "Log message 2"),
LogMsg(LEVEL.WARN, "Log message 3"),
];
// Write each message to the writer
put(writer, messages
// transform LogMsg's into strings to write.
// Bonus points: use chain instead of ~ to avoid allocation
.map!(msg => msg[0].to!string ~ ": " ~ msg[1] ~ "\n")
);
}
有什么好的方法可以将 std.stdio.File
转换为来自 std.stream
的流的实例吗?
原因:我发现自己想要一个在流上工作的通用日志实用程序,我想传递它 std.stdio.stderr
,这是一个 std.stdio.File
.
示例:
import std.stream;
import std.cstream;
void main() {
ubyte[] data = cast(ubyte[])"someData";
OutputStream stream = derr;
stream.write(data);
}
顺便说一句。 D标准库中有一个logging module
使用范围代替已弃用的 std.stream
模块。
import std.stdio;
import std.range;
import std.algorithm;
import std.typecons;
import std.conv;
// Log levels
enum LEVEL {
DEBUG,
INFO,
WARN
};
alias LogMsg = Tuple!(LEVEL, string); // Should be a struct, but I'm lazy
void main() {
// Get a writer, which is an OutputRange
auto writer = stderr.lockingTextWriter();
// Some messages. Can be any InputRange, not just an array
auto messages = [
LogMsg(LEVEL.DEBUG, "Log message 1"),
LogMsg(LEVEL.INFO, "Log message 2"),
LogMsg(LEVEL.WARN, "Log message 3"),
];
// Write each message to the writer
put(writer, messages
// transform LogMsg's into strings to write.
// Bonus points: use chain instead of ~ to avoid allocation
.map!(msg => msg[0].to!string ~ ": " ~ msg[1] ~ "\n")
);
}