Reading a string in binary mode

Christof Schardt csnews at schardt.info
Mon Mar 3 14:52:06 PST 2014


"John Colvin" <john.loughran.colvin at gmail.com> schrieb im Newsbeitrag 
news:zjsykclxreagfhqsqpau at forum.dlang.org...
> On Monday, 3 March 2014 at 22:22:06 UTC, Christof Schardt wrote:
>> "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.
>
> Doesn't seem like trickery to me; you just make a new array of the correct 
> size and then fill it from the file. Is that not what you expected to do?
>
> The only thing that is unusual is assumeUnique, but if you understand that 
> string is an alias to immutable(char)[] then it should be apparent why 
> it's there. You could just write "x = cast(string)tmp;" instead, it's the 
> same.

By "trickery" I meant having to know about things like
"import std.exception : assumeUnique" for this basic kind of task.

Anyway, since D has an incredible community, which answers questions
like mine within minutes, this is not really an obstacle.














More information about the Digitalmars-d-learn mailing list