Re: Overriding opEquals in classes, for comparison with things that aren't Objects

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Friday, 29 January 2016 at 15:00:59 UTC, pineapple wrote:
With this bit of code, the first method seems to work fine - 
things go as expected. But I get a compile error with the 
second method, and I'm not sure how else to write this.


override bool opEquals(Object value) const{
return this.equals(cast(typeof(this)) value);
}
override bool opEquals(T)(T value) const if(isNumeric!(T)){
return this.equals(value);
}

The compile errors I get look like this:

C:\path\to\file.d(477): Error: function 
units.quantity.opEquals!int.opEquals cannot override a 
non-virtual function
C:\path\to\file.d(519): Error: template instance 
units.quantity.opEquals!int error instantiating


How can I revise this so that I can override comparison 
operators for things other than class instances?


The first implementation is fine because you're overriding the 
implementation in the base class (Object). However, the second 
one fails because it's a template. Templates are non-virtual and 
cannot override anything. Even if you could, there is no such 
implementation in Object and, therefore, nothing to override.


Templated functions can be used as overloads, though, but I'm not 
sure off the top of my head if the compiler accepts templated 
opEquals on classes at all. My guess is no, but you can find out 
by removing the override from the template declaration. If not, 
you should be able to implement non-templated overloads for the 
types you're interested in (without the override keyword, mind 
you, since they won't be overriding anything).




Re: Why is it a memory ERRO.

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Friday, 29 January 2016 at 13:22:07 UTC, Mike Parker wrote:

Your problem is probably that you are calling GC.free in the 
destructor. Don't do this. You don't need to call GC.free at 
all. The GC will collect both your object instance and the 
memory you allocated with new. Never, ever, manipulate GC 
memory in the destructor of a GC-managed object.


Here's a modified version of your program. Every time it prints, 
you know the garbage collector has just run a collection cycle. 
Every class instance and every 'by' that is allocated will 
eventually be free. Not all destructors are guaranteed to run 
during the program's lifetime, though. Some will be run after 
main exits and the GC shuts down.


import core.thread;
import std.stdio;

class MyClass
 {
   this(){
   by = new ubyte[1];
   id = i;
   ++i;
   }
   ~this() {
   writeln("freed #", id);
   }
 private:
   ubyte[]   by;
   int id;
   static int i;
 };

void main()
{
while(true) {
   auto obj = new MyClass;
   Thread.sleep(5.msecs);
   if(MyClass.i == 2000)
break;
}
}


Overriding opEquals in classes, for comparison with things that aren't Objects

2016-01-29 Thread pineapple via Digitalmars-d-learn
With this bit of code, the first method seems to work fine - 
things go as expected. But I get a compile error with the second 
method, and I'm not sure how else to write this.


override bool opEquals(Object value) const{
return this.equals(cast(typeof(this)) value);
}
override bool opEquals(T)(T value) const if(isNumeric!(T)){
return this.equals(value);
}

The compile errors I get look like this:

C:\path\to\file.d(477): Error: function 
units.quantity.opEquals!int.opEquals cannot override a 
non-virtual function
C:\path\to\file.d(519): Error: template instance 
units.quantity.opEquals!int error instantiating


How can I revise this so that I can override comparison operators 
for things other than class instances?




Re: Overriding opEquals in classes, for comparison with things that aren't Objects

2016-01-29 Thread pineapple via Digitalmars-d-learn
It also occurred to me to do something like this, but it isn't 
accepted either.


override bool opEquals(T)(T value){
return this.equals(value);
}



Re: Why is it a memory ERRO.

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Friday, 29 January 2016 at 12:43:53 UTC, Dsby wrote:

the Code:



~this(){
GC.free(by.ptr);
by = null;
writeln("free");
}


Your problem is probably that you are calling GC.free in the 
destructor. Don't do this. You don't need to call GC.free at all. 
The GC will collect both your object instance and the memory you 
allocated with new. Never, ever, manipulate GC memory in the 
destructor of a GC-managed object.


d plugin for Intelij Idea debuging support

2016-01-29 Thread Pavel via Digitalmars-d-learn

Hello!

Is there any debuging support for Intelij Idea's D plugin?

Thanks!


Why is it a memory ERRO.

2016-01-29 Thread Dsby via Digitalmars-d-learn

the Code:
class MyClass
{
this(){
by = new ubyte[1];
++i;
}
~this(){
GC.free(by.ptr);
by = null;
writeln("free");
}
void show(){
writeln(i);
};
private:
ubyte[]   by;
static i = 0;
};

void main()
{
bool start = true;
int i = 0;
while(start){
auto obj = new MyClass();
obj.show();
Thread.sleep(5.msecs);
//obj.destroy;
//GC.free(cast(void *)obj);
++i;
if (i > 2)
break;
}
}

the code will be :
341
core.exception.InvalidMemoryOperationError@src/core/exception.d(679): Invalid 
memory operation

core.exception.InvalidMemoryOperationError@src/core/exception.d(679): Invalid 
memory operation


.why is it?
if < obj.destroy; > is exec. the code will not errno.



Re: Why is it a memory ERRO.

2016-01-29 Thread Dsby via Digitalmars-d-learn

On Friday, 29 January 2016 at 12:43:53 UTC, Dsby wrote:

the Code:
class MyClass
{
this(){
by = new ubyte[1];
++i;
}
~this(){
GC.free(by.ptr);
by = null;
writeln("free");
}
void show(){
writeln(i);
};
private:
ubyte[]   by;
static i = 0;
};

void main()
{
bool start = true;
int i = 0;
while(start){
auto obj = new MyClass();
obj.show();
Thread.sleep(5.msecs);
//obj.destroy;
//GC.free(cast(void *)obj);
++i;
if (i > 2)
break;
}
}

the code will be :
341
core.exception.InvalidMemoryOperationError@src/core/exception.d(679): Invalid 
memory operation

core.exception.InvalidMemoryOperationError@src/core/exception.d(679): Invalid 
memory operation


.why is it?
if < obj.destroy; > is exec. the code will not errno.


I am in 2.069, on opensuse leap 42.1 X86_64
dmd -v
DMD64 D Compiler v2.069
Copyright (c) 1999-2015 by Digital Mars written by Walter Bright



Re: merging map/filter/reduce/... in D

2016-01-29 Thread glathoud via Digitalmars-d-learn

Thanks. I am glad be wrong on that one.

I had a look at map & filter in the source code ; pleased to see 
they're lazily implemented!


map
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L425

filter
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L924
I had to look for FilterResult!
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L979

Small remark: One could make the laziness of filter a bit more 
clear in the doc though - at least for newbies like me.

http://dlang.org/phobos/std_algorithm_iteration.html

Best regards,
Guillaume



Re: merging map/filter/reduce/... in D

2016-01-29 Thread cym13 via Digitalmars-d-learn

On Friday, 29 January 2016 at 08:06:14 UTC, glathoud wrote:

Thanks. I am glad be wrong on that one.

I had a look at map & filter in the source code ; pleased to 
see they're lazily implemented!


map
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L425

filter
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L924
I had to look for FilterResult!
https://github.com/D-Programming-Language/phobos/blob/master/std/algorithm/iteration.d#L979

Small remark: One could make the laziness of filter a bit more 
clear in the doc though - at least for newbies like me.

http://dlang.org/phobos/std_algorithm_iteration.html

Best regards,
Guillaume


While it's not entirely true because one can implement a non-lazy 
range, any time you see the word "range" in the documentation you 
should think that it is lazy. Ranges are an important concept in 
D so we usually don't bother explaining it in the doc. You can 
read about it here if you need to: 
http://ddili.org/ders/d.en/ranges.html and 
http://dlang.org/phobos/std_range.html


Re: Overriding opEquals in classes, for comparison with things that aren't Objects

2016-01-29 Thread pineapple via Digitalmars-d-learn

On Friday, 29 January 2016 at 15:13:45 UTC, Mike Parker wrote:
The first implementation is fine because you're overriding the 
implementation in the base class (Object). However, the second 
one fails because it's a template. Templates are non-virtual 
and cannot override anything. Even if you could, there is no 
such implementation in Object and, therefore, nothing to 
override.


Templated functions can be used as overloads, though, but I'm 
not sure off the top of my head if the compiler accepts 
templated opEquals on classes at all. My guess is no, but you 
can find out by removing the override from the template 
declaration. If not, you should be able to implement 
non-templated overloads for the types you're interested in 
(without the override keyword, mind you, since they won't be 
overriding anything).


Hm, I should've thought to try that. I was able to get things 
working as I wanted them to by doing this:


override bool opEquals(Object value) const{
return this.equals(cast(typeof(this)) value);
}
bool opEquals(T)(T value){
return this.equals(value);
}



Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Basile B. via Digitalmars-d-learn

On Friday, 29 January 2016 at 15:28:29 UTC, Adrian Matoga wrote:

How can I reliably test if CallsFoo can be instantiated?


You can use a constraint to prevent invalid instantiation:

struct HasFoo { void foo() {} }

struct NoFoo {}

