Conversion to output ranges

Timon Gehr timon.gehr at gmx.ch
Tue Feb 7 07:49:43 PST 2012


On 02/07/2012 02:35 PM, Mafi wrote:
> Hi,
> does anybody know how to bring std.conv.to or something similar to
> output into an output range?
>
> int a = 42;
> char[25] buffer;
> to!typeof(buffer[])(a, buffer[]);
>
> I want to send these texts throw sockets. Therefore I'd like to reuse
> the buffer.
>
> Mafi

You could use std.format.formattedWrite.

import std.exception, std.format, std.stdio;

// I don't know if this already exists somewhere:
struct Filler(T:T[]){
     this(T[] pl){payload = pl;}
     size_t index=0;
     T[] payload;
     void put(const T[] s){
         enforce(payload.length>=index+s.length);
         payload[index..index+s.length]=s;
         index+=s.length;
     }
     void put(char s){
         enforce(payload.length>=index);
         payload[index++]=s;
     }
     @property auto data(){return payload[0..index];}
}
auto filler(T)(T pl){return Filler!T(pl);}

void main(){
     int a = 42;
     char[25] buffer;
     auto f = filler(buffer[]);
     formattedWrite(&f,"%s",a);
     writeln(f.data);
}


More information about the Digitalmars-d-learn mailing list