Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

On Monday, 16 May 2016 at 22:54:31 UTC, ag0aep6g wrote:

On 05/17/2016 12:43 AM, Alex wrote:
The point is, that in my model the slice has a meaning itself. 
So, the

language provides one of a needed constructs...


Huh? As far as I understand, the pointer of the slice is 
invalid, and you never dereference it. What kind of additional 
meaning can the slice carry then? It's practically just a 
struct of two `size_t`s.


the elements of the slice are accessible just for reading, right, 
but with them I reference the data in other objects.




Re: D equivalent of C++ bind ?

2016-05-16 Thread chmike via Digitalmars-d-learn

On Monday, 16 May 2016 at 15:57:52 UTC, Dsby wrote:



you can remove "auto ref". and I remove the "auto ref" in my 
use.
if used the "alias T", It can not handle all while when the T 
is a delegate.


in C++ std::bind, the arguments order you can sort by used. in 
D I do not find how to enablement.


Yes this doesn't look easy. Maybe by using a mixin. Unfortunately 
this slows down compilation. I don't know the impact on 
optimization.


I'm not sure if converting a function to a delegate is a good 
thing. It is good for your use case where the bind functions are 
used as callbacks. But sometime, users may really want to create 
a function. The user should then use ToDelegate! If he wants to 
convert the function to a delegate. But from the the 
documentation, ToDelegate doesn't work with functions with the 
@safe attribute.


Does DUB create .dll files?

2016-05-16 Thread WhatMeWorry via Digitalmars-d-learn


I just incorporated DerelictALURE into a project and it compiled 
and linked fine, but when I ran the executable, it aborted with:


derelict.util.exception.SharedLibLoadException@N:\DUB_Packages\DerelictOrg\DerelictUtil\source\derelict\util\exception.d(35):
Failed to load one or more sharedlibraries:
ALURE32.dll - The specified module could not be found.

So I went back to DerelictOrg\derelict-alure-master\lib and I see 
a DerelictALURE.lib file that was created, but nothing else.


Am I supposed to get ALURE32.DLL from somewhere outside of DUB, 
or did I miss a step or command when I built 
derelict-alure-master?


thanks.




Re: Formatted Output: Exact number of Decimal Places

2016-05-16 Thread Ali Çehreli via Digitalmars-d-learn

On 05/16/2016 01:24 PM, Q. Schroll wrote:

Lets say I want to print a table with floats. How can it be formatted
like that:
|  2.4   |
| 12.2   |
|  8.131 |
| 17.44  |
Also acceptable is
|  2.400 |
| 12.200 |
|  8.131 |
| 17.440 |
but not
| 02.4   |
| 12.2   |
| 08.131 |
| 17.44  |
or any other solutions with leading zeros.


Also try "%.3g".

Ali



Re: Small-Size-Optimized Array

2016-05-16 Thread Vladimir Panteleev via Digitalmars-d-learn

On Monday, 16 May 2016 at 11:05:40 UTC, Nordlöw wrote:
Does Phobos contain any standard small-size-optimized (SSO) 
array that starts with a stack array and union-converts into a 
standard builtin D-array when grown beyond the size of the 
stack array?


Have a look at tempCString, but it's for internal use only at the 
moment.


Re: Formatted Output: Exact number of Decimal Places

2016-05-16 Thread Andrew Chamberlain via Digitalmars-d-learn

On Monday, 16 May 2016 at 20:24:51 UTC, Q. Schroll wrote:
Lets say I want to print a table with floats. How can it be 
formatted like that:

|  2.4   |
| 12.2   |
|  8.131 |
| 17.44  |
Also acceptable is
|  2.400 |
| 12.200 |
|  8.131 |
| 17.440 |
but not
| 02.4   |
| 12.2   |
| 08.131 |
| 17.44  |
or any other solutions with leading zeros.


I have this one:


import std.stdio;
import std.string, std.algorithm, std.format;

void main(string[] args)
{
[2.4, 12.2, 8.131, 17.44].each!(a => format("%.3f", a)
.rightJustify(6).center(8).center(10,'|').writeln);
}


But only works if fractional and integral part are both up to 3 
digits.


Re: Formatted Output: Exact number of Decimal Places

2016-05-16 Thread Marco Leise via Digitalmars-d-learn
Am Mon, 16 May 2016 20:24:51 +
schrieb Q. Schroll :