struct CallsFoo(T)
if (__traits(hasMember, T, "foo"))
{
T t;
void bar() { t.foo(); }
}

static assert(is(CallsFoo!HasFoo));
static assert(!is(CallsFoo!NoFoo));





Re: Assert failure on 2.070.0 without stack trace

2016-01-29 Thread Benjamin Thaut via Digitalmars-d-learn

On Thursday, 28 January 2016 at 18:33:19 UTC, Nordlöw wrote:


Thanks, I'm aware of these tools.

But it's easier to use the stacktrace...if I only get one. The 
function where the assert() is called is, in turn, called in 
hundreds of places.


Which platform are you on? Are all your binaries compiled with 
debug symbols? If one or multiple functions on the stack are 
within phobos or druntime you might not have debug symbols for 
phobos or druntime. Using inline asm might also destroy your 
stack frames.


Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 10:28 AM, Adrian Matoga wrote:

Code:


struct HasFoo { void foo() {} }

struct NoFoo {}

struct CallsFoo(T) {
 T t;
 void bar() { t.foo(); }
}

static assert(is(CallsFoo!HasFoo));
alias Bar = CallsFoo!HasFoo;

static assert(is(CallsFoo!NoFoo)); // (1)
//alias Baz = CallsFoo!NoFoo;  // (2)


This compiles, although I expected that (1) should fail.
Now try uncommenting (2) and it can't be compiled.

Why does `is(CallsFoo!NoFoo)` evaluate to true if `is(CallsFoo!NoFoo)`
can't be instantiated?
Am I missing something about `is(T)` or is it a bug?
How can I reliably test if CallsFoo can be instantiated?



is(T) is supposed to be false if T is not a valid type.

I would agree with you that the static assert should fail.

-Steve


is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Adrian Matoga via Digitalmars-d-learn

Code:


struct HasFoo { void foo() {} }

struct NoFoo {}

struct CallsFoo(T) {
T t;
void bar() { t.foo(); }
}

static assert(is(CallsFoo!HasFoo));
alias Bar = CallsFoo!HasFoo;

static assert(is(CallsFoo!NoFoo)); // (1)
//alias Baz = CallsFoo!NoFoo;  // (2)


This compiles, although I expected that (1) should fail.
Now try uncommenting (2) and it can't be compiled.

Why does `is(CallsFoo!NoFoo)` evaluate to true if 
`is(CallsFoo!NoFoo)` can't be instantiated?

Am I missing something about `is(T)` or is it a bug?
How can I reliably test if CallsFoo can be instantiated?



InSituRegion + allocatorObject compile time error

2016-01-29 Thread ref2401 via Digitalmars-d-learn

Getting this error, could someone explain why?

void main(string[] args) {
InSituRegion!(1024) stackAlloc;
IAllocator alloc = allocatorObject(stackAlloc);
}

..\src\phobos\std\conv.d(5055):
Error: static assert  "Don't know how to initialize an object of 
type CAllocatorImpl!(InSituRegion!(1024u, 8u), cast(Flag)false) 
with arguments (InSituRegion!(1024u, 8u))"


..\src\phobos\std\experimental\allocator\package.d(1175):
instantiated from here: 
emplace!(CAllocatorImpl!(InSituRegion!(1024u, 8u), 
cast(Flag)false), InSituRegion!(1024u, 8u))


main.d(15):
instantiated from here: allocatorObject!(InSituRegion!(1024u, 8u))

Thank you


Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Adrian Matoga via Digitalmars-d-learn
On Friday, 29 January 2016 at 16:36:01 UTC, Steven Schveighoffer 
wrote:

On 1/29/16 10:28 AM, Adrian Matoga wrote:

Code:


struct HasFoo { void foo() {} }

struct NoFoo {}

struct CallsFoo(T) {
 T t;
 void bar() { t.foo(); }
}

static assert(is(CallsFoo!HasFoo));
alias Bar = CallsFoo!HasFoo;

static assert(is(CallsFoo!NoFoo)); // (1)
//alias Baz = CallsFoo!NoFoo;  // (2)


This compiles, although I expected that (1) should fail.
Now try uncommenting (2) and it can't be compiled.

Why does `is(CallsFoo!NoFoo)` evaluate to true if 
`is(CallsFoo!NoFoo)`

can't be instantiated?
Am I missing something about `is(T)` or is it a bug?
How can I reliably test if CallsFoo can be instantiated?



is(T) is supposed to be false if T is not a valid type.

I would agree with you that the static assert should fail.

-Steve


