Search code examples
arraysdbytebufferread-write

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?


Solution

  • 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.