D - 是否有用于读取和写入字节的字节缓冲区?

D - Is there a bytebuffer for reading and writing bytes?

今天刚开始学D,真的需要这样读写数据:

byte[] bytes = ...;
ByteBuffer buf = new ByteBuffer(bytes);
int a = buf.getInt();
byte b = buf.getByte();
short s = buf.getShort();
buf.putInt(200000);

D 中是否有任何内置的东西可以实现这一点,还是我必须自己制作?

旧的 std.stream 模块应该可以解决问题:http://dlang.org/phobos/std_stream.html#MemoryStream

MemoryStream buf = new MemoryStream(bytes);
// need to declare the variable ahead of time
int a;
// then read knows what to get due to the declared type
buf.read(a);
byte b;
buf.read(b);
but.write(200000); // that is an int literal so it knows it is int
buf.write(cast(ubyte) 255); // you can also explicitly cast

不过正如页面上的警告所说,Phobos 维护者不喜欢这个模块并想杀死它......但他们多年来一直在说,我会继续使用它.如果您愿意,也可以制作 stream.d 源的私人副本。

我建议查看 std.bitmanip 的 read, peek, write and append 函数。例如

ubyte[] buffer = [1, 5, 22, 9, 44, 255, 8];
auto range = buffer; // if you don't want to mutate the original

assert(range.read!ushort() == 261);
assert(range == [22, 9, 44, 255, 8]);

assert(range.read!uint() == 369_700_095);
assert(range == [8]);

assert(range.read!ubyte() == 8);
assert(range.empty);
assert(buffer == [1, 5, 22, 9, 44, 255, 8]);

没有缓冲区类型 - 它们是在 ubyte(包括 ubyte[])范围内运行的自由函数 - 因此它们可能不会完全像你正在寻找的那样工作,但它们是为需要从数组或其他类型的字节范围中提取整数值的情况而设计的。如果你真的想要某种单独的缓冲区类型,那么你应该能够相当容易地创建一个在内部使用它们的缓冲区。