Oh, there's more:
// this should fail:
static assert(is(CallsFoo!NoFoo));
// this should fail too:
static assert(is(typeof({ alias Baz = CallsFoo!NoFoo; return 
Baz.init; }(;

// and this:
static assert(__traits(compiles, { alias Baz = CallsFoo!NoFoo; 
return Baz.init; }()));

// but only this fails:
alias Baz = CallsFoo!NoFoo;

https://issues.dlang.org/show_bug.cgi?id=15623



opApply @safety

2016-01-29 Thread Chris Wright via Digitalmars-d-learn
I want to create an opApply for a type.

I've marked my code @safe, because everything I wrote was @safe. The body 
of opApply is @safe, but it calls a delegate that may or may not be @safe.

How do I make it so I can iterate through this type safely and systemly?

I want to support iteration like:

foreach (string key, string value; collection) {}
foreach (size_t i, string key, string value; collection) {}


Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 6:44 PM, Basile B. wrote:


Haven't you seen my answer about constraint ?

If you put a constraint on your function template then invalid
instantiations are rejected. I mean... this language feature is not just
ornamental...

What do you think constraints are used for otherwise ^^


A constraint should not be necessary here. Constraints are useful when 
you have multiple templates that may match (without specializations), or 
you want to affect the way the compiler reports errors.


Iff a template instantiation T compiles, then is(T) should evaluate to 
true. At least, that's my understanding.


-Steve


Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Basile B. via Digitalmars-d-learn

On Friday, 29 January 2016 at 17:01:46 UTC, Adrian Matoga wrote:
On Friday, 29 January 2016 at 16:36:01 UTC, Steven 
Schveighoffer wrote:

On 1/29/16 10:28 AM, Adrian Matoga wrote:

[...]


is(T) is supposed to be false if T is not a valid type.

I would agree with you that the static assert should fail.

-Steve


Oh, there's more:
// this should fail:
static assert(is(CallsFoo!NoFoo));
// this should fail too:
static assert(is(typeof({ alias Baz = CallsFoo!NoFoo; return 
Baz.init; }(;

// and this:
static assert(__traits(compiles, { alias Baz = CallsFoo!NoFoo; 
return Baz.init; }()));

// but only this fails:
alias Baz = CallsFoo!NoFoo;

https://issues.dlang.org/show_bug.cgi?id=15623


Haven't you seen my answer about constraint ?

If you put a constraint on your function template then invalid 
instantiations are rejected. I mean... this language feature is 
not just ornamental...


What do you think constraints are used for otherwise ^^


Re: UTF-16 endianess

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 6:03 PM, Marek Janukowicz wrote:

On Fri, 29 Jan 2016 17:43:26 -0500, Steven Schveighoffer wrote:

Is there anything I should know about UTF endianess?


It's not any different from other endianness.

In other words, a UTF16 code unit is expected to be in the endianness of
the platform you are running on.

If you are on x86 or x86_64 (very likely), then it should be little endian.

If your source of data is big-endian (or opposite from your native
endianness),


To be precise - my case is IMAP UTF7 folder name encoding and I finally found
out it's indeed big endian, which explains my problem (as I'm indeed on x86_64).


it will have to be converted before treating as a wchar[].


Is there any clever way to do the conversion? Or do I need to swap the bytes
manually?


No clever way, just the straightforward way ;)

Swapping endianness of 32-bits can be done with core.bitop.bswap. Doing 
it with 16 bits I believe you have to do bit shifting. Something like:


foreach(ref elem; wcharArr) elem = ((elem << 8) & 0xff00) | ((elem >> 8) 
& 0x00ff);


Or you can do it with the bytes directly before casting




Note the version identifiers BigEndian and LittleEndian can be used to
compile the correct code.


This solution is of no use to me as I don't want to change the endianess in
general.


What I mean is that you can annotate your code with version statements like:

version(LittleEndian)
{
   // perform the byteswap
   ...
}

so your code is portable to BigEndian systems (where you would not want 
to byte swap).


-Steve


Re: Relocatable objects and internal pointers

2016-01-29 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Jan 30, 2016 at 01:21:27AM +, Matt Elkins via Digitalmars-d-learn 
wrote:
> On Saturday, 30 January 2016 at 01:18:33 UTC, Ali Çehreli wrote:
> >Definitely so. Rvalues are moved around all the time. The following
> >program has two rvalue moves without calling post-blits or
> >destructors.
> 
> Oi, that makes life tough. Ok, I'll figure something else out, then...
[...]

Keep in mind that D structs are conceptually different from C++ structs
(even if they are similarly implemented). D structs are supposed to be
value types with POD-like semantics; so when passing structs around they
are bit-copied into the destination and then the postblit method
(this(this)) is called to "patch up" the copy. This is unlike in C++
where you have copy ctors and dtors and operator=() to manage copying.

Because there are no copy ctors, having internal pointers can be
dangerous, since structs can move around in memory without any warning
(e.g., returning a struct from a function generally involves copying it
from the callee's stack frame into a local variable in the caller's
stack frame).

If you need something with internal pointers, you might want to consider
classes instead. Either that, or be sure to allocate your structs on the
heap instead, and work with pointers instead of the struct values
directly. (Note that this is still risky, since somebody might
dereference the pointer and get a stack copy of the struct, which will
cause problems when it then gets passed around.)


T

-- 
I am a consultant. My job is to make your job redundant. -- Mr Tom


Re: Relocatable objects and internal pointers

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn

On Saturday, 30 January 2016 at 01:28:54 UTC, H. S. Teoh wrote:
On Sat, Jan 30, 2016 at 01:21:27AM +, Matt Elkins via 
Digitalmars-d-learn wrote:
On Saturday, 30 January 2016 at 01:18:33 UTC, Ali Çehreli 
wrote:
>Definitely so. Rvalues are moved around all the time. The 
>following program has two rvalue moves without calling 
>post-blits or destructors.


Oi, that makes life tough. Ok, I'll figure something else out, 
then...

[...]

Keep in mind that D structs are conceptually different from C++ 
structs (even if they are similarly implemented). D structs are 
supposed to be value types with POD-like semantics; so when 
passing structs around they are bit-copied into the destination 
and then the postblit method (this(this)) is called to "patch 
up" the copy. This is unlike in C++ where you have copy ctors 
and dtors and operator=() to manage copying.


Because there are no copy ctors, having internal pointers can 
be dangerous, since structs can move around in memory without 
any warning (e.g., returning a struct from a function generally 
involves copying it from the callee's stack frame into a local 
variable in the caller's stack frame).


If you need something with internal pointers, you might want to 
consider classes instead. Either that, or be sure to allocate 
your structs on the heap instead, and work with pointers 
instead of the struct values directly. (Note that this is still 
risky, since somebody might dereference the pointer and get a 
stack copy of the struct, which will cause problems when it 
then gets passed around.)



T


Yeah, but the whole point of what I am doing is to avoid using 
the heap; I can think of several ways to implement this if I 
relax that restriction :). I'm basically trying to make C++'s 
std::unique_ptr for resource handles, a thin wrapper which 
ensures resource cleanup and allows moving the handle. Since I'm 
putting it in my lowest-level/most-generic library with no 
visibility on how it gets used, I want it very lightweight 
(ideally zero-cost, like I can do in C++11, or at least low-cost 
[sans heap] like I could do in C++98) so that I can use it with 
the broadest range of higher-level applications.


Re: Relocatable objects and internal pointers

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 8:07 PM, Matt Elkins wrote:

[snip]
on D and came across a section in TDPL which said internal pointers are
verboten because objects must be relocatable. Does this mean my example
is invalid (e.g., the invariant will not hold in all circumstances)? If
it is invalid, does that mean there are circumstances under which the
post-blit constructor can be elided when performing a copy or copy-like
operation (such as a move)? I've been treating it like a sort of
copy-constructor that lacks visibility on the copied-from object, but
maybe that's a mistake...


No, you cannot have internal pointers. But...

I figured out a way to have them. You just have to guarantee you don't 
copy the actual "pointer" out of the struct:


https://forum.dlang.org/post/mk5k4l$s5r$1...@digitalmars.com

-Steve


UTF-16 endianess

2016-01-29 Thread Marek Janukowicz via Digitalmars-d-learn
I have trouble understanding how endianess works for UTF-16.

For example UTF-16 code for 'ł' character is 0x0142. But this program shows
otherwise:

import std.stdio;

public void main () {
  ubyte[] properOrder = [0x01, 0x42];
ubyte[] reverseOrder = [0x42, 0x01];
writefln( "proper: %s, reverse: %s", 
cast(wchar[])properOrder, 
cast(wchar[])reverseOrder );
}

output:

proper: 䈁, reverse: ł

Is there anything I should know about UTF endianess?

-- 
Marek Janukowicz


Re: opApply @safety

2016-01-29 Thread Basile B. via Digitalmars-d-learn

On Friday, 29 January 2016 at 17:44:34 UTC, Chris Wright wrote:

I want to create an opApply for a type.

I've marked my code @safe, because everything I wrote was 
@safe. The body of opApply is @safe, but it calls a delegate 
that may or may not be @safe.


How do I make it so I can iterate through this type safely and 
systemly?


I want to support iteration like:

foreach (string key, string value; collection) {}
foreach (size_t i, string key, string value; collection) {}


You can implement an input range and annotate all the primitives 
as @safe.
Then if there's only an input range in your agregate, DMD will 
auto-detect that it must use it in foreach():


http://dlang.org/spec/statement.html#foreach-with-ranges

in the worst case (range not implementable directly but only as a 
getter in .range() or .opSlice() you'll have to change the style 
a bit and consume the range explicitly in a typical "while 
(!stuff.empty) {...}"





Re: UTF-16 endianess

2016-01-29 Thread Johannes Pfau via Digitalmars-d-learn
Am Fri, 29 Jan 2016 18:58:17 -0500
schrieb Steven Schveighoffer :

> On 1/29/16 6:03 PM, Marek Janukowicz wrote:
> > On Fri, 29 Jan 2016 17:43:26 -0500, Steven Schveighoffer wrote:  
> >>> Is there anything I should know about UTF endianess?  
> >>
> >> It's not any different from other endianness.
> >>
> >> In other words, a UTF16 code unit is expected to be in the
> >> endianness of the platform you are running on.
> >>
> >> If you are on x86 or x86_64 (very likely), then it should be
> >> little endian.
> >>
> >> If your source of data is big-endian (or opposite from your native
> >> endianness),  
> >
> > To be precise - my case is IMAP UTF7 folder name encoding and I
> > finally found out it's indeed big endian, which explains my problem
> > (as I'm indeed on x86_64). 
> >> it will have to be converted before treating as a wchar[].  
> >
> > Is there any clever way to do the conversion? Or do I need to swap
> > the bytes manually?  
> 
> No clever way, just the straightforward way ;)
> 
> Swapping endianness of 32-bits can be done with core.bitop.bswap.
> Doing it with 16 bits I believe you have to do bit shifting.
> Something like:
> 
> foreach(ref elem; wcharArr) elem = ((elem << 8) & 0xff00) | ((elem >>
> 8) & 0x00ff);
> 
> Or you can do it with the bytes directly before casting


There's also a phobos solution: bigEndianToNative in std.bitmanip.



Re: Relocatable objects and internal pointers

2016-01-29 Thread Ali Çehreli via Digitalmars-d-learn

On 01/29/2016 05:07 PM, Matt Elkins wrote:

>  this(/* arguments to populate stuff */)
>  {
>  m_this = 
>  /* ... populate stuff ... */
>  }

> a section in TDPL which said internal pointers are
> verboten because objects must be relocatable. Does this mean my example
> is invalid

Yes, D explicitly bans internal pointers.

> does that mean there are circumstances under which the
> post-blit constructor can be elided when performing a copy or copy-like
> operation (such as a move)?

Definitely so. Rvalues are moved around all the time. The following 
program has two rvalue moves without calling post-blits or destructors.


struct Foo {
this(this) {
assert(false);// not expected to be called in this program
}
}

Foo makeFoo() {
return Foo();
}

void takesFoo(Foo foo) {
}

void main() {
Foo foo;
foo = makeFoo();// post-blit not called
takesFoo(Foo());// post-blit not called
}

Ali



Re: Dub packages: Best practices for windows support

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Friday, 29 January 2016 at 19:46:40 UTC, Johannes Pfau wrote:

Now on windows, things are more complicated. First of all, I 
can't seem

to simply use "libs": ["foo"] as the linker won't find the C
import .lib file. Then apparently there's no way to add a 
library search

path with the MSVC linker? So I have to use the full path:
"libs": [$PACKAGE_DIR\\path\\foo]. Without $PACKAGE_DIR paths 
are
incorrect for applications using the library because of a dub 
problem.
And then I'll have to use different import libraries and paths 
for -m32,

-m64 and -m32mscoff.


Now you know my motivation for creating Derelict.



All this leads to the following questions:
* Should cairoD copy the DLLs for all applications using 
cairoD? This
  way simply adding a dependency will work. However, if users 
want to
  use a self compiled cairo DLL with fewer dependencies there's 
no easy

  way to disable the file copying?
* Should cairoD link in the .lib DLL import file? This might be 
useful
  even when not copying the DLLs. But if users want to link a 
custom
  import library that would be difficult. OTOH not copying DLLs 
and/or

  not linking the import library will make dub.json much more
  complicated for simple applications, especially if these 
applications

  want to support -m32, -m32mscoff and -m64.


IMO, no to both of these (for now). Including all of these 
dependencies is going to mean that all of your users, no matter 
the platform, will pull the down with every new version of gtkd.  
I recommend you provide all of the precompiled DLLs and import 
libraries as a separate download and let the user do the 
configuration needed to get it to link. Most Windows developers 
are used to it. You can provide instructions for those who aren't.


Hopefully one day dub will have the ability to pull down library 
dependencies on demand, or based on the current platform and 
architecture by default, then this problem goes away.


* What's the best way to support all of -m32, -m32mscoff and 
-m64? I've
  got working import libraries and DLLs for all configurations, 
but how
  to support this in dub.json? I think the best way would be to 
have
  -ms32coff as a special architecture or flag for dub, but I 
can't seem
  to find any documentation about that. -m64 can be detected by 
x86_64

  in platforms, but how to detect -m32 vs -m32mscoff?

  Alternatively I could simply let users choose the 
configurations

  manually. But adding dflags: ["-m32mscoff"] does not build the
  Derelict dependencies with the m32mscoff flag so linking will 
fail...


  DFLAGS="-m32mscoff" doesn't work with dub test as the dub test
  command ignores the DFLAGS variable. I'd have to check 
whether it
  works for applications, but then there's still no way to use 
the

  correct cairo import library in cairoDs dub.json


There's an issue for this at [1]. Until support for -m32mscoff is 
baked in, distributing any libraries with a dub project will be 
problematic.




Re: Dub packages: Best practices for windows support

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 30 January 2016 at 01:17:13 UTC, Mike Parker wrote:

There's an issue for this at [1]. Until support for -m32mscoff 
is baked in, distributing any libraries with a dub project will 
be problematic.


[1] https://github.com/D-Programming-Language/dub/issues/628


Re: Dub packages: Best practices for windows support

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 30 January 2016 at 01:17:13 UTC, Mike Parker wrote:

Hopefully one day dub will have the ability to pull down 
library dependencies on demand, or based on the current 
platform and architecture by default, then this problem goes 
away.



I should say "precompiled library dependencies".


Re: UTF-16 endianess

2016-01-29 Thread Adam D. Ruppe via Digitalmars-d-learn
On Friday, 29 January 2016 at 22:36:37 UTC, Marek Janukowicz 
wrote:

I have trouble understanding how endianess works for UTF-16.


UTF-16 (as well as UTF-32) comes in both little-endian and 
big-endian variants. A byte-order marker in the file can help you 
detect which one it is in.


See t his t able:

http://www.unicode.org/faq/utf_bom.html#gen6



To cast a uint to float to compute k/n, use to! or cast()?

2016-01-29 Thread Enjoys Math via Digitalmars-d-learn

I want to compute the points of a regular polygon in a loop:

float r = 1.0;

for (uint k=0; k < numVerts; k++) {
   vertlist ~= Vec2D(r * cos(k/n * 2 * PI), ...)
}

How do I make sure k/n is a float or double?


Re: is(some template instantiation) is true, but the actual instantiation fails

2016-01-29 Thread Ali Çehreli via Digitalmars-d-learn

On 01/29/2016 09:01 AM, Adrian Matoga wrote:

> Oh, there's more:
> // this should fail:
> static assert(is(CallsFoo!NoFoo));
> // this should fail too:
> static assert(is(typeof({ alias Baz = CallsFoo!NoFoo; return Baz.init;
> }(;
> // and this:
> static assert(__traits(compiles, { alias Baz = CallsFoo!NoFoo; return
> Baz.init; }()));
> // but only this fails:
> alias Baz = CallsFoo!NoFoo;
>
> https://issues.dlang.org/show_bug.cgi?id=15623

As I noted on the bug report, they are work when moved from module scope 
to inside a function (e.g. main()). At least there's that workaround...


Ali



Re: opApply @safety

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 3:08 PM, Chris Wright wrote:

On Fri, 29 Jan 2016 14:00:08 -0500, Steven Schveighoffer wrote:


On 1/29/16 12:44 PM, Chris Wright wrote:

I want to create an opApply for a type.

I've marked my code @safe, because everything I wrote was @safe. The
body of opApply is @safe, but it calls a delegate that may or may not
be @safe.

How do I make it so I can iterate through this type safely and
systemly?


Likely an overload. Tag the delegate as being @safe or not.

-Steve


That's handy. It works. I can make it so someone can call:
foo.opApply((i, k, v) @safe => 0);
foo.opApply((i, k, v) @system => 0);

And that works.

However, if you have:
@safe void bar() {
   foreach(i, k, v; foo) {
   }
}

the compiler complains:

opapplysafe.d(12): Error: foo.opApply matches more than one declaration:
opapplysafe.d(2): @safe int(int delegate(int, string, string) @safe
dg)
and:
opapplysafe.d(5): @system int(int delegate(int, string, string)
@system dg)

Guess I'll file a bug.



Definitely seems like a bug.

As a workaround, you can name the opApply functions:

struct S
{
   int opApply(int delegate(int, string, string) @safe dg) @safe {...}
   int unsafeApply(int delegate(int, string, string) dg) {...}
}

foreach(i, k, v; foo.unsafeApply) {...}

though that's... ugly.

-Steve


Re: opApply @safety

2016-01-29 Thread Chris Wright via Digitalmars-d-learn
On Fri, 29 Jan 2016 23:35:35 +, Basile B. wrote:
> You can implement an input range and annotate all the primitives as
> @safe.

I hadn't realized that if front() returns a tuple, it's automatically 
expanded. Works for me.


Re: To cast a uint to float to compute k/n, use to! or cast()?

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 6:48 PM, Enjoys Math wrote:

I want to compute the points of a regular polygon in a loop:

float r = 1.0;

for (uint k=0; k < numVerts; k++) {
vertlist ~= Vec2D(r * cos(k/n * 2 * PI), ...)
}

How do I make sure k/n is a float or double?


uint is promoted to float/double with a binary math operation. You could 
simply reverse the order of your expression:


2 * PI * k/n

But if you want to force a type change with simple conversions such as 
these, just use a constructor:


float(k) / n * 2 * PI

There is no need to cast or use `to` (though both of those would be 
equivalent to simple conversion).


-Steve


Re: UTF-16 endianess

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 5:36 PM, Marek Janukowicz wrote:

I have trouble understanding how endianess works for UTF-16.

For example UTF-16 code for 'ł' character is 0x0142. But this program shows
otherwise:

import std.stdio;

public void main () {
   ubyte[] properOrder = [0x01, 0x42];
ubyte[] reverseOrder = [0x42, 0x01];
writefln( "proper: %s, reverse: %s",
cast(wchar[])properOrder,
cast(wchar[])reverseOrder );
}

output:

proper: 䈁, reverse: ł

Is there anything I should know about UTF endianess?


It's not any different from other endianness.

In other words, a UTF16 code unit is expected to be in the endianness of 
the platform you are running on.


If you are on x86 or x86_64 (very likely), then it should be little endian.

If your source of data is big-endian (or opposite from your native 
endianness), it will have to be converted before treating as a wchar[].


Note the version identifiers BigEndian and LittleEndian can be used to 
compile the correct code.


-Steve


Relocatable objects and internal pointers

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
Hi all, I'm a C++ programmer trying to decide whether to switch 
my main focus to D, and so I'm working on a pet project using it. 
So far I really like some of the practical aspects of the 
language (built-in contracts are great, the metaprogramming is 
very accessible, and I can't enough of these compile speeds!), 
but I keep finding myself frustrated by what seem like 
expressiveness limitations (unless, as I hope, they are just 
examples of my newbieness shining through). Case in point:


In an attempt to work around one apparent limitation (previously 
asked about here 
http://forum.dlang.org/thread/eizmagtimvetogana...@forum.dlang.org) I came up with an idea which would require storing internal points in a struct. A very stripped-down but illustrative example would be something like this:


[code]
struct Foo
{
invariant
{
assert(m_this == );
}

@disable(this);

this(/* arguments to populate stuff */)
{
m_this = 
/* ... populate stuff ... */
}

this(this)
{
m_this = 
/* ... do more stuff ... */
}

private:
Foo* m_this;
/* ... stuff ... */
}
[/code]

This is just a piece of what I am doing, if you are wondering why 
I am bothering to save a pointer to this. However, I was doing 
some reading on D and came across a section in TDPL which said 
internal pointers are verboten because objects must be 
relocatable. Does this mean my example is invalid (e.g., the 
invariant will not hold in all circumstances)? If it is invalid, 
does that mean there are circumstances under which the post-blit 
constructor can be elided when performing a copy or copy-like 
operation (such as a move)? I've been treating it like a sort of 
copy-constructor that lacks visibility on the copied-from object, 
but maybe that's a mistake...


Re: Relocatable objects and internal pointers

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 9:35 PM, Matt Elkins wrote:

On Saturday, 30 January 2016 at 02:09:55 UTC, Steven Schveighoffer wrote:

I figured out a way to have them. You just have to guarantee you don't
copy the actual "pointer" out of the struct:

https://forum.dlang.org/post/mk5k4l$s5r$1...@digitalmars.com


Unfortunately, that won't work for what I was trying to do. The stuff I
elided in the comments were more pointers to other Foo instances, used
to create a linked-list (of stack-allocated objects); these would still
break under the conditions Ali described. I was only storing the this
pointer so that blitted objects could deduce where they came from
(trying to turn the post-blit constructor into a copy-constructor).


Ah, so you were actually counting on the postblit to have an *invalid* 
pointer to begin with :) Yeah, that isn't going to work. In D, it's 
legal to do something like memcpy struct data (with no postblit), and 
this is done quite often in many places because of that.



Thanks, though. I'm thinking that maybe D just can't express these
semantics without substantial overhead. While somewhat disappointing (I
came into D with stars in my eyes :)), it's not enough by itself to make
me go back to C++, at least not just yet. Not when I can just use a few
static ifs to do what previously required careful template crafting that
I wouldn't understand 3 months later. On the other hand, I'm falling
behind on my library books since I no longer have any time for reading
during compilations ;).


There are some really smart people who frequent these forums, if you 
post your actual use case, you may get an answer that you hadn't thought of.


I saw you were trying to implement something like std::unique_ptr? There 
is http://dlang.org/phobos/std_typecons.html#.Unique


Not sure if it helps.

-Steve


Re: Relocatable objects and internal pointers

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 10:13 PM, Matt Elkins wrote:

On Saturday, 30 January 2016 at 03:00:11 UTC, Steven Schveighoffer wrote:

There are some really smart people who frequent these forums, if you
post your actual use case, you may get an answer that you hadn't
thought of.


Yeah, I tried that first (on the general forum, since at the time I
didn't know about this one).


Ah, didn't notice that. You are likely to get more eyes there, so that 
is good.





I saw you were trying to implement something like std::unique_ptr?
There is http://dlang.org/phobos/std_typecons.html#.Unique


std.typecons.Unique seems to require heap allocation, which makes it a
far cry from std::unique_ptr.


I admit I'm not familiar with either's implementation. I just know that 
they have similar functions.


-Steve


Re: Access Violation in @safe Code

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
On Saturday, 30 January 2016 at 05:18:08 UTC, Steven 
Schveighoffer wrote:

https://issues.dlang.org/enter_bug.cgi

-Steve


Added!
https://issues.dlang.org/show_bug.cgi?id=15627

Thanks for the help.



Re: Relocatable objects and internal pointers

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
On Saturday, 30 January 2016 at 02:09:55 UTC, Steven 
Schveighoffer wrote:
I figured out a way to have them. You just have to guarantee 
you don't copy the actual "pointer" out of the struct:


https://forum.dlang.org/post/mk5k4l$s5r$1...@digitalmars.com


Unfortunately, that won't work for what I was trying to do. The 
stuff I elided in the comments were more pointers to other Foo 
instances, used to create a linked-list (of stack-allocated 
objects); these would still break under the conditions Ali 
described. I was only storing the this pointer so that blitted 
objects could deduce where they came from (trying to turn the 
post-blit constructor into a copy-constructor).


Thanks, though. I'm thinking that maybe D just can't express 
these semantics without substantial overhead. While somewhat 
disappointing (I came into D with stars in my eyes :)), it's not 
enough by itself to make me go back to C++, at least not just 
yet. Not when I can just use a few static ifs to do what 
previously required careful template crafting that I wouldn't 
understand 3 months later. On the other hand, I'm falling behind 
on my library books since I no longer have any time for reading 
during compilations ;).


Re: Relocatable objects and internal pointers

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
On Saturday, 30 January 2016 at 03:00:11 UTC, Steven 
Schveighoffer wrote:
There are some really smart people who frequent these forums, 
if you post your actual use case, you may get an answer that 
you hadn't thought of.


Yeah, I tried that first (on the general forum, since at the time 
I didn't know about this one).


I saw you were trying to implement something like 
std::unique_ptr? There is 
http://dlang.org/phobos/std_typecons.html#.Unique


std.typecons.Unique seems to require heap allocation, which makes 
it a far cry from std::unique_ptr.


Re: Can D interface with Free Pascal?

2016-01-29 Thread Mike Parker via Digitalmars-d-learn
On Saturday, 30 January 2016 at 03:43:59 UTC, Taylor Hillegeist 
wrote:


Working through a simple example. I tried the cdecl option but 
for some reason i can compile but when i run my Gethello it 
cant find the shared library in the same folder?


taylor@taylor-NE510:~/Projects/PASCAL$ nm libhello.so
3ac0 T SubStr
taylor@taylor-NE510:~/Projects/PASCAL$ ./Gethello
./Gethello: error while loading shared libraries: libhello.so: 
cannot open shared object file: No such file or directory




The binary's directory is not on the system search path by 
default on Linux. This page [1] shows three possible solutions.


[1] 
http://www.aimlesslygoingforward.com/2014/01/19/bundling-shared-libraries-on-linux/


Computing the min() / max() of a slice of doubles.

2016-01-29 Thread Enjoys Math via Digitalmars-d-learn

I want to use std.algorithm.min/max,

how would I apply that to a slice of doubles and not a tuple of 
args?


Thanks.


Re: Can D interface with Free Pascal?

2016-01-29 Thread Taylor Hillegeist via Digitalmars-d-learn
On Saturday, 30 January 2016 at 04:49:39 UTC, Taylor Hillegeist 
wrote:
On Saturday, 30 January 2016 at 04:35:29 UTC, Taylor Hillegeist 
wrote:
On Saturday, 30 January 2016 at 04:11:07 UTC, Mike Parker 
wrote:

[...]


Now I'm wishing that was the problem. Interestingly enough 
when i link to a C shared library it works... but also it 
isn't show in the needed shared library sections like below.


[...]


Acctually I made multiple mistakes. 0x000f (RPATH) 
Library rpath:[--export-dynamic] should be [lib]


Ill fix that and test again.


dmd Gethello.d -Llibhello.so -L"-rpath=./" made it use the CWD 
able to load libraries! cool!


Re: Access Violation in @safe Code

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 11:53 PM, Matt Elkins wrote:

Title says it; I get an access violation in code marked @safe. Here's a
minimal example:

[code]
@safe:

struct Foo(alias Callback)
{
 ~this() {Callback();}
}

unittest
{
 uint stackVar;
 alias FooType = Foo!((){++stackVar;});

 FooType[1] foos;
 foos[0] = FooType.init;
}
[/code]

This results in:
object.Error@(0): Access Violation

0x00405E2A in pure nothrow @nogc @safe void
test.__unittestL9_4().__lambda1() at \test.d(12)
 more stack ...

Line 12 is the alias FooType line, where the delegate is defined.

Where is this coming from? Intuition says it is something to do with
calling the delegate after the stack frame has popped and stackVar is
unreachable, but I'm not seeing it. Wouldn't foos be destructed before
the stack frame is gone?

I don't get the issue if I mark stackVar static, or if I don't perform
the assignment to foos[0].


This looks like a bug in the compiler. It appears that Foo.init as an 
rvalue destroying itself results in a call into an invalid stack.


It doesn't require a lambda, or a fixed-size array. And it doesn't 
require the stack frame holding stackVar to be invalid. This also shows 
the behavior:


unittest
{
uint stackVar;
void blah() { ++stackVar; }

{
   // introduce inner scope
   FooType foo = FooType.init;
}

}

https://issues.dlang.org/enter_bug.cgi

-Steve


Conditional nothrow/safe/nogc/etc?

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
Is there any way to specify that a generic function is 
conditionally nothrow (or other function decorators), based on 
whether the template instantiation is nothrow? I'm looking for 
something akin to C++'s noexcept(noexcept()), e.g.:


template  void foo() noexcept(noexcept(T())) {}

I don't see anything about it on the functions grammar page 
(https://dlang.org/spec/function.html). I do see something to do 
with nothrow_ on the std.traits page, but I'm not sure how to use 
it to achieve this or whether that is the right approach.


My actual use case is a non-generic method opAssign inside of a 
generic struct.


Re: Weird multithreading stuff

2016-01-29 Thread asdf via Digitalmars-d-learn
Okay so it turns out putting something in another thread is like 
throwing it into an alternate universe where only my functions 
exist, and instead of telling me my data doesn't exist, it just 
silently behaves as if it's all empty


Man, threads are weird. I'll just pass the data in as an argument 
or something

christ


Re: Weird multithreading stuff

2016-01-29 Thread tsbockman via Digitalmars-d-learn

On Saturday, 30 January 2016 at 05:15:58 UTC, asdf wrote:
Okay so it turns out putting something in another thread is 
like throwing it into an alternate universe where only my 
functions exist, and instead of telling me my data doesn't 
exist, it just silently behaves as if it's all empty


Are you aware that variables declared "static" or at global scope 
in D are actually thread-local by default?


Anyway, you can't really expect anyone else to be able to debug 
something like this with just pseudo-code.


Give me a *complete* program which you think should work on 
GitHub or http://dpaste.dzfl.pl/ and I'll see what I can do with 
it. Since your problem occurs at runtime, make sure that it 
actually compiles without error before you post it.


Re: Weird multithreading stuff

2016-01-29 Thread tsbockman via Digitalmars-d-learn

On Saturday, 30 January 2016 at 05:57:20 UTC, asdf wrote:

No I've fixed it now
All I was asking for anyway was a little bit of help as to how 
threads work, which "variables declared "static" or at global 
scope in D are actually thread-local by default" definitely 
satisfies. I wasn't really asking for someone to read through 
and debug my entire program


Thanks


It's rarely necessary to provide the entire *original* program.

But, you're a lot more likely to get real help if you include a 
simple program that demonstrates the problem (a "reduced test 
case"), which other people can try out.


As an example of why this is important, consider that the true 
source of your problem cannot actually be found in the code you 
posted above, at all. I guessed what it was, based on your 
follow-up post - but that's all I was doing: *guessing*. It could 
have turned out to be something else entirely - maybe even a bug 
in the compiler or the standard library. (These are still rather 
common with D, unfortunately.)


I think you'll also find, in general, that producing a good, 
simple test case is a very effective technique for debugging your 
own code - even before you ask others for help.


Re: Why is it a memory ERRO.

2016-01-29 Thread Mike Parker via Digitalmars-d-learn

On Saturday, 30 January 2016 at 05:50:33 UTC, Dsby wrote:

Ok.Thank you.
and i want to know how to know when the GC start runing?


For the current implementation, any time you allocate memory 
through the GC it will determine if a collection cycle is needed, 
but it will not run otherwise.


Re: Weird multithreading stuff

2016-01-29 Thread asdf via Digitalmars-d-learn

Okay it somehow just got even stranger

that condition 'tokenIsAnOperator' in that code is a function to 
test whether the token is contained within the array ["+", "-", 
"*", "/"]


It seems that sometimes it returns true for "*", and sometimes 
false, but only when I have "parallel" in that foreach loop


what?


Access Violation in @safe Code

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
Title says it; I get an access violation in code marked @safe. 
Here's a minimal example:


[code]
@safe:

struct Foo(alias Callback)
{
~this() {Callback();}
}

unittest
{
uint stackVar;
alias FooType = Foo!((){++stackVar;});

FooType[1] foos;
foos[0] = FooType.init;
}
[/code]

This results in:
object.Error@(0): Access Violation

0x00405E2A in pure nothrow @nogc @safe void 
test.__unittestL9_4().__lambda1() at \test.d(12)

... more stack ...

Line 12 is the alias FooType line, where the delegate is defined.

Where is this coming from? Intuition says it is something to do 
with calling the delegate after the stack frame has popped and 
stackVar is unreachable, but I'm not seeing it. Wouldn't foos be 
destructed before the stack frame is gone?


I don't get the issue if I mark stackVar static, or if I don't 
perform the assignment to foos[0].


Re: Weird multithreading stuff

2016-01-29 Thread asdf via Digitalmars-d-learn

On Saturday, 30 January 2016 at 05:41:10 UTC, tsbockman wrote:

On Saturday, 30 January 2016 at 05:15:58 UTC, asdf wrote:
Okay so it turns out putting something in another thread is 
like throwing it into an alternate universe where only my 
functions exist, and instead of telling me my data doesn't 
exist, it just silently behaves as if it's all empty


Are you aware that variables declared "static" or at global 
scope in D are actually thread-local by default?


Anyway, you can't really expect anyone else to be able to debug 
something like this with just pseudo-code.


Give me a *complete* program which you think should work on 
GitHub or http://dpaste.dzfl.pl/ and I'll see what I can do 
with it. Since your problem occurs at runtime, make sure that 
it actually compiles without error before you post it.


No I've fixed it now
All I was asking for anyway was a little bit of help as to how 
threads work, which "variables declared "static" or at global 
scope in D are actually thread-local by default" definitely 
satisfies. I wasn't really asking for someone to read through and 
debug my entire program


Thanks


Re: Conditional nothrow/safe/nogc/etc?

2016-01-29 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Jan 30, 2016 at 05:37:07AM +, Matt Elkins via Digitalmars-d-learn 
wrote:
> On Saturday, 30 January 2016 at 05:25:49 UTC, Rikki Cattermole wrote:
> >On 30/01/16 6:17 PM, Matt Elkins wrote:
> >>[...]
> >
> >templated functions have attribute inference. Meaning if it can be
> >nothrow it will be.
> >Regarding your real use case, again struct if templated so it should
> >be inferred.
> 
> Convenient! Thanks!

A common idiom that we use is to write an attributed unittest to verify
that the function itself is @safe/etc.. This way, if instantiated with
safe/etc. types, the template will also be safe/etc., but if
instantiated with an unsafe type, it will correspondingly be unsafe
(instead of failing to compile if you wrote @safe on the template). The
unittest ensures that you do not accidentally introduce un-@safe code
into the template and cause *all* instantiations to become un-@safe.

auto mySafeCode(T)(T t) { ... }

@safe unittest
{
auto x = mySafeCode(safeValue);
}


T

-- 
Why are you blatanly misspelling "blatant"? -- Branden Robinson


Weird multithreading stuff

2016-01-29 Thread asdf via Digitalmars-d-learn
I'm writing a program to parse and evaluate mathematical 
expressions


the parse tree is in the format:

struct node
{
string token;
node*[] children;
}

it is parsed such that for the input 1*(2+3)-4*(5+6), the tree 
ends up looking like

 -
   *   *
1  + 4 +
 2   3   5   6

When the time comes to evaluate this I thought a sensible way to 
do it would be this


real evaluate(node top)
{
real output;
string token = top.token;

if (tokenIsAnOperator)
{
real[2] operands;

foreach (i, child; parallel(top.children))
{
operands[i] = evaluate(*child);
}

output = someFunctionWiththeRightOperator(operands[0], 
operands[1]);

}
else // it must be a number
{
output = parse!real();
}

return output;
}

Which works perfectly - about 20-30% of the time
I can literally paste 1*(2+3)-4*(5+6) into the input over and 
over, and I get

0
5
-39
no digits seen
Floating point conversion error for input "".

seemingly randomly (those two errors are apparently coming from 
somewhere in the std library)


When I put in less complicated expressions I get the right answer 
more of the time, but it can still come out wrong occasionally


And the weirdest part: when I remove "parallel" from the foreach 
loop, it always gives me the correct answer


anyone know what's going on here, and/or how to fix it?


Re: Can D interface with Free Pascal?

2016-01-29 Thread Taylor Hillegeist via Digitalmars-d-learn

On Saturday, 30 January 2016 at 04:11:07 UTC, Mike Parker wrote:
On Saturday, 30 January 2016 at 03:43:59 UTC, Taylor Hillegeist 
wrote:


Working through a simple example. I tried the cdecl option but 
for some reason i can compile but when i run my Gethello it 
cant find the shared library in the same folder?


taylor@taylor-NE510:~/Projects/PASCAL$ nm libhello.so
3ac0 T SubStr
taylor@taylor-NE510:~/Projects/PASCAL$ ./Gethello
./Gethello: error while loading shared libraries: libhello.so: 
cannot open shared object file: No such file or directory




The binary's directory is not on the system search path by 
default on Linux. This page [1] shows three possible solutions.


[1] 
http://www.aimlesslygoingforward.com/2014/01/19/bundling-shared-libraries-on-linux/


Now I'm wishing that was the problem. Interestingly enough when i 
link to a C shared library it works... but also it isn't show in 
the needed shared library sections like below.


taylor@taylor-NE510:~/Projects/PASCAL$ readelf -d Gethello

Dynamic section at offset 0x26dd8 contains 29 entries:
  TagType Name/Value
 0x0001 (NEEDED) Shared library: 
[libhello.so]
 0x0001 (NEEDED) Shared library: 
[libpthread.so.0]
 0x0001 (NEEDED) Shared library: 
[librt.so.1]
 0x0001 (NEEDED) Shared library: 
[libc.so.6]
 0x0001 (NEEDED) Shared library: 
[ld-linux-x86-64.so.2]
 0x000f (RPATH)  Library rpath: 
[--export-dynamic]

 0x000c (INIT)   0x4017f8
 0x000d (FINI)   0x42
 0x0019 (INIT_ARRAY) 0x626db0
 0x001b (INIT_ARRAYSZ)   16 (bytes)
 0x001a (FINI_ARRAY) 0x626dc0
 0x001c (FINI_ARRAYSZ)   16 (bytes)
 0x6ef5 (GNU_HASH)   0x4002d0
 0x0005 (STRTAB) 0x400aa8
 0x0006 (SYMTAB) 0x4002f8
 0x000a (STRSZ)  1202 (bytes)
 0x000b (SYMENT) 24 (bytes)
 0x0015 (DEBUG)  0x0
 0x0003 (PLTGOT) 0x627000
 0x0002 (PLTRELSZ)   1824 (bytes)
 0x0014 (PLTREL) RELA
 0x0017 (JMPREL) 0x4010d8
 0x0007 (RELA)   0x401090
 0x0008 (RELASZ) 72 (bytes)
 0x0009 (RELAENT)24 (bytes)
 0x6ffe (VERNEED)0x401000
 0x6fff (VERNEEDNUM) 4
 0x6ff0 (VERSYM) 0x400f5a
 0x (NULL)   0x0
taylor@taylor-NE510:~/Projects/PASCAL$ ./Gethello
./Gethello: error while loading shared libraries: libhello.so: 
cannot open shared object file: No such file or directory




Re: Computing the min() / max() of a slice of doubles.

2016-01-29 Thread Enjoys Math via Digitalmars-d-learn

On Saturday, 30 January 2016 at 04:13:09 UTC, Enjoys Math wrote:

I want to use std.algorithm.min/max,

how would I apply that to a slice of doubles and not a tuple of 
args?


Thanks.


Oh I got it:

import std.algorithm;

reduce!(max)(slice);

I'ma D wizard!



Re: Conditional nothrow/safe/nogc/etc?

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn
On Saturday, 30 January 2016 at 05:25:49 UTC, Rikki Cattermole 
wrote:

On 30/01/16 6:17 PM, Matt Elkins wrote:

[...]


templated functions have attribute inference. Meaning if it can 
be nothrow it will be.
Regarding your real use case, again struct if templated so it 
should be inferred.


Convenient! Thanks!


How do you get mouse movement info in GtkD?

2016-01-29 Thread Enjoys Math via Digitalmars-d-learn

I'm able to get the mouse click positions with event.button().x/y

But what .x/y do you query inside of an onMotionNotify event 
handler?


Thanks!


Re: Computing the min() / max() of a slice of doubles.

2016-01-29 Thread cym13 via Digitalmars-d-learn

On Saturday, 30 January 2016 at 04:13:09 UTC, Enjoys Math wrote:

I want to use std.algorithm.min/max,

how would I apply that to a slice of doubles and not a tuple of 
args?


Thanks.


Combine it with reduce:

import std.algorithm;

void main() {
double[] arr = [1.0, 2.1, 3.2, 4.3, 5.4];
assert(arr.reduce!max == 5.4);
assert(arr.reduce!min == 1.0);
}


Re: Can D interface with Free Pascal?

2016-01-29 Thread Taylor Hillegeist via Digitalmars-d-learn
On Saturday, 30 January 2016 at 04:35:29 UTC, Taylor Hillegeist 
wrote:

On Saturday, 30 January 2016 at 04:11:07 UTC, Mike Parker wrote:

[...]


Now I'm wishing that was the problem. Interestingly enough when 
i link to a C shared library it works... but also it isn't show 
in the needed shared library sections like below.


[...]


Acctually I made multiple mistakes. 0x000f (RPATH) 
Library rpath:[--export-dynamic] should be [lib]


Ill fix that and test again.


Re: Conditional nothrow/safe/nogc/etc?

2016-01-29 Thread Rikki Cattermole via Digitalmars-d-learn

On 30/01/16 6:17 PM, Matt Elkins wrote:

Is there any way to specify that a generic function is conditionally
nothrow (or other function decorators), based on whether the template
instantiation is nothrow? I'm looking for something akin to C++'s
noexcept(noexcept()), e.g.:

template  void foo() noexcept(noexcept(T())) {}

I don't see anything about it on the functions grammar page
(https://dlang.org/spec/function.html). I do see something to do with
nothrow_ on the std.traits page, but I'm not sure how to use it to
achieve this or whether that is the right approach.

My actual use case is a non-generic method opAssign inside of a generic
struct.


templated functions have attribute inference. Meaning if it can be 
nothrow it will be.
Regarding your real use case, again struct if templated so it should be 
inferred.


Re: Why is it a memory ERRO.

2016-01-29 Thread Dsby via Digitalmars-d-learn

Ok.Thank you.
and i want to know how to know when the GC start runing?


Re: Conditional nothrow/safe/nogc/etc?

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn

On Saturday, 30 January 2016 at 05:57:34 UTC, H. S. Teoh wrote:
A common idiom that we use is to write an attributed unittest 
to verify that the function itself is @safe/etc.. This way, if 
instantiated with safe/etc. types, the template will also be 
safe/etc., but if instantiated with an unsafe type, it will 
correspondingly be unsafe (instead of failing to compile if you 
wrote @safe on the template). The unittest ensures that you do 
not accidentally introduce un-@safe code into the template and 
cause *all* instantiations to become un-@safe.


auto mySafeCode(T)(T t) { ... }

@safe unittest
{
auto x = mySafeCode(safeValue);
}


T


Seems sound. Thanks!



Re: Can D interface with Free Pascal?

2016-01-29 Thread Taylor Hillegeist via Digitalmars-d-learn

On Friday, 29 January 2016 at 01:47:11 UTC, Mike Parker wrote:
On Thursday, 28 January 2016 at 19:49:22 UTC, Taylor Hillegeist 
wrote:

On Thursday, 28 January 2016 at 19:33:22 UTC, bearophile wrote:

FreeSlave:

On Thursday, 28 January 2016 at 08:15:38 UTC, FreeSlave wrote:
Not directly. You can declare cdecl function on Free Pascal 
side and call it as extern(C).


What about extern(Pascal)?
https://dlang.org/spec/attribute.html#linkage

Bye,
bearophile


Cool!, I did find this little gem. but still havent gotten a 
hello world to work. I need to figure out which libraries i 
need to include for fpc dependencies.


AFAIK, FreePascal does not use the pascal calling convention by 
default. If this page [1] is correct, the default convention is 
'register' and can be changed to something else (like pascal or 
cdecl) with a command-line switch [2].


[1] http://www.freepascal.org/docs-html/prog/progse22.html
[2] http://www.freepascal.org/docs-html/prog/progsu87.html




Working through a simple example. I tried the cdecl option but 
for some reason i can compile but when i run my Gethello it cant 
find the shared library in the same folder?


taylor@taylor-NE510:~/Projects/PASCAL$ ls
Gethello  Gethello.d  hello.pas  libhello.so
taylor@taylor-NE510:~/Projects/PASCAL$ cat Gethello.d
extern(C) void SubStr();

void main(){
SubStr();
}
taylor@taylor-NE510:~/Projects/PASCAL$ cat hello.pas
library subs;

procedure SubStr(); cdecl;

begin
  write('hello World');
end;

exports
  SubStr;

end.
taylor@taylor-NE510:~/Projects/PASCAL$ nm libhello.so
3ac0 T SubStr
taylor@taylor-NE510:~/Projects/PASCAL$ ./Gethello
./Gethello: error while loading shared libraries: libhello.so: 
cannot open shared object file: No such file or directory

===


Re: How do you get mouse movement info in GtkD?

2016-01-29 Thread Enjoys Math via Digitalmars-d-learn

On Saturday, 30 January 2016 at 06:33:55 UTC, Enjoys Math wrote:
I'm able to get the mouse click positions with 
event.button().x/y


But what .x/y do you query inside of an onMotionNotify event 
handler?


Thanks!


I see now:
bool onMouseMove(GdkEventMotion* eventMotion, Widget widget) {
//event.get
writeln("Mouse move event in scene.");
return true;
}

addOnMotionNotify()

There's also one that takes an Event param, but there's no 
obvious way to get the x/y info from that so I'll just use this 
lower level one which seems to work.


Re: UTF-16 endianess

2016-01-29 Thread Marek Janukowicz via Digitalmars-d-learn
On Fri, 29 Jan 2016 17:43:26 -0500, Steven Schveighoffer wrote:
>> Is there anything I should know about UTF endianess?
>
> It's not any different from other endianness.
>
> In other words, a UTF16 code unit is expected to be in the endianness of 
> the platform you are running on.
>
> If you are on x86 or x86_64 (very likely), then it should be little endian.
>
> If your source of data is big-endian (or opposite from your native 
> endianness), 

To be precise - my case is IMAP UTF7 folder name encoding and I finally found
out it's indeed big endian, which explains my problem (as I'm indeed on x86_64).

> it will have to be converted before treating as a wchar[].

Is there any clever way to do the conversion? Or do I need to swap the bytes
manually?

> Note the version identifiers BigEndian and LittleEndian can be used to 
> compile the correct code.

This solution is of no use to me as I don't want to change the endianess in
general.

-- 
Marek Janukowicz


Re: Relocatable objects and internal pointers

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn

On Saturday, 30 January 2016 at 01:18:33 UTC, Ali Çehreli wrote:
Definitely so. Rvalues are moved around all the time. The 
following program has two rvalue moves without calling 
post-blits or destructors.


Oi, that makes life tough. Ok, I'll figure something else out, 
then...


Thanks for the response!


Re: d plugin for Intelij Idea debuging support

2016-01-29 Thread Matt Elkins via Digitalmars-d-learn

On Friday, 29 January 2016 at 12:00:25 UTC, Pavel wrote:

Hello!

Is there any debuging support for Intelij Idea's D plugin?

Thanks!


I can't say for certain, but the website 
(https://github.com/kingsleyh/DLanguage) lists this as an 
upcoming feature by the end of 2016, so I think there probably 
isn't any support yet?


I use this plugin, too, it's pretty awesome.


Re: Compiling dmd -m64 on windows?

2016-01-29 Thread Tofu Ninja via Digitalmars-d-learn

On Friday, 29 January 2016 at 18:26:15 UTC, Tofu Ninja wrote:
For some reason it complains that link.exe is missing. Anyone 
know what's up?



dmd test.d



dmd test.d -m64

Can't run '\bin\link.exe', check PATH


link.exe is definitely on PATH...


where link.exe

C:\D\dmd2\windows\bin\link.exe


Re: opApply @safety

2016-01-29 Thread Steven Schveighoffer via Digitalmars-d-learn

On 1/29/16 12:44 PM, Chris Wright wrote:

I want to create an opApply for a type.

I've marked my code @safe, because everything I wrote was @safe. The body
of opApply is @safe, but it calls a delegate that may or may not be @safe.

How do I make it so I can iterate through this type safely and systemly?


Likely an overload. Tag the delegate as being @safe or not.

-Steve


Re: Compiling dmd -m64 on windows?

2016-01-29 Thread Adam D. Ruppe via Digitalmars-d-learn

On Friday, 29 January 2016 at 18:27:50 UTC, Tofu Ninja wrote:

where link.exe

C:\D\dmd2\windows\bin\link.exe


-m64 needs a different link.exe. It uses the Microsoft linker so 
you've gotta be sure that one is installed and the path of the VS 
bin is in there too.


The dmd install exe will do all this for you, but then you need 
to remember to run the "D2 64 bit command prompt" so the PATH is 
set rather than just any cmd.


Compiling dmd -m64 on windows?

2016-01-29 Thread Tofu Ninja via Digitalmars-d-learn
For some reason it complains that link.exe is missing. Anyone 
know what's up?



dmd test.d



dmd test.d -m64

Can't run '\bin\link.exe', check PATH


View model separation X and D.

2016-01-29 Thread Igor via Digitalmars-d-learn
Suppose I create a model in D and would like it to support a gui 
written in another language such as Qt C++ or WPF .NET.


Can anyone think of an efficient and very easy way to hook up the 
"bindings"? The gui doesn't need to be updated more than about 30 
times a second and it should run in it's own thread.


I would think a simple message queue would work that uses 
commands to tell the gui that value X has changed. The gui then 
checks the queue and updates the values visually. This should be 
quick except one needs to deal with potential multiple changes of 
the same value so the queue is not flooded with useless 
changes(changes that are not able to be displayed due to the fps 
limitation).


Does this seem relatively viable? It would need a rather minimal 
api and should be relatively fast?


The other problem of the gui updating the or changing the model 
is a bit harder but commands could also be used. Seems like most 
of the work would be done in creating the bindings to the model 
so the view can act on them. I imagine a simple syntax in the gui 
design could be used to bind view to model actions.


Any ideas on the subject?







Dub packages: Best practices for windows support

2016-01-29 Thread Johannes Pfau via Digitalmars-d-learn
I want to add proper windows support to the cairoD dub package. cairoD
is a wrapper for the [cairo](http://cairographics.org/) C library. As
it can be difficult to obtain cairo DLLs on windows I want to ship
these DLLs with cairoD. It is also possible to enable or disable
additional cairo features. I want to use the DLLs from the [MSYS2
project](http://msys2.github.io/) which enable all relevant features.
Because of that, the MSYS2 cairo DLL depends on _13_ other DLLs.

On linux it would be common practice to simply have a "libs": ["foo"]
entry in the dub configuration for cairoD. This way applications using
the library won't have to manually link the C library. And everything
(dub run, dub test) will just work.

Now on windows, things are more complicated. First of all, I can't seem
to simply use "libs": ["foo"] as the linker won't find the C
import .lib file. Then apparently there's no way to add a library search
path with the MSVC linker? So I have to use the full path:
"libs": [$PACKAGE_DIR\\path\\foo]. Without $PACKAGE_DIR paths are
incorrect for applications using the library because of a dub problem.
And then I'll have to use different import libraries and paths for -m32,
-m64 and -m32mscoff.

Additionally, applications can't run without the DLLs in the same
directory as the target application executable. So dub run and dub test
won't work. As a solution it is possible to do this in the cairoD dub
configuration:
"copyFiles": ["lib\\dmc32\\*.dll"]
The path again depends on -m32 vs -m64 and -m32mscoff



All this leads to the following questions:
* Should cairoD copy the DLLs for all applications using cairoD? This
  way simply adding a dependency will work. However, if users want to
  use a self compiled cairo DLL with fewer dependencies there's no easy
  way to disable the file copying?
* Should cairoD link in the .lib DLL import file? This might be useful
  even when not copying the DLLs. But if users want to link a custom
  import library that would be difficult. OTOH not copying DLLs and/or
  not linking the import library will make dub.json much more
  complicated for simple applications, especially if these applications
  want to support -m32, -m32mscoff and -m64.
* What's the best way to support all of -m32, -m32mscoff and -m64? I've
  got working import libraries and DLLs for all configurations, but how
  to support this in dub.json? I think the best way would be to have
  -ms32coff as a special architecture or flag for dub, but I can't seem
  to find any documentation about that. -m64 can be detected by x86_64
  in platforms, but how to detect -m32 vs -m32mscoff?

  Alternatively I could simply let users choose the configurations
  manually. But adding dflags: ["-m32mscoff"] does not build the
  Derelict dependencies with the m32mscoff flag so linking will fail...

  DFLAGS="-m32mscoff" doesn't work with dub test as the dub test
  command ignores the DFLAGS variable. I'd have to check whether it
  works for applications, but then there's still no way to use the
  correct cairo import library in cairoDs dub.json


Re: opApply @safety

2016-01-29 Thread Chris Wright via Digitalmars-d-learn
On Fri, 29 Jan 2016 14:00:08 -0500, Steven Schveighoffer wrote:

> On 1/29/16 12:44 PM, Chris Wright wrote:
>> I want to create an opApply for a type.
>>
>> I've marked my code @safe, because everything I wrote was @safe. The
>> body of opApply is @safe, but it calls a delegate that may or may not
>> be @safe.
>>
>> How do I make it so I can iterate through this type safely and
>> systemly?
> 
> Likely an overload. Tag the delegate as being @safe or not.
> 
> -Steve

That's handy. It works. I can make it so someone can call:
foo.opApply((i, k, v) @safe => 0);
foo.opApply((i, k, v) @system => 0);

And that works.

However, if you have:
@safe void bar() {
  foreach(i, k, v; foo) {
  }
}

the compiler complains:

opapplysafe.d(12): Error: foo.opApply matches more than one declaration:
opapplysafe.d(2): @safe int(int delegate(int, string, string) @safe 
dg)
and:
opapplysafe.d(5): @system int(int delegate(int, string, string) 
@system dg)

Guess I'll file a bug.


Re: View model separation X and D.

2016-01-29 Thread Igor via Digitalmars-d-learn

On Friday, 29 January 2016 at 20:04:59 UTC, Igor wrote:
Suppose I create a model in D and would like it to support a 
gui written in another language such as Qt C++ or WPF .NET.


Can anyone think of an efficient and very easy way to hook up 
the "bindings"? The gui doesn't need to be updated more than 
about 30 times a second and it should run in it's own thread.


I would think a simple message queue would work that uses 
commands to tell the gui that value X has changed. The gui then 
checks the queue and updates the values visually. This should 
be quick except one needs to deal with potential multiple 
changes of the same value so the queue is not flooded with 
useless changes(changes that are not able to be displayed due 
to the fps limitation).


Does this seem relatively viable? It would need a rather 
minimal api and should be relatively fast?


The other problem of the gui updating the or changing the model 
is a bit harder but commands could also be used. Seems like 
most of the work would be done in creating the bindings to the 
model so the view can act on them. I imagine a simple syntax in 
the gui design could be used to bind view to model actions.


Any ideas on the subject?



If the above is a good way, then the approach I would take is

I: Use attributes on properties to attach them to the message 
queue. All marked properties are automatically modified so they 
"add a message" to the queue. This should somehow be real 
fast(messages would be statically created).


II: Use attributes on methods and objects to export them so they 
can be called by the view.


The goal is to use attributes and allow the meta programming to 
do all the heavy lifting behind the scenes.


Sounds good? Anyone see any performance issues with this? My main 
goal is to avoid the model from being bogged down in step I.





Re: Dub packages: Best practices for windows support

2016-01-29 Thread Johannes Pfau via Digitalmars-d-learn
Am Fri, 29 Jan 2016 20:46:40 +0100
schrieb Johannes Pfau :

>   DFLAGS="-m32mscoff" doesn't work with dub test as the dub test
>   command ignores the DFLAGS variable. I'd have to check whether it
>   works for applications, but then there's still no way to use the
>   correct cairo import library in cairoDs dub.json

Should have mentioned DFLAGS is an environment in that example, e.g
using dub like this:

DFLAGS="-m32mscoff" dub run
DFLAGS="-m32mscoff" dub test