Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I just started learning D today and I really need to read and write data like this:

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

Is there anything built in to D that can achieve this or must I make it myself?

like image 375
user3441843 Avatar asked Jan 01 '26 03:01

user3441843


1 Answers

I'd suggest looking at std.bitmanip's read, peek, write and append functions. e.g.

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]);

There is no buffer type - rather they're free functions which operate on ranges of ubyte (which includes ubyte[]) - so they may not work exactly like what you're looking for, but they are designed for the case where you need to extract integral values from an array or some other kind of range of bytes. And if you really want some kind of separate buffer type, then you should be able to create one fairly easily which uses them internally.

like image 111
Jonathan M Davis Avatar answered Jan 04 '26 16:01

Jonathan M Davis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!