> Lets say I want to print a table with floats. How can it be 
> formatted like that:
> |  2.4   |
> | 12.2   |
> |  8.131 |
> | 17.44  |
> Also acceptable is
> |  2.400 |
> | 12.200 |
> |  8.131 |
> | 17.440 |

Use %#6.3f to get the above output.

> but not
> | 02.4   |
> | 12.2   |
> | 08.131 |
> | 17.44  |
> or any other solutions with leading zeros.

-- 
Marco



Re: Small-Size-Optimized Array

2016-05-16 Thread Jack Stouffer via Digitalmars-d-learn

On Monday, 16 May 2016 at 11:05:40 UTC, Nordlöw wrote:
Does Phobos contain any standard small-size-optimized (SSO) 
array that starts with a stack array and union-converts into a 
standard builtin D-array when grown beyond the size of the 
stack array?


No.


If not has anybody put together one?


Not that I know of. Grapheme has small string optimized code in 
it though.


Re: Void pointers

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/17/2016 12:53 AM, Alex wrote:

Just as the reality (in my head) is: you can count something without
having written the natural numbers before you start to count...


iota does that, too. A iota struct doesn't store all the numbers it will 
emit. Just like a slice, a iota struct stores two numbers: the first and 
the amount of numbers. Iterating over it means counting, not reading 
pre-generated numbers from a list.



Especially, I don't have to create some strange structs containing just
a number, as I expect to have some millions of them.


Some million slices will take just as much space as some million iota 
structs. Storing a slice isn't free. If you create the slices on the 
fly, you can do that with iota too. No need to store them beforehand.


Re: Void pointers

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/17/2016 12:43 AM, Alex wrote:

The point is, that in my model the slice has a meaning itself. So, the
language provides one of a needed constructs...


Huh? As far as I understand, the pointer of the slice is invalid, and 
you never dereference it. What kind of additional meaning can the slice 
carry then? It's practically just a struct of two `size_t`s.


Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

On Monday, 16 May 2016 at 22:30:38 UTC, ag0aep6g wrote:

On 05/16/2016 11:33 PM, Alex wrote:
Well... not wanting to have a variable, which stores numbers, 
which are

natural numbers, beginning with zero, used for counting only.


But you have such a variable: b. I may still be missing the 
point.


Yeah, the b variable is contained in the E objects and is 
unavoidable, as the E object has to save the region he is at and 
some number has to be reported by the E object to the describing 
objects in case of an action.
The point is, that the slice of numbers, contained in the E 
object is done from nothing. Well, from a void pointer. So, I get 
ordinal numbers from void and not from a list.
Just as the reality (in my head) is: you can count something 
without having written the natural numbers before you start to 
count... Especially, I don't have to create some strange structs 
containing just a number, as I expect to have some millions of 
them.


Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

On Monday, 16 May 2016 at 22:28:04 UTC, ag0aep6g wrote:


I can't say that I understand the setup you describe. But are 
you sure that iota has a higher cost than (ab)using a slice?


I mean, they're pretty much exactly the same: an offset, a 
length, and an increment operation. If inlining doesn't fail, 
they should perform the same, no?


Maybe. I should test this...


And if iota does perform worse for some reason, I feel like 
there must be a way to implement something that matches the 
speed of the slice without inheriting its ugliness.


:)
The point is, that in my model the slice has a meaning itself. 
So, the language provides one of a needed constructs...




Re: Void pointers

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/16/2016 11:33 PM, Alex wrote:

Well... not wanting to have a variable, which stores numbers, which are
natural numbers, beginning with zero, used for counting only.


But you have such a variable: b. I may still be missing the point.


Re: Void pointers

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/16/2016 11:35 PM, Alex wrote:

Background:
Say, I have objects of kind E, which operate on structs of kind M. The
problem: if an action is done on a struct, say M42, there should be also
some action done on other structs, which have some relation to M42, but
neither the operating object, nor M42 is aware of them (and the action
which is required), as this would break encapsulation.
So, I choosed another approach:
There are some describing objects, say of kind B and G, which hold a
specific information (a single property) of all existent M structs.
These objects know which "neighbors" are also affected in case of some
action of E on the struct M42 and can perform appropriate actions on
them, at least on the contained property.
The problem which is still unsolved:
objects of kind E operates on structs M randomly. For this goal, they
have to save the information between their actions, on which structs
they are interested in, to report the ordinal number to the describing
objects.
The saving of ordinal numbers with minimum computational costs (nogc,
even no construction of iota-structs, etc) is crucial.


