buffer to struct type conversion...TArrayStream?
Charles Hixson via Digitalmars-d-learn
digitalmars-d-learn at puremagic.com
Thu Mar 19 13:11:30 PDT 2015
On 03/19/2015 12:05 PM, via Digitalmars-d-learn wrote:
> On Thursday, 19 March 2015 at 18:42:03 UTC, Marc Schütz wrote:
>> 3) Using std.bitmap.peek(), which also supports conversion between
>> big- and little-endian:
>> import std.bitmap;
>> n.self = buf.peek!(Node.Node_, Endian.bigEndian);
>>
>> (The examples are untested, it's possible you'll need to make some
>> adjustments to make them work.)
>>
>> You should probably use option 3). It is safe, because it checks that
>> the buffer has the right size, and it also allows you to specify the
>> endian-ness (many file formats have a standardized endian-ness).
>>
>> While you're at it, you can also try std.bitmanip.read(). It can be
>> applied to any range, so you can probably do something like this
>> (also untested):
>>
>> auto input = btFile.byChunk(4096).joiner;
>> while(!input.empty) {
>> auto node = input.read!(Node.Node_, Endian.bigEndian);
>> // use `node`
>> }
>
> Urgh... it seems `peek()` and `read()` only work with numerical types
> :-( Is this intentional? It would be quite useful for arbitrary types,
> IMO, even if care must be taken with regard to pointers.
>
Note: Thanks for the prior comment about where to place the array
markers. I keep forgetting.
Umnf...I don't plan on needing conversion between Endian versions, but I
guess that's important. But more significant if it only handles numeric
types I wonder about handling arrays of structs, even if those structs
*are* composed entirely of numerical types. Being secure against a
future need to handle Endian variations would be good, but not enough to
both increase the complexity that way and deal with possible unexpected
errors.
P.S.: Looking at the std.bitmanip documentation causes me to feel that
the restriction to integral types was intentional, though admittedly it
doesn't seem to be stated explicitly, but all of the examples seem to be
simple arrays. I'll grant that this could be just to keep things
simple. And the wording of the docs causes me to think it would
probably only work for integral values, as in not even floats. This is
reasonable if you are thinking of it as a set of routines for bit
manipulation.
At all events, I think that it involves excessive overhead (in code
verbosity) and that I'ld likely need to use a loop to read the array
within the struct. A simple bit copy is much more straightforwards (I
was already checking that the read was the correct length, though I
haven't decided what to do if that ever fails. Currently it's an assert
statement, but this clearly needs to be changed to either an enforce
statement or to a thrown exception...but I haven't yet thought of a
valid case where the block would be an incorrect length.
More information about the Digitalmars-d-learn
mailing list