Re: Socket: Detect connection close

2014-03-24 Thread Vladimir Panteleev

On Monday, 24 March 2014 at 18:06:56 UTC, nrgyzer wrote:
Alright, that world work. But what about sending 10 Bytes, 
waiting some minutes (probably some hours) and sending 10 Bytes 
again. Is it possible to do this on the same Socket?


Yes. Unless your socket is marked as non-blocking, the read 
operation will block until more data is available (or the 
connection gets closed).


My scenario is: I've one central server and multiple clients. 
The clients are connecting to the server and send (or request) 
some information. After that the clients are simply "sleeping" 
for an unknown time. For instance client 1 for 1 seconds, 
client 2 for 1 minute, client 3 for 1 hours and client 4 for 1 
day. After that time they resend/request some more information 
from the server... my questions regarding this are:


- When I client connects, the server creates a thread. How can 
I determine that I can terminate the thread because the 
connection is inactive (for instance because the client closed 
the connection or some connecting issues)?


As mentioned previously, you know that the connection was closed 
cleanly on the remote side when receive returns an empty buffer.


- How can the client check if the connection is alive? (If the 
connection isn't alive, I need to reconnect)


You generally have to implement this yourself. Silence on the 
wire can mean two things:


1. No data is being sent;
2. Something is preventing data from being sent (lost packets, a 
peer was shut down or restarted, Internet routing changes, 
squirrel chewed through a wire).


Generally network software implements "ping" packets that are 
sent occasionally (once every few seconds or minutes). If no 
"ping" packets are received throughout a certain interval, the 
connection is considered dead.


TCP also has a "keepalive" option which does this for you, but it 
is an optional TCP feature and thus may or may not work.


Re: Function implemented outside the class

2014-03-24 Thread Rikki Cattermole

On Sunday, 23 March 2014 at 21:48:33 UTC, MarisaLovesUsAll wrote:
Hi! I didn't find how to implement functions outside the class, 
like in C++.


C++:
class MyClass
{
   void myFunc();
};
void MyClass::myFunc() { ... }

Is it possible to do this in D ?


Sorry for my bad English.
Regards,
Alexey


There is one way that could be made far nicer with templates and 
traits but..


import std.stdio;

alias void delegate() testfunc;

class T {
this() {
test = () { test_(this); }; 
}


testfunc test;
}

void test_(T t) {
writeln("hi from test");
}

void main() {
T t = new T();
t.test();
}

There will be other ways to make this nicer. If you feel you 
really really want this sort of thing (advised not to).


Re: Function to print a diamond shape

2014-03-24 Thread Jay Norwood
These were times on ubuntu. I may have printed debug build times 
previously, but these are dmd release build.  I gave up trying to 
figure out how to build ldc on ubuntu.  The dmd one click 
installer is much appreciated.


brad: time: 12425[ms]
printDiamond1: time: 380[ms]
printDiamond2: time: 728[ms]
printDiamond3: time: 378[ms]
jay1: time: 62[ms]
sergei: time: 3965[ms]
jay2: time: 27[ms]
diamondShape: time: 2778[ms]
printDiamond: time: 19[ms]
printDiamonde: time: 19[ms]
printDiamonde2b: time: 16[ms]


This was using the appended newlines to get rid of the extra wput 
in the loops.


void printDiamonde2b(in uint N)
{
uint N2 = N/2;
char pSpace[] = uninitializedArray!(char[])(N2);
pSpace[] = ' ';

char pStars[] = uninitializedArray!(char[])(N+1);
pStars[] = '*';

pStars[$-1] = '\n';

auto w = appender!(char[])();
w.reserve(N*3);

foreach (n ; 0 .. N2 + 1){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[$-2*n-2 .. $]);
}

foreach_reverse (n ; 0 .. N2){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[$-2*n-2 .. $]);
}

write(w.data);
}


Re: Problems with OutputRanges

2014-03-24 Thread Ali Çehreli

On 03/24/2014 07:42 PM, Meta wrote:

> I'm not sure what I'm doing wrong... the following code prints nothing:
>
> void main()
> {
>  import std.stdio, std.range;
>
>  string str = "asdf";
>  auto sink = new dchar[](str.length);
>  auto fun = (dchar c) { sink.put(c); };
>  foreach (dchar c; str)
>  {
>  fun(c);
>  }
>  writeln(sink);
> }
>
> If I print sink's length inside the foreach loop, its length is reduced
> by 1 each step, until it's 0. That explains why nothing is being
> printed, but why is put altering the length of the array?