I can't say that I understand the setup you describe. But are you sure 
that iota has a higher cost than (ab)using a slice?


I mean, they're pretty much exactly the same: an offset, a length, and 
an increment operation. If inlining doesn't fail, they should perform 
the same, no?


And if iota does perform worse for some reason, I feel like there must 
be a way to implement something that matches the speed of the slice 
without inheriting its ugliness.


Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn
On Monday, 16 May 2016 at 21:41:20 UTC, Steven Schveighoffer 
wrote:




Hey, there's nothing wrong with for-loops. Just trying to 
answer the question :)


You could also do something like:

foreach(i; 0 .. b.length) writeln(&b[i]);


Ha! Yes! :)
Thanks :)


-Steve





Re: Void pointers

2016-05-16 Thread Steven Schveighoffer via Digitalmars-d-learn

On 5/16/16 5:38 PM, Alex wrote:

On Monday, 16 May 2016 at 21:15:16 UTC, Steven Schveighoffer wrote:

On 5/16/16 4:39 PM, Alex wrote:

 // something that does not worked as expected:
 // how to rewrite a for loop
 for(auto i = 0; i < b.length; i++) writeln(&b[i]);
 // into a foreach loop?



What you need is a range that produces void * instead element itself.

This would probably work:

struct VoidRange
{
   void[] arr;
   auto front() { return arr.ptr; }
   void popFront() { arr.popFront; }
   bool empty() { return arr.empty; }
}

foreach(p; VoidRange(b)) writeln(p);

-Steve


Yes... I could do this... but then, I would construct millions of
structs to hold just ordinal numbers... Using a iota would also be a
possibility... but I want something even less perceptible...


Hey, there's nothing wrong with for-loops. Just trying to answer the 
question :)


You could also do something like:

foreach(i; 0 .. b.length) writeln(&b[i]);

-Steve


Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn
On Monday, 16 May 2016 at 21:15:16 UTC, Steven Schveighoffer 
wrote:

On 5/16/16 4:39 PM, Alex wrote:

 // something that does not worked as expected:
 // how to rewrite a for loop
 for(auto i = 0; i < b.length; i++) writeln(&b[i]);
 // into a foreach loop?



What you need is a range that produces void * instead element 
itself.


This would probably work:

struct VoidRange
{
   void[] arr;
   auto front() { return arr.ptr; }
   void popFront() { arr.popFront; }
   bool empty() { return arr.empty; }
}

foreach(p; VoidRange(b)) writeln(p);

-Steve


Yes... I could do this... but then, I would construct millions of 
structs to hold just ordinal numbers... Using a iota would also 
be a possibility... but I want something even less perceptible...


Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

Background:
Say, I have objects of kind E, which operate on structs of kind 
M. The problem: if an action is done on a struct, say M42, there 
should be also some action done on other structs, which have some 
relation to M42, but neither the operating object, nor M42 is 
aware of them (and the action which is required), as this would 
break encapsulation.

So, I choosed another approach:
There are some describing objects, say of kind B and G, which 
hold a specific information (a single property) of all existent M 
structs. These objects know which "neighbors" are also affected 
in case of some action of E on the struct M42 and can perform 
appropriate actions on them, at least on the contained property.

The problem which is still unsolved:
objects of kind E operates on structs M randomly. For this goal, 
they have to save the information between their actions, on which 
structs they are interested in, to report the ordinal number to 
the describing objects.
The saving of ordinal numbers with minimum computational costs 
(nogc, even no construction of iota-structs, etc) is crucial.




Re: Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

On Monday, 16 May 2016 at 21:04:32 UTC, ag0aep6g wrote:


Typo here. Should be `ptr[a .. b]`.

Thanks



