Reading a string in binary mode

Christof Schardt csnews at schardt.info
Mon Mar 3 14:21:57 PST 2014


"John Colvin" <john.loughran.colvin at gmail.com> schrieb im Newsbeitrag 
news:dyfkblqonigrtmkwtfjs at forum.dlang.org...
> On Monday, 3 March 2014 at 21:44:16 UTC, Christof Schardt wrote:
>> I'm evaluating D and try to write a binary io class.
>> I got stuck with strings:
>>
>>     void rw(ref string x)
>>     {
>>         if(_isWriting)
>>         {
>>             int size = x.length;
>>             _f.rawWrite((&size)[0..1]);
>>             _f.rawWrite(x);
>>         }
>>         else
>>         {
>>             int size;
>>             _f.rawRead((&size)[0..1]);
>>
>>             ... what now?
>>         }
>>     }
>>
>> Writing is ok, but how do I read the bytes to the
>> string x after having its size?
>
>
> Assuming you're not expecting pre-allocation (which I infer from your 
> choice of "ref string" instead of "char[]"), you could do this:
>
>>     void rw(ref string x)
>>     {
>>         if(_isWriting)
>>         {
>>             size_t size = x.length;
>>             _f.rawWrite((&size)[0..1]);
>>             _f.rawWrite(x);
>>         }
>>         else
>>         {
>>             size_t size;
>>             _f.rawRead((&size)[0..1]);
>>             auto tmp = new char[size];
>>             _f.rawRead(tmp);
>>             import std.exception : assumeUnique;
>>             x = tmp.assumeUnique;
>>         }
>>     }

Thanks, John, this works.

Though it feels a bit strange, that one has to do such trickery in order to
perform basic things like binary io of strings.





More information about the Digitalmars-d-learn mailing list