Very many things can be output ranges depending on what operations they 
support:


  http://dlang.org/phobos/std_range.html#.put

sink above is a slice, matching "if R defines put, r.front = e if r is 
an input range (followed by r.popFront())" in the above document. That's 
popFront() in that excerpt that is causing the loss of element here.


I have a more detailed explanation of this under the "Using slices as 
OutputRange" section in the following chapter:


  http://ddili.org/ders/d.en/ranges.html

So, one of the solutions here is to use a surrogate slice instead:

auto sinkSurrogate = sink;
auto fun = (dchar c) { sinkSurrogate.put(c); };

Now, sinkSurrogate will lose elements and sink will still be usable.

Ali



Problems with OutputRanges

2014-03-24 Thread Meta
I'm not sure what I'm doing wrong... the following code prints 
nothing:


void main()
{
import std.stdio, std.range;

string str = "asdf";
auto sink = new dchar[](str.length);
auto fun = (dchar c) { sink.put(c); };
foreach (dchar c; str)
{
fun(c);
}
writeln(sink);
}

If I print sink's length inside the foreach loop, its length is 
reduced by 1 each step, until it's 0. That explains why nothing 
is being printed, but why is put altering the length of the array?


Re: Function to print a diamond shape

2014-03-24 Thread Jay Norwood
not through yet with the diamond.  This one is a little faster.  
Appending the newline to the stars and calculating the slice 
backward from the end would save a w.put for the newlines ... 
probably faster.  I keep looking for a way to create a dynamic 
array of a specific size, filled with the init value I provide. 
Does it exist?


D:\diamond\diamond\diamond\Release>diamond 1>nul
brad: time: 19370[ms]
printDiamond1: time: 1140[ms]
printDiamond2: time: 1631[ms]
printDiamond3: time: 633[ms]
jay1: time: 459[ms]
sergei: time: 11886[ms]
jay2: time: 415[ms]
diamondShape: time: 4553[ms]
printDiamond: time: 187[ms]
printDiamonde2a: time: 139[ms]


void printDiamonde2a(in uint N)
{
size_t N2 = N/2;
char pSpace[] = uninitializedArray!(char[])(N2);
pSpace[] = ' ';

char pStars[] = uninitializedArray!(char[])(N);
pStars[] = '*';

char pNewLine[]=uninitializedArray!(char[])(2);
pNewLine[] = '\n';

auto w = appender!(char[])();
w.reserve(N*4);

foreach (n ; 0 .. N2 + 1){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[0 .. 2*n+1]);
w.put(pNewLine[1]);
}

foreach_reverse (n ; 0 .. N2){
w.put(pSpace[0 .. N2 - n]);
w.put(pStars[0 .. 2*n+1]);
w.put(pNewLine[1]);
}
write(w.data);
}


Re: CMake for D

2014-03-24 Thread Trent Forkert

On Monday, 24 March 2014 at 23:55:14 UTC, Dragos Carp wrote:


Any alternatives??


I moved cmaked2 to github [1], updated and simplified the usage 
a

little (system cmake patch not necessary anymore). You can give
it a try. Dub registry support is also on the way.

Regards
Dragos


[1] - https://github.com/dcarp/cmake-d


Heh, seems I waited a bit too long, eh? I've been gearing up to 
do an initial release of some modifications to CMake that give 
better D support. (To clarify: this isn't being merged upstream 
yet, but hopefully that'll happen eventually)


While the approach taken by CMakeD2 and cmake-d gets a good 
amount of the way there, it lacks key CMake features. Namely: 
Visual Studio support, which unfortunately requires patching the 
C++ source.


The module-only approach also cannot support LDC (save via ldmd, 
which is not ideal), as CMake will think it is a linker. There 
were other problems I encountered that required changes to the 
C++ code as well, though I don't recall what they were off the 
top of my head.


I'm curious to see how you intend to do dub support, though.

 - Trent


Re: CMake for D

2014-03-24 Thread ed

On Monday, 24 March 2014 at 23:55:14 UTC, Dragos Carp wrote:


Any alternatives??


I moved cmaked2 to github [1], updated and simplified the usage 
a

little (system cmake patch not necessary anymore). You can give
it a try. Dub registry support is also on the way.

Regards
Dragos


[1] - https://github.com/dcarp/cmake-d


You beat me to it :)