void main()
{
 void* ptr; // this will stay uninitialized during the 
whole program

run


The pointer is being initialized, though. To null, which is why 
your shenanigans below work reliably.


Ok, this is a cool hint, especially about the reliability. Thanks!




 // something that works as desired:
 writeln(&ptr[4]); // prints '4'
 auto b = getSlice(ptr, 5, 10);
 writeln("b first: ", &b[0]); // prints '5'. This is the 
most useful

feature.
 assert(b.capacity == 0); // holds always. So, getSlice 
returns

always a slice, not an array.
 // arr[3] = ... // fails. It is intended to do so.

 // something that does not worked as expected:
 // how to rewrite a for loop
 for(auto i = 0; i < b.length; i++) writeln(&b[i]);
 // into a foreach loop?


Not, I guess, since you can't have a void variable, not even if 
it's marked `ref`.


Yes, this is something what I was surprised about, but, seems 
logical on the other hand... So, I get a slice, which is not 
foreachable, but still able to be iterated over...


I have to say that I don't see the point in all this. You can't 
access the elements of b in any way, since they're in memory 
that you don't own. So all you got here is a fancy way of 
counting, no?


Yes! This is important and this is the place, where I have to 
provide background. (Following post)




Not sure what you mean here. What's the described manner? Not 
being able to have a variable of the type?


Well... not wanting to have a variable, which stores numbers, 
which are natural numbers, beginning with zero, used for counting 
only.




I think void is the only type with that property. So maybe 
checking if the type is exactly void is enough: `is(T == void)`.


OK...

Or you can check if some operation works on the type or a value 
of it: `__traits(compiles, writeln(T.init))`







Re: Void pointers

2016-05-16 Thread Steven Schveighoffer via Digitalmars-d-learn

On 5/16/16 4:39 PM, Alex wrote:

 // something that does not worked as expected:
 // how to rewrite a for loop
 for(auto i = 0; i < b.length; i++) writeln(&b[i]);
 // into a foreach loop?



What you need is a range that produces void * instead element itself.

This would probably work:

struct VoidRange
{
   void[] arr;
   auto front() { return arr.ptr; }
   void popFront() { arr.popFront; }
   bool empty() { return arr.empty; }
}

foreach(p; VoidRange(b)) writeln(p);

-Steve


Re: Void pointers

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/16/2016 10:39 PM, Alex wrote:

// This function is intentionally templated, as it should take slices
and return something
// boundchecked only
@nogc T[] getSlice(T)(T* ptr, size_t a, size_t b)
{
 return T[a .. b];


Typo here. Should be `ptr[a .. b]`.


}

void main()
{
 void* ptr; // this will stay uninitialized during the whole program
run


The pointer is being initialized, though. To null, which is why your 
shenanigans below work reliably.



 // something that works as desired:
 writeln(&ptr[4]); // prints '4'
 auto b = getSlice(ptr, 5, 10);
 writeln("b first: ", &b[0]); // prints '5'. This is the most useful
feature.
 assert(b.capacity == 0); // holds always. So, getSlice returns
always a slice, not an array.
 // arr[3] = ... // fails. It is intended to do so.

 // something that does not worked as expected:
 // how to rewrite a for loop
 for(auto i = 0; i < b.length; i++) writeln(&b[i]);
 // into a foreach loop?


Not, I guess, since you can't have a void variable, not even if it's 
marked `ref`.


I have to say that I don't see the point in all this. You can't access 
the elements of b in any way, since they're in memory that you don't 
own. So all you got here is a fancy way of counting, no?


Looping over a range of numbers:

foreach (i; 5 .. 10) writeln(i);


Or if you want to store it in a variable:

import std.range: iota;
auto b = iota(5, 10);
foreach (i; b) writeln(i);



 // a question about usability: is there a trait, which can
semantically check, if a type
 // (void, or something else) behaves in the described manner?


Not sure what you mean here. What's the described manner? Not being able 
to have a variable of the type?


I think void is the only type with that property. So maybe checking if 
the type is exactly void is enough: `is(T == void)`.


Or you can check if some operation works on the type or a value of it: 
`__traits(compiles, writeln(T.init))`



}




Re: `return ref`, DIP25, and struct/class lifetimes

2016-05-16 Thread Dicebot via Digitalmars-d-learn
There is also another counter-obvious bit regarding current 
implementation - it only tracks lifetime of actual references. 
Check this example:


ref int wrap ( return ref int input )
{
return input;
}

int badWrapper()
{
int z;
{
int x = 42;
z = wrap(x);
}
return z;
}


it looks obvious that this compiles OK with dip25 check because 
once value assignment happens, there is no more reference to 
track. However it is very common to expect different semantics if 
return type contains reference types - probably because it would 
be very useful and because Rust has changed expectations of what 
lifetime control can do :) And yet it will still work exactly the 
same with no warnings from compiler, creating false sense of 
correctness.


Void pointers

2016-05-16 Thread Alex via Digitalmars-d-learn

Hi all!
Let's talk about void pointers a little bit. Found this already
http://forum.dlang.org/thread/codoixfeqstvqswir...@forum.dlang.org?page=1
but my question/problem differs from the above, so maybe, I have 
found a useful application  for void pointers...


Form of the posting: I have some questions about the usage of 
void pointers in some expressions, but I'm not even sure, if void 
pointers should be used. For the latter part, I found at least 
two other possibilities, which goes further below.


Say I have something like that:

// This function is intentionally templated, as it should take 
slices and return something

// boundchecked only
@nogc T[] getSlice(T)(T* ptr, size_t a, size_t b)
{
return T[a .. b];
}

void main()
{
void* ptr; // this will stay uninitialized during the whole 
program run


// something that works as desired:
writeln(&ptr[4]); // prints '4'
auto b = getSlice(ptr, 5, 10);
writeln("b first: ", &b[0]); // prints '5'. This is the most 
useful feature.
assert(b.capacity == 0); // holds always. So, getSlice 
returns always a slice, not an array.

// arr[3] = ... // fails. It is intended to do so.

// something that does not worked as expected:
// how to rewrite a for loop
for(auto i = 0; i < b.length; i++) writeln(&b[i]);
// into a foreach loop?

// a question about usability: is there a trait, which can 
semantically check, if a type

// (void, or something else) behaves in the described manner?
}

Something, which also could be used to achieve the same behavior:
using ubyte* instead of void*
using something like this:
struct M
{
@disable this();
@disable this(this);
}

The important thing, as I found out is: the underlying type has 
to be only as large as a byte.


Background:
is already written and could be provided :)

Thanks in advance :)


Formatted Output: Exact number of Decimal Places

2016-05-16 Thread Q. Schroll via Digitalmars-d-learn
Lets say I want to print a table with floats. How can it be 
formatted like that:

|  2.4   |
| 12.2   |
|  8.131 |
| 17.44  |
Also acceptable is
|  2.400 |
| 12.200 |
|  8.131 |
| 17.440 |
but not
| 02.4   |
| 12.2   |
| 08.131 |
| 17.44  |
or any other solutions with leading zeros.


Re: Async or event library

2016-05-16 Thread chmike via Digitalmars-d-learn

On Thursday, 12 May 2016 at 14:02:30 UTC, Dsby wrote:


https://github.com/putao-dev/collie


Thank you very much for this library I wasn't aware of.

I see it's using the Reactor pattern (select/kevent/epoll of 
Posix) by opposition to the Proactor pattern (IOCP on Windows)  
[D. Schmidt et al, Pattern Oriented Software Architecture, Volume 
2. Wiley, 2000].


In the Proactor pattern you pass a function and its parameters 
(e.g. buffer) to be executed asynchronously. In the Reactor 
pattern the user is notified when there is data to read.


The Reactor pattern is superior in many ways to the Proactor 
pattern (IOCP):


- There is no need to preallocate a buffer for all input channels 
that can stay idle for a long time. This doesn't scale well to 
million connections.


- There is no risk to pass a parameter (e.g. array) on the stack 
or destroyed before the function execution.


- It is possible to read into (or write data from) a transient 
storage on the stack (e.g. array or a struct) and benefit from 
RAII and less GC load.


Unfortunately Windows only provide the slow select() operation. 
User are advised to use the faster IOCP which I guess is there 
mainly for historical reasons.


So the first question to ask when designing an async IO system is 
if we go for a Reactor system or a Proactor system.


Nearly all async IO system (except libev) adopted the Proactor 
pattern to be compatible with Windows and its IOCP.


My feeling is that if we want to provide a simple, robust and 
scalable API, the Reactor pattern should be favored.






Re: Request assistance converting C's #ifndef to D

2016-05-16 Thread Joseph Rushton Wakeling via Digitalmars-d-learn

On Thursday, 12 May 2016 at 22:51:17 UTC, Andrew Edwards wrote:
The following preprocessor directives are frequently 
encountered in C code, providing a default constant value where 
the user of the code has not specified one:


#ifndef MIN
#define MIN 99
#endif

#ifndef MAX
#define MAX 999
#endif


One option here is that the programmer is trying to avoid 
multiple definitions of MIN and MAX if for some reason this 
header is included together with another header that also defines 
a MIN and MAX.


So, you might start by checking if any other header/source file 
does so.  It's entirely possible the programmer is just going 
overkill with the kind of stuff one does to guard against 
multiple #include's of the same header, and that this header is 
the _only_ place where MIN and MAX are defined, and that it's 
ALWAYS valid for them to be 99 and 999 respectively.