I was going to github my version today at work but I'll drop it 
now and work from your repo.


Thanks setting it up!

Cheers,
ed


Re: CMake for D

2014-03-24 Thread Andrei Alexandrescu

On 3/24/14, 4:55 PM, Dragos Carp wrote:


Any alternatives??


I moved cmaked2 to github [1], updated and simplified the usage a
little (system cmake patch not necessary anymore). You can give
it a try. Dub registry support is also on the way.

Regards
Dragos


[1] - https://github.com/dcarp/cmake-d


Fantastic, thanks Dragos!! A fellow Romanian it seems :o) -- Andrei



Re: CMake for D

2014-03-24 Thread Dragos Carp


Any alternatives??


I moved cmaked2 to github [1], updated and simplified the usage a
little (system cmake patch not necessary anymore). You can give
it a try. Dub registry support is also on the way.

Regards
Dragos


[1] - https://github.com/dcarp/cmake-d


Re: Function implemented outside the class

2014-03-24 Thread Steven Schveighoffer
On Mon, 24 Mar 2014 16:02:25 -0400, MarisaLovesUsAll   
wrote:



On Monday, 24 March 2014 at 01:34:22 UTC, Matej Nanut wrote:

Hello!

You can implement static functions that act like members, like so:

---
void myFunc(MyClass c) { ... }
---

Which you will be able to call like:

---
auto c = new MyClass();
c.myFunc();
---

because of uniform function call syntax (UFCS).

But they won't be real methods (virtual member functions), which means  
they

can't be overridden.

Note that you can use the class's private members in such functions,
because private things in D are private to the file (module) instead of  
the

containing class or struct.

I don't think it's possible to do the same thing as in C++ though; but I
might be wrong.


2 all:
Thanks for replies!


Why would you like to do that?


I planned to use it to take event handling out from class (and put it in  
another file), but now I see that isn't a good idea.

class App
{
 void updateEvents(SDL_Event event) { ... }
}


By the way, it would be useful if it was written somewhere that  
implementation outside the class is impossible.


Implementation outside the class is not exactly possible, but it IS  
possible to separate declaration from implementation, see D interface  
(.di) files. You can't split an implementation into two files, however.


Note, there are serious drawbacks for using an interface file, most  
importantly eliminating the ability to inline. It should only be used,  
IMO, when you need to hide the implementation, as in a closed-source  
project.


-Steve


Re: Function implemented outside the class

2014-03-24 Thread MarisaLovesUsAll

On Monday, 24 March 2014 at 01:34:22 UTC, Matej Nanut wrote:

Hello!

You can implement static functions that act like members, like 
so:


---
void myFunc(MyClass c) { ... }
---

Which you will be able to call like:

---
auto c = new MyClass();
c.myFunc();
---

because of uniform function call syntax (UFCS).

But they won't be real methods (virtual member functions), 
which means they

can't be overridden.

Note that you can use the class's private members in such 
functions,
because private things in D are private to the file (module) 
instead of the

containing class or struct.

I don't think it's possible to do the same thing as in C++ 
though; but I

might be wrong.


2 all:
Thanks for replies!


Why would you like to do that?


I planned to use it to take event handling out from class (and 
put it in another file), but now I see that isn't a good idea.

class App
{
void updateEvents(SDL_Event event) { ... }
}


By the way, it would be useful if it was written somewhere that 
implementation outside the class is impossible.


Sorry for bad English.
Regards,
Alexey


Re: Socket: Detect connection close

2014-03-24 Thread nrgyzer
On Monday, 24 March 2014 at 05:32:30 UTC, Vladimir Panteleev 
wrote:

On Sunday, 23 March 2014 at 20:12:38 UTC, nrgyzer wrote:

Hi guys,

I'm experimenting with sockets and having trouble to detect 
when the remote side closes the connection. Here's my code:


// Client:
module client;

import std.socket;