The other thought is that the programmer might have in mind to be 
able to choose alternative MIN and MAX at compile time via 
environment variables (perhaps the project's build scripts make 
use of this?).  If you think so, is that something you want to 
support?  There are probably better ways of achieving the same 
result.


I suspect it'll probably turn out to be fine to just use

enum MIN = 99;
enum MAX = 999;

... but H. S. Teoh's suggestion looks sane as a more cautious 
alternative.


Re: `return ref`, DIP25, and struct/class lifetimes

2016-05-16 Thread Joseph Rushton Wakeling via Digitalmars-d-learn

On Monday, 16 May 2016 at 15:33:09 UTC, Dicebot wrote:
tl; dr: DIP25 is so heavily under-implemented in its current 
shape it can be considered 100% broken and experimenting will 
uncover even more glaring holes.


Well, it's always fun to find the holes in things ... :-)

To be more precise, judging by experimental observation, 
currently dip25 only works when there is explicitly a `ref` 
return value in function or method. Any escaping of reference 
into a pointer confuses it completely:


To be fair, this is all in line with the DIP25 spec that I 
re-read after running into these issues with my wrapper struct.  
AFAICS pretty much the only case where it really relates to 
structs is when a struct method is returning a reference to an 
internal variable.


It's just frustrating there _isn't_ any thought for the kind of 
wrapper I have in mind, because as you say,


But there isn't any way to write such wrapper struct without 
using pointers AFAIK.


As for your point:

In your actual example putting `return` on `get` method 
annotation is additionally very misleading because it only 
implies ensuring result does not outlive struct instance itself 
- but it gets passed around by value anyway.


I thought much the same, but thought I'd try it on the off chance 
it would make a difference to detection of the problem.


Worst part of all this is that even an invariant to 
assert(this.data !is null) won't protect against issues: the 
pointer doesn't get reset to 0 after the data it points to goes 
out of scope, it just now points to potentially garbage data.


In fact, it's only with compiler optimizations enabled that the 
example I posted even generates the wrong result in its 
`writeln()` call :-P


Basically, it sounds to me like there _is_ no way to guarantee 
the safety/validity of wrapping data via pointer in this way ... 
? :-(


Re: D equivalent of C++ bind ?

2016-05-16 Thread Dsby via Digitalmars-d-learn

On Monday, 16 May 2016 at 15:11:26 UTC, chmike wrote:

On Thursday, 12 May 2016 at 10:38:37 UTC, Dsby wrote:


[...]


Thank you. Would you agree to help me understand it ?

The only thing I don't understand is why the function template 
argument is defined as T and the argument as auto ref T fun. 
Why the auto ref  and not alias T in the template argument list 
?


This bind is better than Partial!() from std.functional since 
it accepts any number of parameters. But the given parameters 
are passed as first arguments of fun. The std::bind of C++ 
allows to bind any parameter in any order and eventually 
multiple times. It's really as if a new function was defined 
with a total liberty degree on its signature.


Anyway thank you very much.


you can remove "auto ref". and I remove the "auto ref" in my use.
if used the "alias T", It can not handle all while when the T is 
a delegate.


in C++ std::bind, the arguments order you can sort by used. in D 
I do not find how to enablement.




Re: `return ref`, DIP25, and struct/class lifetimes

2016-05-16 Thread Dicebot via Digitalmars-d-learn
tl; dr: DIP25 is so heavily under-implemented in its current 
shape it can be considered 100% broken and experimenting will 
uncover even more glaring holes.


To be more precise, judging by experimental observation, 
currently dip25 only works when there is explicitly a `ref` 
return value in function or method. Any escaping of reference 
into a pointer confuses it completely:


ref int wrap ( return ref int input )
{
return input;
}

ref int badWrapper()
{
int x = 5;
return wrap(x); // Error: escaping reference to local 
variable x

}

void main()
{
auto badWrap = badWrapper();
}

vs

struct S
{
int* ptr;
}

S wrap ( return ref int input )
{
return S(&input);
}

S badWrapper()
{
int x = 5;
return wrap(x); // OK!
}

void main()
{
auto badWrap = badWrapper();
}

vs

struct S
{
int* ptr;
}

ref S wrap ( return ref int input )
{
static S tmp; // spot another hole :)
tmp = S(&input);
return tmp;
}

ref S badWrapper()
{
int x = 5;
return wrap(x); // Error: escaping reference to local 
variable x

}

void main()
{
auto badWrap = badWrapper();
}

You can probably spot the pattern here - compiler matches `return 
ref` in parameter declaration to `ref` in return value and 
enforces identical lifetime for those. No `ref` in return value - 
no enforcing, but it will also happily accept nonsense `return 
ref` annotations.


Theoretically it was supposed to be protected by `@safe` 
attribute as one can't take address of local variable in safe 
code. But there isn't any way to write such wrapper struct 
without using pointers AFAIK.


In your actual example putting `return` on `get` method 
annotation is additionally very misleading because it only 
implies ensuring result does not outlive struct instance itself - 
but it gets passed around by value anyway.


Re: D equivalent of C++ bind ?

2016-05-16 Thread chmike via Digitalmars-d-learn

On Thursday, 12 May 2016 at 10:38:37 UTC, Dsby wrote:


I write one, bind functon to a delegate.

In here:
https://github.com/putao-dev/collie/blob/master/source/collie/utils/functional.d


this is the code:

auto  bind(T,Args...)(auto ref T fun,Args args) if 
(isCallable!(T))

{
alias FUNTYPE = Parameters!(fun);
static if(is(Args == void))
{
static if(isDelegate!T)
return fun;
else
return toDelegate(fun);
}
else static if(FUNTYPE.length > args.length)
{
alias DTYPE = FUNTYPE[args.length..$];
return
delegate(DTYPE ars){
TypeTuple!(FUNTYPE) value;
value[0..args.length] = args[];
value[args.length..$] = ars[];
return fun(value);
};
}
else
{
return delegate(){return fun(args);};
}
}


Thank you. Would you agree to help me understand it ?

The only thing I don't understand is why the function template 
argument is defined as T and the argument as auto ref T fun. Why 
the auto ref  and not alias T in the template argument list ?


This bind is better than Partial!() from std.functional since it 
accepts any number of parameters. But the given parameters are 
passed as first arguments of fun. The std::bind of C++ allows to 
bind any parameter in any order and eventually multiple times. 
It's really as if a new function was defined with a total liberty 
degree on its signature.


Anyway thank you very much.


`return ref`, DIP25, and struct/class lifetimes

2016-05-16 Thread Joseph Rushton Wakeling via Digitalmars-d-learn

Hello all,

Consider a struct that wraps a pointer to some other piece of 
data as follows:


struct MyWrapper(T)
{
private T* data;

public this(ref T input)
{
this.data = &input;
}

... other methods that use `this.data` ...
}

Is there any way to guarantee at compile time that the input data 
will outlive the wrapper struct?


I'd assumed (dangerous thing to do...) that DIP25 would allow 
this to be guaranteed by `return ref`, but compiling/running the 
following program, with or without the --dip25 flag, would appear 
to suggest otherwise:




struct MyWrapper(T)
{
private T* data;

public this(return ref T input)
{
this.data = &input;
}

public T get() return
{
return *(this.data);
}

invariant()
{
assert(this.data !is null);
}
}

auto badWrapper()
{
double x = 5.0;
return MyWrapper!double(x);
}

void main()
{
import std.stdio;
auto badWrap = badWrapper();
writeln(badWrap.get());
}



Is there any current way to achieve what I'm looking for here, or 
is this all on a hiding to nothing? :-(


N.B. for motivation behind this request, see:
https://github.com/WebDrake/dxorshift/pull/1


Re: source/protocols.d(40, 34): Error: uninitialized variable 'value' cannot be returned from CTFE

2016-05-16 Thread Stefan via Digitalmars-d-learn

On Monday, 16 May 2016 at 11:13:52 UTC, ag0aep6g wrote:

On 05/16/2016 11:24 AM, Stefan wrote:
source/protocols.d(40,34): Error: uninitialized variable 
'value' cannot

be returned from CTFE


Ouch. That's not a good error message. There is no `value` on 
that line.


I've filed an issue: 
https://issues.dlang.org/show_bug.cgi?id=16030




thank you


Protocol[] Protocols;

static this()
{
Protocols = [
Protocol(P_IP4, 32, "ip4", CodeToVarint(P_IP4)),
Protocol(P_TCP, 16, "tcp", CodeToVarint(P_TCP)),
Protocol(P_UDP, 16, "udp", CodeToVarint(P_UDP)),
Protocol(P_DCCP, 16, "dccp", CodeToVarint(P_DCCP)),
Protocol(P_IP6, 128, "ip6", CodeToVarint(P_IP6)),
// these require varint:
Protocol(P_SCTP, 16, "sctp", CodeToVarint(P_SCTP)),
Protocol(P_ONION, 80, "onion", CodeToVarint(P_ONION)),
Protocol(P_UTP, 0, "utp", CodeToVarint(P_UTP)),
Protocol(P_UDT, 0, "udt", CodeToVarint(P_UDT)),
Protocol(P_HTTP, 0, "http", CodeToVarint(P_HTTP)),
Protocol(P_HTTPS, 0, "https", CodeToVarint(P_HTTPS)),
Protocol(P_IPFS, LengthPrefixedVarSize, "ipfs", 
CodeToVarint(P_IPFS)),

];
}




forgot about "static this", works like a charm



Re: source/protocols.d(40, 34): Error: uninitialized variable 'value' cannot be returned from CTFE

2016-05-16 Thread ag0aep6g via Digitalmars-d-learn

On 05/16/2016 11:24 AM, Stefan wrote:

source/protocols.d(40,34): Error: uninitialized variable 'value' cannot
be returned from CTFE


Ouch. That's not a good error message. There is no `value` on that line.

I've filed an issue: https://issues.dlang.org/show_bug.cgi?id=16030



this ist the code in question
https://gist.github.com/erde74/5bd7d91070791142c929258fee8d887b

the go source
https://github.com/jbenet/go-multiaddr/blob/master/protocols.go

i am a bit lost currently and don't know how to fix the error messages.
A hint how to fix this would be create.


The problem seems to be that nativeToLittleEndian cannot be evaluted at 
compile time. You can fill `protocols` at run time instead, using a 
static constructor:



Protocol[] Protocols;

static this()
{
Protocols = [
Protocol(P_IP4, 32, "ip4", CodeToVarint(P_IP4)),
Protocol(P_TCP, 16, "tcp", CodeToVarint(P_TCP)),
Protocol(P_UDP, 16, "udp", CodeToVarint(P_UDP)),
Protocol(P_DCCP, 16, "dccp", CodeToVarint(P_DCCP)),
Protocol(P_IP6, 128, "ip6", CodeToVarint(P_IP6)),
// these require varint:
Protocol(P_SCTP, 16, "sctp", CodeToVarint(P_SCTP)),
Protocol(P_ONION, 80, "onion", CodeToVarint(P_ONION)),
Protocol(P_UTP, 0, "utp", CodeToVarint(P_UTP)),
Protocol(P_UDT, 0, "udt", CodeToVarint(P_UDT)),
Protocol(P_HTTP, 0, "http", CodeToVarint(P_HTTP)),
Protocol(P_HTTPS, 0, "https", CodeToVarint(P_HTTPS)),
Protocol(P_IPFS, LengthPrefixedVarSize, "ipfs", 
CodeToVarint(P_IPFS)),

];
}


Also note the different syntax for struct values: `Protocol(...)`, not 
`{...}`.


By the way, by convention `Protocols` would be called `protocols` in D. 
A capitalized name indicates a type.



i am thinking about to wrap all the funtions into a class, does this
make sense?


Not as far as I can tell.



Small-Size-Optimized Array

2016-05-16 Thread Nordlöw via Digitalmars-d-learn
Does Phobos contain any standard small-size-optimized (SSO) array 
that starts with a stack array and union-converts into a standard 
builtin D-array when grown beyond the size of the stack array?


If not has anybody put together one?


source/protocols.d(40,34): Error: uninitialized variable 'value' cannot be returned from CTFE

2016-05-16 Thread Stefan via Digitalmars-d-learn

Hello, i try to port some go code to D
i get this error messages from my current code.

source/protocols.d(40,34): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(41,34): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(42,34): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(43,36): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(44,35): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(46,36): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(47,38): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(48,33): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(49,33): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(50,35): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(51,37): Error: uninitialized variable 'value' 
cannot be returned from CTFE
source/protocols.d(52,55): Error: uninitialized variable 'value' 
cannot be returned from CTFE


this ist the code in question
https://gist.github.com/erde74/5bd7d91070791142c929258fee8d887b

the go source 
https://github.com/jbenet/go-multiaddr/blob/master/protocols.go


i am a bit lost currently and don't know how to fix the error 
messages. A hint how to fix this would be create.


i am thinking about to wrap all the funtions into a class, does 
this make sense?