void main()
{
TcpSocket s = new TcpSocket();
s.connect(new InternetAddress("localhost", 8080));
SocketStream ss = new SocketStream(s);

for (int i= 0; i < 10; i++)
{
ss.write(1);
ss.flush();
}
ss.socket.shutdown(SocketShutdown.BOTH);
ss.close();
}

// Server:
module server;

import std.sdio;
import std.socket;

void main()
{

TcpSocket s = new TcpSocket(AddressFamily.INET);
s.bind(new InternetAddress("localhost", 8080));
s.blocking(false);
s.listen(0);

while(1)
{
try {
Socket requestSocket = oSocket.accept();
RequestThread rt = new RequestThread(requestSocket);
rt.start();
}
catch (SocketAcceptException e)
{
Thread.yield();
}
}

s.socket.shutdown(SocketShutdown.BOTH);
s.close();

}

class RequestThread : Thread
{
private {
__gshared Socket s;

void run()
{
ubyte[1] buffer;
while(s.isAlive)
{
s.receive(buffer);
writeln("receiving");
}
writeln("client closed connection");
}

}

public this(Socket socket)
{
super(&run);
s = socket;
}
}

I know... dirty (really) dirty code, but it works , except 
that I'm in an endless loop and my server always prints 
"receiving". I never see "client closed connection" although 
the client sends only 10 int values. It seems that "s.isAlive" 
is always true. How can I detect when the client closes the 
connection (or how can I detect if the connection is broken)?


You can determine when the connection was closed on the remote 
side by checking if s.receive returns an empty array.


Alright, that world work. But what about sending 10 Bytes, 
waiting some minutes (probably some hours) and sending 10 Bytes 
again. Is it possible to do this on the same Socket?


My scenario is: I've one central server and multiple clients. The 
clients are connecting to the server and send (or request) some 
information. After that the clients are simply "sleeping" for an 
unknown time. For instance client 1 for 1 seconds, client 2 for 1 
minute, client 3 for 1 hours and client 4 for 1 day. After that 
time they resend/request some more information from the server... 
my questions regarding this are:


- When I client connects, the server creates a thread. How can I 
determine that I can terminate the thread because the connection 
is inactive (for instance because the client closed the 
connection or some connecting issues)?
- How can the client check if the connection is alive? (If the 
connection isn't alive, I need to reconnect)


Re: Is there a standard way to parse hex strings into numbers?

2014-03-24 Thread Gary Willoughby

On Monday, 24 March 2014 at 16:35:42 UTC, Brad Anderson wrote:

On Monday, 24 March 2014 at 16:30:37 UTC, Gary Willoughby wrote:

Is there a standard way to parse hex strings into numbers?

I have the following returned as a string:

   0xac036f90

Is there a standard way to parse this into a ulong or do you 
just roll your own?


To accepts a radix parameter. You need to strip off the 0x 
though.


"ac036f90".to!ulong(16) -> 18446744072300490640


Awesome ta.


Re: How to hand in a closure variable

2014-03-24 Thread Matej Nanut
Hello!

You just missed the syntax a little.

Instead of:

> int delegate(int) dg = { value => return value + a + 3; };

You can write

auto dg = (int value) { return value + a + 3; }; // Omitted return
type, but had to specify type of value.

or

auto dg = (int value) => value + a + 3; // Notice no "return" keyword.

or

int delegate(int) dg = value => value + a + 3; // Omitted type of
value, but had to write the full type of dg.

You can also write a delegate as an inner function:

int a = 7;
int dg(int value)
{
return value + a + 3;
}
auto result = dg(123);

I'm not sure, but I guess all of these should mean the same thing.


Re: How to hand in a closure variable

2014-03-24 Thread Dicebot

On Monday, 24 March 2014 at 16:40:55 UTC, Bienlein wrote:
Now I want the closure (aka delegate) to have a closure 
variable:


int a = 7;
int delegate(int) dg = { value => return value + a + 3; };
auto result = dg(123);

Unhappily, the code above doesn't compile. Tried various 
things, looked for samples on the D hompepage and in the book 
by Çehreli, but had no luck.


Some hints appreciated.
Thanks, Bienlein


auto dg = (int value) { return value + a + 3; };

or short-hand form:

auto dg = (int value) => value + a + 3;


How to hand in a closure variable

2014-03-24 Thread Bienlein

Hello,

I have some piece of code that compiles and runs fine:

void main(string[] args)
{   
int a = 7;
int delegate() dg = { return a + 3; };
auto result = dg();
writeln(result);
}

Now I want the closure (aka delegate) to have a closure variable:

int a = 7;
int delegate(int) dg = { value => return value + a + 3; };
auto result = dg(123);

Unhappily, the code above doesn't compile. Tried various things, 
looked for samples on the D hompepage and in the book by Çehreli, 
but had no luck.


Some hints appreciated.
Thanks, Bienlein


Re: Is there a standard way to parse hex strings into numbers?

2014-03-24 Thread Brad Anderson

On Monday, 24 March 2014 at 16:30:37 UTC, Gary Willoughby wrote:

Is there a standard way to parse hex strings into numbers?

I have the following returned as a string:

0xac036f90

Is there a standard way to parse this into a ulong or do you 
just roll your own?


To accepts a radix parameter. You need to strip off the 0x though.

"ac036f90".to!ulong(16) -> 18446744072300490640


Is there a standard way to parse hex strings into numbers?

2014-03-24 Thread Gary Willoughby

Is there a standard way to parse hex strings into numbers?

I have the following returned as a string:

0xac036f90

Is there a standard way to parse this into a ulong or do you just 
roll your own?


Re: Need help how to get started with D ranges

2014-03-24 Thread monarch_dodra

On Monday, 24 March 2014 at 14:12:58 UTC, Uranuz wrote:

Have you read this: http://ddili.org/ders/d.en/ranges.html ?


Yes I have read it. It's difficult to formulate the question in 
English bu I'l try. In this example I searching for special 
symbols '&' and '='. So when symbol found I use *save* method 
of range to remember start of *name* or *value* string of URL 
encoded param. Then I trying to find next special symbol. And 
when I found it I need to take a slice and insert in result AA. 
Should input range be RandomAccess for it? And if it's not 
random access range should should I append this substring by 
symbol to some temp variable and then (when delimiter found) 
insert into Associative Array. So result is that I will 
implement two different behaviours for InputRange and for 
RandomAccessRange. Am I right or not?


If you want to be able to *slice*, then you need an 
`RandomAccessRange` with `hasSlicing`.


a RandomAccessRange is a special kind of ForwardRange, which 
itself is an Input Range.


Re: Function to print a diamond shape

2014-03-24 Thread bearophile

On Thursday, 20 March 2014 at 21:25:03 UTC, Ali Çehreli wrote:

This is a somewhat common little exercise:


if you like similar puzzles, here is another:

Write a program that expects a 10-by-10 matrix from standard 
input. The program should compute sum of each row and each column 
and print the highest of these numbers to standard output.


An example input:

01 34 46 31 55 21 16 88 87 87
32 40 82 40 43 96 08 82 41 86
30 16 24 18 04 54 65 96 38 48
32 00 99 90 24 75 89 41 04 01
11 80 31 83 08 93 37 96 27 64
09 81 28 41 48 23 68 55 86 72
64 61 14 55 33 39 40 18 57 59
49 34 50 81 85 12 22 54 80 76
18 45 50 26 81 95 25 14 46 75
22 52 37 50 37 40 16 71 52 17

Expected output:

615

The purpose is to write a "golfing" program, that is the shortest.

My current D solution is about 170 bytes (UNIX newlines):

void main(){
import std.stdio,std.range,std.algorithm,std.conv;
auto m=10.iota.map!(_=>readln.split.to!(int[]));
m.map!sum.chain(m.transposed.map!sum).reduce!max.write;
}


I am now trying to use std.file.slurp, but its documentation is 
insufficient.


A cryptic Python solution (not mine), 73 characters:

m=[map(int,_().split())for _ in[raw_input]*10]
_(max(map(sum,m+zip(*m

Bye,
bearophile


Re: Need help how to get started with D ranges

2014-03-24 Thread Uranuz
I have another question. For example I have some range with input 
data (for example some array). I using method popFront() to 
iterate to next element. Then with property front I check element 
if it has some value. Then I *save* it. But how could I get 
position of this derived range in original range without 
overhead. As I see it is only possible via additional variable 
that will keep this position. In this case I can't understand 
what is the benefit of range over iterators or simply iterating 
using some integral index. I should admit that I haven't used 
iterators a lot in C++ so I don't know all of it's possibilities/ 
advantages. It's why I asking.


In my algorithms for parsing some strings I often save positions 
of beginings of some tokens in order to take a slice and put it 
into some buffer. But for opearting with them in terms of ranges 
I need to have RandomAccessRange, because (as far as I 
understand) only it have ability to take a slice. But with input 
I will need to operate (save parsed data) element-wise. And this 
will realocate and slow execution. What is preferable startegy 
opearating with ranges that will be flexible and productive?


Re: Need help how to get started with D ranges

2014-03-24 Thread Uranuz

Have you read this: http://ddili.org/ders/d.en/ranges.html ?


Yes I have read it. It's difficult to formulate the question in 
English bu I'l try. In this example I searching for special 
symbols '&' and '='. So when symbol found I use *save* method of 
range to remember start of *name* or *value* string of URL 
encoded param. Then I trying to find next special symbol. And 
when I found it I need to take a slice and insert in result AA. 
Should input range be RandomAccess for it? And if it's not random 
access range should should I append this substring by symbol to 
some temp variable and then (when delimiter found) insert into 
Associative Array. So result is that I will implement two 
different behaviours for InputRange and for RandomAccessRange. Am 
I right or not?




Re: How useful should inout be?

2014-03-24 Thread Steven Schveighoffer
On Sun, 23 Mar 2014 06:28:52 -0400, Infiltrator   
wrote:


So, following on from monarchdodra's comment [0] in the bug tracker, how  
exactly should inout work?  For example, should the following work?



import std.algorithm : map;

class L {
auto fun(const S s) inout nothrow pure @safe {
   if(point[0] is s)
  return point[1];
   else
  return point[0];
}
this(S a, S b) {
   point = [a, b];
}
S[2] point;
}

class S {
@property auto foo() inout nothrow pure @safe {
   return arr.map!(e => e.fun(this));
}
L[] arr;
}

void main() { }



Writing foo imperatively causes no problems with inout:

@property auto foo() inout nothrow pure @safe {
   inout(S)[] tmp;
   foreach(e; arr)
  tmp ~= e.fun(this);
   return tmp;
}



Of course, the functional style looks cleaner, neater, and more  
immediately obvious what is being done.


So, is this a limitation with inout, part of its design, or am I  
misunderstaning something more fundamental?


inout has issues when it comes to delegates. Note that inout has two modes  
of operation, one is as a type constructor, which is distinct from const  
and immutable, and has its own rules. The other is a link between the  
parameters and the return value to determine what the return value can  
bind to.


The issue is that as you nest delegates, the lines become blurred as to  
what inout actually means, and what it binds to. There can be several  
levels of inout, and all are accessible from the nested delegate function.  
The link between the parameters and the return value depends on the type  
constructor being consistent within the function. If we allow delegates to  
access inout variables outside the function, bad things can happen.


So it is a limitation, it wasn't exactly part of the design, and there  
have been ideas to fix it, but nothing has happened so far. Timon Gehr has  
a very good grasp of the issues and how they need to be fixed.


-Steve


Re: Function to print a diamond shape

2014-03-24 Thread Jay Norwood

Very nice example.   I'll test on ubuntu later.

On windows ...

D:\diamond\diamond\diamond\Release>diamond 1> nul
brad: time: 19544[ms]
printDiamond1: time: 1139[ms]
printDiamond2: time: 1656[ms]
printDiamond3: time: 663[ms]
jay1: time: 455[ms]
sergei: time: 11673[ms]
jay2: time: 411[ms]
diamondShape: time: 4399[ms]
printDiamond: time: 185[ms]


Re: Need help how to get started with D ranges

2014-03-24 Thread John Colvin

On Monday, 24 March 2014 at 12:13:43 UTC, Uranuz wrote:
I see that ranges is primitive to organzie universal approach 
to write some algorithms. But I'm using algorithms from the 
library but I still can't start with writing my own algorithms 
based on ranges. For example I have the following function 
written without ranges. I want to improve it and make it 
working with different types of strings (char[], string, 
wchar[], etc...). So could someone give me an example how to 
rewrite this function in `range`-style?


//Parses HTML form data
dstring[dstring] parseFormData2(dstring queryStr)
{   size_t LexStart = 0;
dstring curKey;
dstring curValue;
for( size_t i = 0; i < queryStr.length; ++i )
{   if( queryStr[i] == '=' )
{   curKey = queryStr[LexStart..i].idup;
curValue = null;
LexStart = i+1;
}
if( (queryStr[i] == '&') || (i+1 == queryStr.length) )
		{	curValue = queryStr[ LexStart .. (i+1 == queryStr.length) ? 
++i : i ].idup;

if( curKey.length > 0)
{   result[curKey] = curValue;
//result[curKey] ~= curValue;
}
curKey = null;
LexStart = i+1;
}
}
return result;
}


Have you read this: http://ddili.org/ders/d.en/ranges.html ?


Need help how to get started with D ranges

2014-03-24 Thread Uranuz
I see that ranges is primitive to organzie universal approach to 
write some algorithms. But I'm using algorithms from the library 
but I still can't start with writing my own algorithms based on 
ranges. For example I have the following function written without 
ranges. I want to improve it and make it working with different 
types of strings (char[], string, wchar[], etc...). So could 
someone give me an example how to rewrite this function in 
`range`-style?


//Parses HTML form data
dstring[dstring] parseFormData2(dstring queryStr)
{   size_t LexStart = 0;
dstring curKey;
dstring curValue;
for( size_t i = 0; i < queryStr.length; ++i )
{   if( queryStr[i] == '=' )
{   curKey = queryStr[LexStart..i].idup;
curValue = null;
LexStart = i+1;
}
if( (queryStr[i] == '&') || (i+1 == queryStr.length) )
		{	curValue = queryStr[ LexStart .. (i+1 == queryStr.length) ? 
++i : i ].idup;

if( curKey.length > 0)
{   result[curKey] = curValue;
//result[curKey] ~= curValue;
}
curKey = null;
LexStart = i+1;
}
}
return result;
}


Re: Function to print a diamond shape

2014-03-24 Thread monarch_dodra

On Sunday, 23 March 2014 at 18:28:18 UTC, Jay Norwood wrote:

On Sunday, 23 March 2014 at 17:30:20 UTC, bearophile wrote:



The task didn't ask for a computationally efficient solution 
:-) So you are measuring something that was not optimized for. 
So there's lot of variance.


Bye,
bearophile


Yes, this is just for my own education.   My builds are using 
the dmd compiler on windows, and some  posts indicate I should 
expect better optimization currently with the ldc compiler... 
so maybe I'll get on a linux box and retest with ldc.


So it's about speed now? Then I submit this:

//
void printDiamond(size_t N)
{
char[32] rawSpace = void;
char[64] rawStars = void;
char* pSpace = rawSpace.ptr;
char* pStars = rawStars.ptr;
if (N > 64)
{
pSpace = new char[](N/2).ptr;
pStars = new char[](N).ptr;
}
pSpace[0 .. N/2] = ' ';
pStars[0 ..   N] = '*';

N/=2;
foreach (n ; 0 .. N + 1)
writeln(pSpace[0 .. N - n], pStars[0 .. 2*n+1]);
foreach_reverse (n ; 0 .. N)
writeln(pSpace[0 .. N - n], pStars[0 .. 2*n+1]);
}
//


Re: GDC/LDC on Sparc Solaris

2014-03-24 Thread Nordlöw

On Sunday, 23 March 2014 at 22:00:23 UTC, andro wrote:

On Tuesday, 18 March 2014 at 23:52:49 UTC, Nordlöw wrote:

Does GDC and/or LDC have sparc solaris backend support?

I'm trying to make my company use D and we have a bunch of 
legacy machines that unfortunately run on sparc-solaris 2.10.


/Per


GCC has back end support for SPARC, it should not be a problem.


What about exception handling?

Isn't this the same struggle as with ARM support in GDC which
just got into beta?

/Per


Re: Template with template?

2014-03-24 Thread Chris

On Sunday, 23 March 2014 at 12:37:34 UTC, Marc Schütz wrote:

On Friday, 21 March 2014 at 09:56:49 UTC, Chris wrote:
Btw, I was initially inspired by Objective-C's NSSet that can 
hold arbitrary objects.


That's because Objective-C's objects are references. It would 
be equivalent to Adam Ruppe's suggestion of using 
classes/interfaces.


Yes, I will explore that too. Originally I thought I would have 
an array of references, but that was wrong of course.