Re: how to debug memory errors

2016-11-07 Thread Era Scarecrow via Digitalmars-d-learn

On Tuesday, 8 November 2016 at 06:04:59 UTC, thedeemon wrote:
On Tuesday, 8 November 2016 at 05:36:22 UTC, Era Scarecrow 
wrote:


 Hmmm.. I had the impression that if something was referenced 
by another object, then it couldn't be collected,


Another *live* object, I.e. reachable from globals and stack. 
If you have a big tree and it becomes unreachable (you only had 
a pointer to its root and you nulled it), then this whole tree 
becomes garbage, and its nodes and leafs will be collected in 
unpredictable order, with destructors being run in 
unpredictable order, even when these dead nodes reference each 
other.


 And I can't help but hope it would start at the largest/base 
object and work it's way up. Or the largest object and then work 
it's way down. Alright...


 Shouldn't for warnings then in the destructor about accessing 
arrays, class objects or other allocated items that they might 
not even exist anymore?


 If I think of it like making a class/struct that does 
compression and the blob that manages tracking the compressed 
data uses simple array appending, and then the struct or class 
notices it's thrown away and it has an active connection to save 
it's contents to a file, as part of the destructor I'd probably 
write it so it would save and flush what data was left before 
deallocating everything or closing the file descriptors. With 
this you might have to manage your own memory to ensure the GC 
doesn't accidentally remove important data first...


Re: Thread (spawn) for object's method

2016-11-07 Thread Basile B. via Digitalmars-d-learn
On Monday, 7 November 2016 at 16:15:44 UTC, Konstantin Kutsevalov 
wrote:

Is there a way to make new thread for class method?

E.g. I have some class and I need to run one of them method in 
new thread.


I found wxamples only with function...



import core.thread;

class Foo
{
void method(){}
}

void main()
{
Foo foo = new Foo;
Thread t = new Thread(&foo.method);
}


Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Basile B. via Digitalmars-d-learn

On Monday, 7 November 2016 at 23:03:32 UTC, Picaud Vincent wrote:

 I need:

1/ a way to detect compile-time constant vs "dynamic" values


/**
 * Indicates if something is a value known at compile time.
 *
 * Params:
 *  V = The value to test.
 *  T = Optional, the expected value type.
 */
template isCompileTimeValue(alias V, T...)
if (T.length == 0 || (T.length == 1 && is(T[0])))
{
enum isKnown = is(typeof((){enum v = V;}));
static if (!T.length)
enum isCompileTimeValue = isKnown;
else
enum isCompileTimeValue = isKnown && is(typeof(V) == 
T[0]);

}
///
unittest
{
string a;
enum b = "0";
enum c = 0;
static assert(!isCompileTimeValue!a);
static assert(isCompileTimeValue!b);
static assert(isCompileTimeValue!c);
static assert(isCompileTimeValue!(b,string));
static assert(isCompileTimeValue!(c,int));
static assert(!isCompileTimeValue!(c,char));
static assert(!isCompileTimeValue!(char));
}




Re: how to debug memory errors

2016-11-07 Thread thedeemon via Digitalmars-d-learn

On Tuesday, 8 November 2016 at 05:36:22 UTC, Era Scarecrow wrote:

 Hmmm.. I had the impression that if something was referenced 
by another object, then it couldn't be collected,


Another *live* object, i.e. reachable from globals and stack.
If you have a big tree and it becomes unreachable (you only had a 
pointer to its root and you nulled it), then this whole tree 
becomes garbage, and its nodes and leafs will be collected in 
unpredictable order, with destructors being run in unpredictable 
order, even when these dead nodes reference each other.





Re: how to debug memory errors

2016-11-07 Thread Era Scarecrow via Digitalmars-d-learn
On Tuesday, 8 November 2016 at 03:27:32 UTC, Steven Schveighoffer 
wrote:
 Err that makes no sense... If that's the case why have a 
destructor at all?


To free non-GC resources.

http://dlang.org/spec/class.html#destructors

"Furthermore, the order in which the garbage collector calls 
destructors for unreference objects is not specified. This 
means that when the garbage collector calls a destructor for an 
object of a class that has members that are references to 
garbage collected objects, those references may no longer be 
valid. This means that destructors cannot reference sub 
objects."


 Hmmm.. I had the impression that if something was referenced by 
another object, then it couldn't be collected, so sub-objects 
shouldn't/couldn't be collected until the object holding them was 
dealt with (since it holds a reference).


 Although I suppose it's possible to rush in to the deepest 
levels and start collecting there first on objects presumed to be 
unneeded, but that just _feels_ wrong.


Re: how to debug memory errors

2016-11-07 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/6/16 11:01 PM, thedeemon wrote:

On Monday, 7 November 2016 at 02:22:35 UTC, Steven Schveighoffer wrote:

OP: it's not legal to destroy or even access GC allocated members in a
destructor. The GC may have already destroyed that data.


Isn't destroy() fine there? It doesn't call destructors for already
destroyed objects, so I guess it should be safe. (assuming the
destructors don't do any allocations)


The problem is that you don't know when the GC has destroyed that 
object. It may have been freed and already reallocated to something 
else. The time between when your object becomes garbage and when it's 
collected is not explicitly defined. Nor is the order of collection or 
if it will even be collected at all.


Another possibility is that your object destroys something that is 
pointed at by someone else. This is not a horrible condition, but could 
result in some unwanted segfaults.


Hence, just don't access members from the destructor. You'll be glad you 
didn't.


-Steve


Re: how to debug memory errors

2016-11-07 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/6/16 10:57 PM, Era Scarecrow wrote:

On Monday, 7 November 2016 at 02:22:35 UTC, Steven Schveighoffer wrote:

OP: it's not legal to destroy or even access GC allocated members in a
destructor. The GC may have already destroyed that data. I would
recommend printing the stack trace when you get the exception, and
figure out where the culprit is.


 Err that makes no sense... If that's the case why have a destructor
at all?


To free non-GC resources.

http://dlang.org/spec/class.html#destructors

"Furthermore, the order in which the garbage collector calls destructors 
for unreference objects is not specified. This means that when the 
garbage collector calls a destructor for an object of a class that has 
members that are references to garbage collected objects, those 
references may no longer be valid. This means that destructors cannot 
reference sub objects."


-Steve


Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

On Monday, 7 November 2016 at 23:07:27 UTC, Picaud Vincent wrote:

typo...
auto capacity = max(0,(size_-1)*stride_+1);


To be more correct I have something like:

alias IntergralConstant!(int,0) Zero_c;
alias IntergralConstant!(int,1) One_c;

auto capacity = max(Zero_c,(size_-One_c)*stride_+One_c);

with "smooth" implicit conversion IntegralConstant -> int for 
cases where size_ or stride_ are "int" and not both 
IntegralConstant types.




Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

typo...
auto capacity = max(0,(size_-1)*stride_+1);



Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

On Monday, 7 November 2016 at 22:18:56 UTC, Jerry wrote:
On Monday, 7 November 2016 at 21:37:50 UTC, Picaud Vincent 
wrote:
  static if ( isIntegralConstant!(typeof(required_capacity()) 
)

{
}
else
{
}

}


Premature post send by error sorry Well something like:

   static if ( isIntegralConstant!(typeof(required_capacity()) 
)

 ElementType[required_capacity()] data_;
   else
 ElementType[] data_;
}

For that, at least in C++, I need integral_constant<> type 
with compile-time arithmetic and smooth integration with 
"usual" size_t/ptrdiff_t types.


2/ I also would like to test some implementations concerning 
automatic differentiation.

I have my own C++ libs, inspired, but ~20% faster than Adept:
http://www.met.reading.ac.uk/clouds/adept/
and I would like to know how I can do that in D

Well... That is the idea... I hope I will get some results and 
I will be happy to share if it is something interesting.


Vincent


Ah I get what you mean, you can do that without using a special 
type.


struct Vector(T, Args...) if(Args.length == 1)
{
static if(is(Args[0] == size_t))
{
size_t size;
}
else static if(Args[0] != 0) // would error if it's a 
type that's not size_t

{
enum size = Args[0];
}
else
{
static assert(0);
}
}

Vector!(int, 10) a;
Vector!(int, size_t) b; // both work with IntegralConstant

could use __traits(compiles) to see if it's not a type, for 
that second static if. Which would probably be better, so if 
you pass a float or something, it won't give a weird error.


Thank you again Jerry!

For sure my way of thinking is twisted by my C++ habits! :-/

The positive point is that D seems to offer much shorter 
solutions (this is my hope).


However I still need some investigations and/or some guidance:

-> not sure that it is ok for me as I really want to track 
"static constants" all the

   way long.
   That is the reason why I introduced the IntegralConstant type
   (with operator overloading, work in progress)

For instance, the code:

 enum int a=1,b=2;
 auto c = a+b;

 pragma(msg,typeof(c));   // prints "int"
 static assert(c==3); // compilation fails: "variable c 
cannot be read at compile time"


To implement my vector structs I need:

1/ a way to detect compile-time constant vs "dynamic" values
2/ to perform and to propagate compile-time constants across 
"arithmetic" computations.
   For instance to compute the required capacity to store vector 
data, I need something

like

auto capacity = max(0,(size_-1)*stride_);

and this expression must make sense for both "dynamic" values and 
compile-time constant.


In one case I expect
   typeof(capacity) -> int,
in the other
   typeof(capacity) -> IntegralConst



Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

On Monday, 7 November 2016 at 18:38:14 UTC, ag0aep6g wrote:

I've reduced it to this:


void main() {}
void f()
{
import core.atomic: atomicOp;
shared size_t workUnitIndex;
atomicOp!"+="(workUnitIndex, 1);
}


Which crashes when compiled with -profile. Looks like issue 
14511 covers this (comment 5):

https://issues.dlang.org/show_bug.cgi?id=14511#c5


Ok... I'm impressed. Thanks for clarification :)
But something changed nevertheless... I have the problem only 
since the update from 2.071.2 to 2.072.0.

Is this worth mentioning in a comment of the issue somehow?


Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Jerry via Digitalmars-d-learn

On Monday, 7 November 2016 at 21:37:50 UTC, Picaud Vincent wrote:

  static if ( isIntegralConstant!(typeof(required_capacity()) )
{
}
else
{
}

}


Premature post send by error sorry Well something like:

   static if ( isIntegralConstant!(typeof(required_capacity()) )
 ElementType[required_capacity()] data_;
   else
 ElementType[] data_;
}

For that, at least in C++, I need integral_constant<> type with 
compile-time arithmetic and smooth integration with "usual" 
size_t/ptrdiff_t types.


2/ I also would like to test some implementations concerning 
automatic differentiation.

I have my own C++ libs, inspired, but ~20% faster than Adept:
http://www.met.reading.ac.uk/clouds/adept/
and I would like to know how I can do that in D

Well... That is the idea... I hope I will get some results and 
I will be happy to share if it is something interesting.


Vincent


Ah I get what you mean, you can do that without using a special 
type.


struct Vector(T, Args...) if(Args.length == 1)
{
static if(is(Args[0] == size_t))
{
size_t size;
}
else static if(Args[0] != 0) // would error if it's a 
type that's not size_t

{
enum size = Args[0];
}
else
{
static assert(0);
}
}

Vector!(int, 10) a;
Vector!(int, size_t) b; // both work with IntegralConstant

could use __traits(compiles) to see if it's not a type, for that 
second static if. Which would probably be better, so if you pass 
a float or something, it won't give a weird error.


Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

On Monday, 7 November 2016 at 21:23:37 UTC, Picaud Vincent wrote:

On Monday, 7 November 2016 at 18:59:24 UTC, Jerry wrote:
On Monday, 7 November 2016 at 18:42:37 UTC, Picaud Vincent 
wrote:

template isIntegralConstant(ANY)
{
enum bool 
isIntegralConstant=__traits(identifier,ANY)=="IntegralConstant";

}


A bit more elegant way of doing that would be:

enum isIntegralConstant(T) = is(T : IntegralConstant!U, U...);


I would be very graceful for any help/advice that explains 
the right way to implement C++ std::integral_constantvalue> in the D language.


Vincent


Now the question is, do you really need IntegralConstant? I've 
never used it in C++ so I don't really know any of the use 
cases for it. But generally in D if you need something to be a 
compile time constant value you can just use "enum". It can be 
any type as well, so long as it can be evaluated at compile 
time.


enum long someConstant = 1 << 32;


Hi Jerry,

Thank you so much for your quick answer! I tried your 
suggestion and it works.


My main interest is numerical computations. I have some C++ 
libs using meta-programming and I want to see how I can 
translate some parts in D. The goal is to check: productivity & 
code readability & performance. I will try to implement 2 toy 
examples:


1/ A basic example of strided dense vector structure dealing 
with the dynamic/static size in an uniform way. In D I thing 
this can be done with something like this (not tried yet to 
compile it, but that is the idea to mimick my C++ 
implementation)


struct Vector(T,SIZE,STRIDE) if( 
(is(SIZE==size_t)||isIntegralConstant!SIZE) ...)

{
  alias T ElementType;

  private SIZE size_;
  private STRIDE stride_;

  ...

  auto required_capacity() { return size_*stride_; } // return 
a size_t or a IntegralConst


  static if ( isIntegralConstant!(typeof(required_capacity()) )
{
}
else
{
}

}


Premature post send by error sorry Well something like:

   static if ( isIntegralConstant!(typeof(required_capacity()) )
 ElementType[required_capacity()] data_;
   else
 ElementType[] data_;
}

For that, at least in C++, I need integral_constant<> type with 
compile-time arithmetic and smooth integration with "usual" 
size_t/ptrdiff_t types.


2/ I also would like to test some implementations concerning 
automatic differentiation.

I have my own C++ libs, inspired, but ~20% faster than Adept:
http://www.met.reading.ac.uk/clouds/adept/
and I would like to know how I can do that in D

Well... That is the idea... I hope I will get some results and I 
will be happy to share if it is something interesting.


Vincent



Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

On Monday, 7 November 2016 at 18:59:24 UTC, Jerry wrote:
On Monday, 7 November 2016 at 18:42:37 UTC, Picaud Vincent 
wrote:

template isIntegralConstant(ANY)
{
enum bool 
isIntegralConstant=__traits(identifier,ANY)=="IntegralConstant";

}


A bit more elegant way of doing that would be:

enum isIntegralConstant(T) = is(T : IntegralConstant!U, U...);


I would be very graceful for any help/advice that explains the 
right way to implement C++ std::integral_constant 
in the D language.


Vincent


Now the question is, do you really need IntegralConstant? I've 
never used it in C++ so I don't really know any of the use 
cases for it. But generally in D if you need something to be a 
compile time constant value you can just use "enum". It can be 
any type as well, so long as it can be evaluated at compile 
time.


enum long someConstant = 1 << 32;


Hi Jerry,

Thank you so much for your quick answer! I tried your suggestion 
and it works.


My main interest is numerical computations. I have some C++ libs 
using meta-programming and I want to see how I can translate some 
parts in D. The goal is to check: productivity & code readability 
& performance. I will try to implement 2 toy examples:


1/ A basic example of strided dense vector structure dealing with 
the dynamic/static size in an uniform way. In D I thing this can 
be done with something like this (not tried yet to compile it, 
but that is the idea to mimick my C++ implementation)


struct Vector(T,SIZE,STRIDE) if( 
(is(SIZE==size_t)||isIntegralConstant!SIZE) ...)

{
  alias T ElementType;

  private SIZE size_;
  private STRIDE stride_;

  ...

  auto required_capacity() { return size_*stride_; } // return a 
size_t or a IntegralConst


  static if ( isIntegralConstant!(typeof(required_capacity()) )
{
}
else
{
}

}


Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn
On Monday, 7 November 2016 at 21:05:32 UTC, Jonathan M Davis 
wrote:


No. @trusted. The calling function could only be marked @safe 
if the callee were @trusted, and I was suggesting that it be 
marked @system so that it's then clear to the caller that they 
need to pass the correct arguments for it to be okay to treat 
it as @safe and mark the caller as @trusted. If need be, the 
contract can be documented to make it clear what's required for 
it to be reasonable to mark the caller as @trusted.


- Jonathan M Davis


Oh, I see. I think I prefer to use the modified enforce trough 
(see above), so I have no need to make @trusted layers in the 
calling site. Thanks anyway.





Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Jonathan M Davis via Digitalmars-d-learn
On Monday, November 07, 2016 20:38:00 Somebody via Digitalmars-d-learn 
wrote:
> > So, while I don't know what the official stance is, I'd suggest
> > having the function be @trusted and having the documentation
> > make it clear what the preconditions are so that the calling
> > function can be marked @trusted.
> >
> I reckon you meant marking the calling function @safe?

No. @trusted. The calling function could only be marked @safe if the callee
were @trusted, and I was suggesting that it be marked @system so that it's
then clear to the caller that they need to pass the correct arguments for it
to be okay to treat it as @safe and mark the caller as @trusted. If need be,
the contract can be documented to make it clear what's required for it to be
reasonable to mark the caller as @trusted.

- Jonathan M Davis



Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn

On Monday, 7 November 2016 at 20:42:26 UTC, ag0aep6g wrote:


Apparently, yes: `version (D_NoBoundsChecks)`.

http://dlang.org/spec/version.html#predefined-versions


You're probably aware of it, but just to be sure: Note that 
-noboundscheck (or -boundscheck=off) absolutely breaks safety.


Yes I am. Using that is in my understanding unwise in any trivial 
project. Thanks for your help and the warning. This anyway seems 
to let choose the best tradeoff when compiling, unlike enforce, 
assert in @system or my original contracted version.





Re: Are contracts intended for verifying @safety;

2016-11-07 Thread ag0aep6g via Digitalmars-d-learn

On 11/07/2016 09:16 PM, Somebody wrote:

Can the version switch be used to detect noboundscheck?


Apparently, yes: `version (D_NoBoundsChecks)`.

http://dlang.org/spec/version.html#predefined-versions


I was thinking
that if, it could be used to make an overload of enforce that acts just
like in your example, but is taken off with bounds checking. Then it
would not violate safety any more than arrays do, yet could be compiled
to as efficient a release build as the contract version, if needed.


You're probably aware of it, but just to be sure: Note that 
-noboundscheck (or -boundscheck=off) absolutely breaks safety.


Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn
On Monday, 7 November 2016 at 20:24:25 UTC, Jonathan M Davis 
wrote:


That's a matter of debate. What you're saying is that the 
contract for the function requires certain conditions be true 
for the function arguments, and if they are true, then the 
function is @safe. And that's legitimate. But at the same time, 
it doesn't absolutely guarantee @safety, because if the caller 
passes arguments that violate the contract, and the function is 
compiled with -release, then unsafe things will occur. So, you 
could mark the function as @system, and then make it clear in 
the documentation that the function's @safety depends on the 
function's arguments meeting the pre-condition. So, the caller 
then knows when they can mark the call as being @trusted.


There have been several discussions about @trusted over the 
last couple of years (both in the newsgroup and on github), and 
I don't know what the official stance on this sort of thing 
currently is. I know that at one point, it was argued that 
@trusted functions were @safe so long as their arguments were 
valid, but then you get stuff like


auto foo(int* arr, size_t index) @trusted
{
return *(arr + index);
}

or

auto foo(int* arr, size_t length) @trusted
{
return arr[0 .. length];
}

or

auto foo(int[], size_t index) @trusted
{
return *(arr.ptr + index);
}

and it doesn't seem like a good idea to me to mark functions 
like that as @trusted. It's too much like you're trying to have 
array indexing be marked as @trusted while circumventing the 
array bounds checks without any guarantee that the values are 
going to be valid.





All pure functions which a programmer, save for a blackhat 
perhaps, has any reason to use are @safe with correct arguments. 
So we would have no use for @safe when we have @pure, were that 
argument about arguments wise to follow. So I agree with you that 
they definitely would be a bad idea without contracts. However, 
with contracts, as you said, it is less clear.


So, while I don't know what the official stance is, I'd suggest 
having the function be @trusted and having the documentation 
make it clear what the preconditions are so that the calling 
function can be marked @trusted.


- Jonathan M Davis


I reckon you meant marking the calling function @safe?



Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Jonathan M Davis via Digitalmars-d-learn
On Monday, November 07, 2016 17:30:09 Somebody via Digitalmars-d-learn 
wrote:
> void moveFrom(int[] a, in int[] b) @trusted in{
>  assert(a.length >= b.length);
> } body {
>  memmove(cast(void*)a.ptr, cast(void*)b.ptr, b.length *
> int.sizeof);
> }
>
> Is this ok? And if not, how should it be done, preferably without
> changing the condition or memmove call?

That's a matter of debate. What you're saying is that the contract for the
function requires certain conditions be true for the function arguments, and
if they are true, then the function is @safe. And that's legitimate. But at
the same time, it doesn't absolutely guarantee @safety, because if the
caller passes arguments that violate the contract, and the function is
compiled with -release, then unsafe things will occur. So, you could mark
the function as @system, and then make it clear in the documentation that
the function's @safety depends on the function's arguments meeting the
pre-condition. So, the caller then knows when they can mark the call as
being @trusted.

There have been several discussions about @trusted over the last couple of
years (both in the newsgroup and on github), and I don't know what the
official stance on this sort of thing currently is. I know that at one
point, it was argued that @trusted functions were @safe so long as their
arguments were valid, but then you get stuff like

auto foo(int* arr, size_t index) @trusted
{
return *(arr + index);
}

or

auto foo(int* arr, size_t length) @trusted
{
return arr[0 .. length];
}

or

auto foo(int[], size_t index) @trusted
{
return *(arr.ptr + index);
}

and it doesn't seem like a good idea to me to mark functions like that as
@trusted. It's too much like you're trying to have array indexing be marked
as @trusted while circumventing the array bounds checks without any
guarantee that the values are going to be valid.

So, while I don't know what the official stance is, I'd suggest having the
function be @trusted and having the documentation make it clear what the
preconditions are so that the calling function can be marked @trusted.

- Jonathan M Davis



Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn
...and it would, unlike enforce(), of course throw an Error 
instead of an Exception.


Re: Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn

On Monday, 7 November 2016 at 19:30:01 UTC, ag0aep6g wrote:
No, it's not ok. Contracts and (most) asserts are not included 
in release builds, but the rules for @safe/@trusted don't 
change. So you'd be breaking @safe in release builds.


You can use std.exception.enforce instead, in the body instead 
of a contract:


void moveFrom(int[] a, in int[] b) @trusted
{
import std.exception: enforce;
enforce(a.length >= b.length);
memmove(/* ... as above ... */);
}


Can the version switch be used to detect noboundscheck? I was 
thinking that if, it could be used to make an overload of enforce 
that acts just like in your example, but is taken off with bounds 
checking. Then it would not violate safety any more than arrays 
do, yet could be compiled to as efficient a release build as the 
contract version, if needed.


Re: Are contracts intended for verifying @safety;

2016-11-07 Thread ag0aep6g via Digitalmars-d-learn

On 11/07/2016 06:30 PM, Somebody wrote:

void moveFrom(int[] a, in int[] b) @trusted in{
assert(a.length >= b.length);
} body {
memmove(cast(void*)a.ptr, cast(void*)b.ptr, b.length * int.sizeof);
}

Is this ok? And if not, how should it be done, preferably without
changing the condition or memmove call?


No, it's not ok. Contracts and (most) asserts are not included in 
release builds, but the rules for @safe/@trusted don't change. So you'd 
be breaking @safe in release builds.


You can use std.exception.enforce instead, in the body instead of a 
contract:


void moveFrom(int[] a, in int[] b) @trusted
{
import std.exception: enforce;
enforce(a.length >= b.length);
memmove(/* ... as above ... */);
}


Re: New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Jerry via Digitalmars-d-learn

On Monday, 7 November 2016 at 18:42:37 UTC, Picaud Vincent wrote:

template isIntegralConstant(ANY)
{
enum bool 
isIntegralConstant=__traits(identifier,ANY)=="IntegralConstant";

}


A bit more elegant way of doing that would be:

enum isIntegralConstant(T) = is(T : IntegralConstant!U, U...);


I would be very graceful for any help/advice that explains the 
right way to implement C++ std::integral_constant in 
the D language.


Vincent


Now the question is, do you really need IntegralConstant? I've 
never used it in C++ so I don't really know any of the use cases 
for it. But generally in D if you need something to be a compile 
time constant value you can just use "enum". It can be any type 
as well, so long as it can be evaluated at compile time.


enum long someConstant = 1 << 32;




New to D and mimicking C++ : how to implement std::integral_constant<>?

2016-11-07 Thread Picaud Vincent via Digitalmars-d-learn

Hi all,

I have ~15y of C++ and now I want to test D, because it seems 
really intersting and "cleaner" than C++.


As an exercice I m trying to implement something equivalent to 
the C++ std::integral_constant in D.


In D:

struct IntegralConstant(T, T VALUE) {
 ...
}

But I do not know how to write a compile-time type check. I tried

template isIntegralConstant(ANY)
{
enum bool 
isIntegralConstant=__traits(identifier,ANY)=="IntegralConstant";

}

But when using it with ANY=long type, I get a compile-time error:

"argument long has no identifier"

A workaround that worked is:

struct IntegralConstantTag {}

struct IntegralConstant(T, T VALUE) {
  private IntegralConstantTag selfTag_;
  alias selfTag_ this;
}

template isIntegralConstant(ANY)
{
enum bool isIntegralConstant=is(ANY : IntegralConstantTag);
}

But now I'm sticked by a compiler issue when I want to introduce 
2 "alias this" to allow implicit conversion:


struct IntegralConstant(T, T VALUE) {
  private IntegralConstantTag selfTag_;
  alias selfTag_ this;
  T value_=VALUE;
  alias value_ this;
}

Compiler error message is "integralConstant.d:16:3: error: there 
can be only one alias this".



I would be very graceful for any help/advice that explains the 
right way to implement C++ std::integral_constant in 
the D language.


Vincent



Re: Bug after update to 2.072?

2016-11-07 Thread ag0aep6g via Digitalmars-d-learn

On 11/07/2016 06:18 PM, Alex wrote:

On Monday, 7 November 2016 at 17:12:32 UTC, Alex wrote:


dmd -c -of./app.o -debug -g -gc -O -profile -w ./app.d -vcolumns
dmd -of./app ./app.o -g -gc


Knowing this, I tried to find the option which does the difference. This
was the profile option. So, if I omit it, the segmentation fault is gone...


I've reduced it to this:


void main() {}
void f()
{
import core.atomic: atomicOp;
shared size_t workUnitIndex;
atomicOp!"+="(workUnitIndex, 1);
}


Which crashes when compiled with -profile. Looks like issue 14511 covers 
this (comment 5):

https://issues.dlang.org/show_bug.cgi?id=14511#c5


Are contracts intended for verifying @safety;

2016-11-07 Thread Somebody via Digitalmars-d-learn

void moveFrom(int[] a, in int[] b) @trusted in{
assert(a.length >= b.length);
} body {
memmove(cast(void*)a.ptr, cast(void*)b.ptr, b.length * 
int.sizeof);

}

Is this ok? And if not, how should it be done, preferably without 
changing the condition or memmove call?


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:55:29 UTC, Alex wrote:

Ok... Another point is, that I'm using dub and trying compiling 
my app directly by dmd does not yield the error.
So, I have to attach the compiling commands, which I see, when 
tried

dub build --force -v

dmd -c -of./app.o -debug -g -gc -O -profile -w ./app.d -vcolumns
dmd -of./app ./app.o -g -gc


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

On Monday, 7 November 2016 at 17:12:32 UTC, Alex wrote:


dmd -c -of./app.o -debug -g -gc -O -profile -w ./app.d -vcolumns
dmd -of./app ./app.o -g -gc


Knowing this, I tried to find the option which does the 
difference. This was the profile option. So, if I omit it, the 
segmentation fault is gone...


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Heisenberg via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:54:06 UTC, Ali Çehreli wrote:

On 11/07/2016 08:40 AM, Heisenberg wrote:

[...]


Exactly how it happens requires explaining a long chain of 
function calls. Probably that's why the author did not 
elaborate further. ;) I've probably omitted some steps here but 
I think the following is close enough:


- writeln() that's in the sample code calls write() with the 
addition of '\n'.


- write() eventually calls formattedWrite() with a 
lockingTextWriter as the writer:


  https://github.com/dlang/phobos/blob/master/std/stdio.d#L1401

- formattedWrite() calls formatValue():

  https://github.com/dlang/phobos/blob/master/std/format.d#L2906

- formatValue() calls formatObject() and that's the one that 
makes a distinction between different overloads of toString():


  https://github.com/dlang/phobos/blob/master/std/format.d#L2805

- formatObject() calls put(), which finally uses the 'sink' 
parameter as an output range and fills in with characters.


Ali


I see now. :) Sounds like I have to finish the whole book to be 
able to grasp all of that a little better. I think I do get a 
general picture now, though. Thanks for a quick reply, everyone!


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn
Ok, ok. Here, I pasted the code, minimized as far as I could. 
There are 434 lines of code, sorry.

http://pastebin.com/UcZUc79g

The main is empty. This is intended. I still have the 
segmentation fault.


Maybe, I have another hint:
If I comment all the attributes in the
private HeadUnshared!(T) atomicFetchAdd(T, V1)( ref shared T val, 
V1 mod ) //pure nothrow @nogc @trusted

method in atomic.d, in line 657, away, and add something like
import std.stdio;
writeln("kuku");
at the first lines of the body
I get an error message on compiling:

/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/core/atomic.d(722,46): Error: pure 
function 'core.atomic.atomicOp!("+=", ulong, int).atomicOp' cannot call impure 
function 'core.atomic.atomicFetchAdd!(ulong, int).atomicFetchAdd'
/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/core/atomic.d(722,46): Error: @nogc 
function 'core.atomic.atomicOp!("+=", ulong, int).atomicOp' cannot call 
non-@nogc function 'core.atomic.atomicFetchAdd!(ulong, int).atomicFetchAdd'
/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/core/atomic.d(722,46): Error: 
function 'core.atomic.atomicFetchAdd!(ulong, int).atomicFetchAdd' is not nothrow
/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/core/atomic.d(692,22): Error: nothrow 
function 'core.atomic.atomicOp!("+=", ulong, int).atomicOp' may throw
/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/std/parallelism.d-mixin-3786(3812,50): 
Error: template instance core.atomic.atomicOp!("+=", ulong, int) error 
instantiating
/usr/local/Cellar/dmd/2.072.0/include/dlang/dmd/std/parallelism.d(3309,1):  
  instantiated from here: ParallelForeach!(double[][])
source/app.d(143,41):instantiated from here: 
parallel!(double[][])
source/app.d(20,34):instantiated from here: 
crs2!(crs2Fun02, crs2Params!(OptInit))


Maybe, this doesn't say anything about the segmentation error. 
But the last two lines are, maybe a hint, which route is taken on 
compilation.


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Ali Çehreli via Digitalmars-d-learn

On 11/07/2016 08:40 AM, Heisenberg wrote:

On Monday, 7 November 2016 at 16:33:30 UTC, Adam D. Ruppe wrote:

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:

Why? How can a delegate which returns nothing be used as an array
which is going to be printed on the screen?


You pass the string to the delegate, which does whatever with it
somewhere else.

So you call: `passed_delegate("your string");` and it can forward it
to writeln or whatever.


But how does it forward it if it's:


void delegate(const(char)[]) sink // ?


It returns nothing, and just takes an array of characters as a
parameter.. Just how does it print?..


Exactly how it happens requires explaining a long chain of function 
calls. Probably that's why the author did not elaborate further. ;) I've 
probably omitted some steps here but I think the following is close enough:


- writeln() that's in the sample code calls write() with the addition of 
'\n'.


- write() eventually calls formattedWrite() with a lockingTextWriter as 
the writer:


  https://github.com/dlang/phobos/blob/master/std/stdio.d#L1401

- formattedWrite() calls formatValue():

  https://github.com/dlang/phobos/blob/master/std/format.d#L2906

- formatValue() calls formatObject() and that's the one that makes a 
distinction between different overloads of toString():


  https://github.com/dlang/phobos/blob/master/std/format.d#L2805

- formatObject() calls put(), which finally uses the 'sink' parameter as 
an output range and fills in with characters.


Ali



Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Heisenberg via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:37:50 UTC, Mathias Lang wrote:

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:

[...]


When you ask for a string (or more generally, an array), you 
put a specific construct on the way the data should be. For 
starters, the items have to be contiguous in memory. But most 
of the time, they aren't, and you end up allocating memory to 
put them contiguously.


[...]


I see.. So we're basically adding stuff to it and then printing 
it all in one go. Still, the delegate in the example isn't 
defined, so how does it manage to output the result?


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Heisenberg via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:33:30 UTC, Adam D. Ruppe wrote:

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:
Why? How can a delegate which returns nothing be used as an 
array which is going to be printed on the screen?


You pass the string to the delegate, which does whatever with 
it somewhere else.


So you call: `passed_delegate("your string");` and it can 
forward it to writeln or whatever.


But how does it forward it if it's:


void delegate(const(char)[]) sink // ?


It returns nothing, and just takes an array of characters as a 
parameter.. Just how does it print?..


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Mathias Lang via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:
Hi there. I'm currently following Ali Çehreli's "Programming in 
D" book and I can't seem to be able to wrap my head around the 
of delegates in the toString() functions..


http://ddili.org/ders/d.en/lambda.html
(Bottom of the page)


Why? How can a delegate which returns nothing be used as an 
array which is going to be printed on the screen? And just how 
is it printed? The Documentation didn't make it much clearer.. 
the 'sink' is supposed to be the 'writer', isn't it? So what 
does it do? The arguments get interpreted and formatted into 
the string, but what happens after that?


P.S. I've just checked the book, it doesn't seem to be 
explained anywhere properly (the way formattedRead is)

P.P.S. I'm following the PDF version of the book


When you ask for a string (or more generally, an array), you put 
a specific construct on the way the data should be. For starters, 
the items have to be contiguous in memory. But most of the time, 
they aren't, and you end up allocating memory to put them 
contiguously.


A sink is a method to work around that problem. A simple example 
would be:


```
import std.stdio;

void main ()
{
   // A delegate that write to stdout
   auto dg = (const(char)[] v) { write(v); }
   ColoredPoint p;
   p.toString(dg);
   write("\n");
}
```

With this definition, every time `ColoredPoint` will want to 
output a chunk of data, it will call the delegate, which will 
print to stdout. When the function returns, we now all chunks 
have been appended, and we complete the line with a \n, flushing 
the output.


This is great to write memory-friendly algorithm:

```
void main ()
{
   AppendBuffer!char myBuffer;
   auto dg = (const(char)[] v) { myBuffer ~= v; }
   ColoredPoint p;
   p.toString(dg);
   // Now we can use myBuffer.data
}
```

With this example, you can see that, by just forwarding chunks to 
the delegate, we're able to let the caller to decide of the 
memory strategy to use. It can be plain GC allocation, it can be 
using `malloc` / `realloc`, it can use a static array and only 
aggregate up to a certain size, etc...


Re: Can't understand the application of delegates in toString() functions

2016-11-07 Thread Adam D. Ruppe via Digitalmars-d-learn

On Monday, 7 November 2016 at 16:22:17 UTC, Heisenberg wrote:
Why? How can a delegate which returns nothing be used as an 
array which is going to be printed on the screen?


You pass the string to the delegate, which does whatever with it 
somewhere else.


So you call: `passed_delegate("your string");` and it can forward 
it to writeln or whatever.


Can't understand the application of delegates in toString() functions

2016-11-07 Thread Heisenberg via Digitalmars-d-learn
Hi there. I'm currently following Ali Çehreli's "Programming in 
D" book and I can't seem to be able to wrap my head around the of 
delegates in the toString() functions..


http://ddili.org/ders/d.en/lambda.html
(Bottom of the page)

We have defined many toString() functions up to this point in 
the book to represent objects as strings. Those toString() 
definitions all returned a string without taking any 
parameters. As noted by the comment lines below, structs and 
classes took advantage of toString() functions of their 
respective members by simply passing those members to format():



... code ...


In order for polygon to be sent to the output as a string on 
the last line of the program, all of the toString() functions 
of Polygon, ColoredPoint, Color, and Point are called 
indirectly, creating a total of 10 strings in the process. Note 
that the strings that are constructed and returned by the 
lower-level functions are used only once by the respective 
higher-level function that called them.


Okay, I get it.

However, although a total of 10 strings get constructed, only 
the very last one is printed to the output:


[{RGB:10,10,10;(1,1)}, {RGB:20,20,20;(2,2)}, 
{RGB:30,30,30;(3,3)}]


However practical, this method may degrade the performance of 
the program because of the many string objects that are 
constructed and promptly thrown away.


I can see the reasoning behind this. But ..

However practical, this method may degrade the performance of 
the program because of the many string objects that are 
constructed and promptly thrown away.


An overload of toString() avoids this performance issue by 
taking a delegate parameter:


CODE: void toString(void delegate(const(char)[]) sink) const;

As seen in its declaration, this overload of toString() does 
not return a string. Instead, the characters that are going to 
be printed are passed to its delegate parameter. It is the 
responsibility of the delegate to append those characters to 
the single string that is going to be printed to the output.


All the programmer needs to do differently is to call 
std.format.formattedWrite instead of std.string.format and pass 
the delegate parameter as its first parameter:


Why? How can a delegate which returns nothing be used as an array 
which is going to be printed on the screen? And just how is it 
printed? The Documentation didn't make it much clearer.. the 
'sink' is supposed to be the 'writer', isn't it? So what does it 
do? The arguments get interpreted and formatted into the string, 
but what happens after that?


P.S. I've just checked the book, it doesn't seem to be explained 
anywhere properly (the way formattedRead is)

P.P.S. I'm following the PDF version of the book


Thread (spawn) for object's method

2016-11-07 Thread Konstantin Kutsevalov via Digitalmars-d-learn

Is there a way to make new thread for class method?

E.g. I have some class and I need to run one of them method in 
new thread.


I found wxamples only with function...


Re: Floating-point Modulus math.fmod

2016-11-07 Thread Fendercaster via Digitalmars-d-learn

On Monday, 7 November 2016 at 09:21:11 UTC, Ilya Yaroshenko wrote:

On Sunday, 6 November 2016 at 21:45:28 UTC, Fendercaster wrote:
I'm not quite sure if this is the right forum to ask this 
question:
I've been trying to implement the "floating-point modulus" 
function from the math library. Equivalently that's what I've 
tried in Python too. Problem is - the results are different 
and not even close. Please have a look at both snippets. Maybe 
someone can help me out:


[...]


Python uses 64-bit doubles. You may want to try with `double` 
and `core.stdc.tgmath` -- Ilya


I'll give it a shot. Since the "real" type usually considers 
80-bit operands, is the D variant more precise? And which of 
those two results is correct, if any?


Re: Bug after update to 2.072?

2016-11-07 Thread ag0aep6g via Digitalmars-d-learn

On 11/07/2016 12:21 PM, Alex wrote:

On Sunday, 6 November 2016 at 16:07:54 UTC, ag0aep6g wrote:

[...]

Very weird. Would be great if you could provide a test case. Doesn't
need to be minimal.


I would if I would know how... :) the problem is, setting up the
debugger itself was not a simple task and then, the only point where it
stops - is before my main, at the mentioned line.
Every attempt to make a step just aborts the run and that's it.

What I have just tested is, that on a linux machine I have access to,
the error does not appear.


Don't need a debugger to get a test case.

You have some code that segfaults when run, right? For a test case you 
can just post that exact code.


Of course, you should remove any confidential information, and if it's 
closed source you may not be allowed to post it. So you may have to 
reduce it to a trivial example for legal reasons. But as for a test 
case, you can just post the code that fails right now. Doesn't matter if 
that includes a lot of unrelated stuff.


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

On Sunday, 6 November 2016 at 16:07:54 UTC, ag0aep6g wrote:

On 11/06/2016 05:00 PM, Alex wrote:

On Sunday, 6 November 2016 at 15:13:56 UTC, Alex wrote:

ok... played with the code a little bit.

If I remove the @trusted attribute in line 657 inside atomic.d
everything works as expected...
Any ideas, why it is so?


By the way, replacement with @safe works too...


Very weird. Would be great if you could provide a test case. 
Doesn't need to be minimal.


I would if I would know how... :) the problem is, setting up the 
debugger itself was not a simple task and then, the only point 
where it stops - is before my main, at the mentioned line.

Every attempt to make a step just aborts the run and that's it.

What I have just tested is, that on a linux machine I have access 
to, the error does not appear.


Re: Floating-point Modulus math.fmod

2016-11-07 Thread Ilya Yaroshenko via Digitalmars-d-learn

On Sunday, 6 November 2016 at 21:45:28 UTC, Fendercaster wrote:
I'm not quite sure if this is the right forum to ask this 
question:
I've been trying to implement the "floating-point modulus" 
function from the math library. Equivalently that's what I've 
tried in Python too. Problem is - the results are different and 
not even close. Please have a look at both snippets. Maybe 
someone can help me out:


[...]


Python uses 64-bit doubles. You may want to try with `double` and 
`core.stdc.tgmath` -- Ilya


Re: Error 42 When Trying to Interop with a C# Libary

2016-11-07 Thread Mike Parker via Digitalmars-d-learn

On Monday, 7 November 2016 at 06:22:16 UTC, Mike Parker wrote:



What I would do rather than adding -m32mscoff in additional 
options


Oh, and I forgot. Don't set the lib path in additional options 
either. In 'Configuration Properties -> Linker', enter the path 
in the 'Library Search Path' field. That way, you don't have to 
worry about the specific linker flags.


Re: Error 42 When Trying to Interop with a C# Libary

2016-11-07 Thread Mike Parker via Digitalmars-d-learn

On Sunday, 6 November 2016 at 17:57:23 UTC, Sarcross wrote:


Building Debug\Resume_Parser.exe...
OPTLINK (R) for Win32  Release 8.00.17




"$(VisualDInstallDir)pipedmd.exe" dmd -g -debug -X 
-Xf"$(IntDir)\$(TargetName).json" 
-deps="$(OutDir)\$(ProjectName).dep" 
-of"$(OutDir)\$(ProjectName).exe" -map 
"$(INTDIR)\$(SAFEPROJECTNAME).map" -L/MAP:FULL src\Parser2.lib


And I've added this to the "Additional options" section:

-m32mscoff 
\LIBPATH:C:\Users\antzy_000\Documents\Programming\D\Resume-Parser\src\Parser2.lib


Notice that the linker error is coming from OPTLINK, not the MS 
linker. That, and your -m32mscoff isn't showing up in Visual D's 
command line output (als, the \LIBPATH should be /LIBPATH).


What I would do rather than adding -m32mscoff in additional 
options is to go into the project properties in 'Configuration 
Properties -> Compiler -> Output' and check the box 'Use MS-COFF 
object file format for Win32 (DMD 2.067+)'. I know that has 
worked for me when using Visual D.


Also, run 'Clean' before building again just to make sure you 
aren't mixing OMF/COFF object files.


Re: how to debug memory errors

2016-11-07 Thread Era Scarecrow via Digitalmars-d-learn
On Monday, 7 November 2016 at 02:22:35 UTC, Steven Schveighoffer 
wrote:
OP: it's not legal to destroy or even access GC allocated 
members in a destructor. The GC may have already destroyed that 
data. I would recommend printing the stack trace when you get 
the exception, and figure out where the culprit is.


 Err that makes no sense... If that's the case why have a 
destructor at all?


Re: how to debug memory errors

2016-11-07 Thread thedeemon via Digitalmars-d-learn
On Monday, 7 November 2016 at 02:22:35 UTC, Steven Schveighoffer 
wrote:
OP: it's not legal to destroy or even access GC allocated 
members in a destructor. The GC may have already destroyed that 
data.


Isn't destroy() fine there? It doesn't call destructors for 
already destroyed objects, so I guess it should be safe. 
(assuming the destructors don't do any allocations)




how to debug memory errors

2016-11-07 Thread Øivind via Digitalmars-d-learn

Hi,

My app occasionally gives me a

*** Error in `./hauto-test': double free or corruption (fasttop): 
0x7f504c002a60 ***


but gives me the following on every termination

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

How do I go about debugging and resolving these?

-Øivind


Re: how to debug memory errors

2016-11-07 Thread Lodovico Giaretta via Digitalmars-d-learn

On Sunday, 6 November 2016 at 21:46:52 UTC, Øivind wrote:

Hi,

My app occasionally gives me a

*** Error in `./hauto-test': double free or corruption 
(fasttop): 0x7f504c002a60 ***


but gives me the following on every termination

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

How do I go about debugging and resolving these?

-Øivind


I think that "Invalid Memory Operation" is the error the GC gives 
you when you try to allocate memory during the collection phase 
(i.e. inside a destructor). I suggest you avoid doing so.


I don't know if the double free problem is related to this. It 
may as well be a totally unrelated bug of some container you are 
using.


Re: how to debug memory errors

2016-11-07 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/6/16 5:15 PM, Lodovico Giaretta wrote:

On Sunday, 6 November 2016 at 21:46:52 UTC, Øivind wrote:

Hi,

My app occasionally gives me a

*** Error in `./hauto-test': double free or corruption (fasttop):
0x7f504c002a60 ***

but gives me the following on every termination

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

How do I go about debugging and resolving these?

-Øivind


I think that "Invalid Memory Operation" is the error the GC gives you
when you try to allocate memory during the collection phase (i.e. inside
a destructor). I suggest you avoid doing so.

I don't know if the double free problem is related to this. It may as
well be a totally unrelated bug of some container you are using.


It absolutely could be related to this.

Imagine a resource wrapper like so:

class Foo
{
   int *mem;
   this() { mem = cast(int *)malloc(int.sizeof); }
   ~this() { .free(mem); }
}

Now, you have a problem if you do something like this:

class Bar
{
   Foo foo;
   ~this() { delete foo; }
}

Whenever Bar's dtor is called, it's going to throw the error when the 
delete call tries to free the block.


However, occasionally, the GC will have destroyed the foo instance 
BEFORE destroying the Bar instance that holds it. This will result in 
Foo's dtor being called twice for the same memory, resulting in the 
double-free call. Then of course, the memory free of the GC is not 
allowed, so we have the exception happening after.


OP: it's not legal to destroy or even access GC allocated members in a 
destructor. The GC may have already destroyed that data. I would 
recommend printing the stack trace when you get the exception, and 
figure out where the culprit is.


-Steve


Re: system's "kill " signal

2016-11-07 Thread Steven Schveighoffer via Digitalmars-d-learn

On 11/6/16 11:05 AM, Konstantin Kutsevalov wrote:

On Saturday, 5 November 2016 at 07:52:53 UTC, Basile B. wrote:

On Saturday, 5 November 2016 at 06:17:51 UTC, Basile B. wrote:
3rd option, from my Windows times I remember that people tend to use
launchers
to handle the real application, i.e a process that launches the main
process. Then the launcher can have a thread that checks the PID (like
in "After Term..."). If SIGKILL isn't handled by a signal() callback
then this could be an option.

Do you have to check if a server crashes or something like that ?


not a system crash. just a signal of sistems shutdown or process kill.


You can catch signals, but some the OS does not let you catch.

IIRC, Posix systems on shutdown first send a "TERM" signal (15) which is 
the default signal for the kill command line as well. If the process 
does not clean up within a certain timeout, then it is sent the "KILL" 
signal (9), which CANNOT be caught.


What you want is to handle process cleanup on the TERM signal.

-Steve


Re: Sockets and using them...

2016-11-07 Thread Charles Hixson via Digitalmars-d-learn

On 11/05/2016 11:02 PM, Era Scarecrow via Digitalmars-d-learn wrote:
 So I've got a project where I want to create basically a 
decentralized chat program where every program is a host and a client. 
When you connect all connections can go through to route the chat to 
everyone else.


 So to make this work I've looked over the sockets package and I don't 
quite follow how you'd make it so it works a lot like a web browser, 
aka when you get a connection you redirect to a different port so you 
have 1 listening port for new connections so it can act as a server. 
What settings or configuration would I need to be able to do that?


That sounds more like a job for udp than tcp sockets.  You'd need to 
implement an ack/nak protocol because udp doesn't guarantee delivery, 
but unless you want a central server I don't see how you could use tcp.  
The central server wouldn't need to do much, and could delegate most of 
the processing, but it wouldn't be decentralized.  I was looking into 
using tcp (actually zmq) for something similar awhile back and tcp just 
didn't seem to support actually decentralized communication.  Udp 
did...which meant I couldn't use zmq.  That was a real pity because zmq 
is basically a very nice package, and easy to wrap.


Floating-point Modulus math.fmod

2016-11-07 Thread Fendercaster via Digitalmars-d-learn
I'm not quite sure if this is the right forum to ask this 
question:
I've been trying to implement the "floating-point modulus" 
function from the math library. Equivalently that's what I've 
tried in Python too. Problem is - the results are different and 
not even close. Please have a look at both snippets. Maybe 
someone can help me out:


[code = D]
import std.math;
import std.stdio;

immutable real MODULUS = 1e8;

real floatModPow(real base, ulong exp, real mod)
{
real r = 1.0;

while (exp) {
if (exp & 1) r = fmod(r * base, mod);
exp >>= 1;
base = fmod(base*base, mod);
}

return r;
}

void main()
{
floatModPow(3.866, 987654321UL, MODULUS).writeln;
}
[/code]

In this case the result is 6.44588e+07.

[code = Python]
import math

MOD = 1e8

def fpmod(b, e, m):
r = 1.0
while e:
if (e & 1):
r = math.fmod(r * b, m)
e >>= 1
b = math.fmod(b * b, m)
return r

print (fpmod(3.866, 987654321, MOD))
[/code]

In this case the result is 82031250.0.

AFAIK the D.fmod and Python.fmod functions serve the same 
purpose. What am I missing?


Re: Bug after update to 2.072?

2016-11-07 Thread ag0aep6g via Digitalmars-d-learn

On 11/06/2016 05:00 PM, Alex wrote:

On Sunday, 6 November 2016 at 15:13:56 UTC, Alex wrote:

ok... played with the code a little bit.

If I remove the @trusted attribute in line 657 inside atomic.d
everything works as expected...
Any ideas, why it is so?


By the way, replacement with @safe works too...


Very weird. Would be great if you could provide a test case. Doesn't 
need to be minimal.


Re: system's "kill " signal

2016-11-07 Thread Konstantin Kutsevalov via Digitalmars-d-learn

On Saturday, 5 November 2016 at 06:17:51 UTC, Basile B. wrote:
On Saturday, 5 November 2016 at 02:24:00 UTC, Konstantin 
Kutsevalov wrote:

Hi,

is there a way to catch system signal of "kill" command or 
"shutdown"?


During the Run-time:


You can register a signal callback, like in this sample (hit 
CTRL+C once running in a terminal):



After termination:
==

if (tryWait(PID)[0] == true) then the value carried by 
tryWait(PID)[1] will tell you if the process has exited because 
of a signal whatever it's, e.g SIGKILL, SIGTERM, SIGINT, ...


Thank you!


Re: Error 42 When Trying to Interop with a C# Libary

2016-11-07 Thread Sarcross via Digitalmars-d-learn

On Sunday, 6 November 2016 at 02:37:23 UTC, Mike Parker wrote:

On Saturday, 5 November 2016 at 22:06:21 UTC, Sarcross wrote:

LINK : fatal error LNK1104: cannot open file 
'+C:\Users\antzy_000\Documents\Programming\D\Resume-Parser\src\Parser2.lib'

--- errorlevel 1104
dmd failed with exit code 1104.


  "lflags" :  
["+C:\\Users\\antzy_000\\Documents\\Programming\\D\\Resume-Parser\\src\\Parser2.lib"],


The error linker error tells you that the linker thinks the 
path you specified with '+' is a filename (which is why it 
tacked .lib on the end), meaning it doesn't recognize it as a 
command line option. That's because when you compile with 
-m32mscoff, you are using the Microsoft linker (link) rather 
than optlink, the default. The '+path' syntax is something 
optlink understands, but link does not. You can find the MS 
linker commands at [1], in this case you want [2]:


"lflags" : 
"/LIBPATH:C:\Users\antzy_000\Documents\Programming\D\Resume-Parser\src\Parser2"


[1] https://msdn.microsoft.com/en-us/library/y0zzbyt4.aspx
[2] https://msdn.microsoft.com/en-us/library/1xhzskbe.aspx


Well Mike, that seems to have gotten me a step closer, but now a 
new error:


Building Debug\Resume_Parser.exe...
OPTLINK (R) for Win32  Release 8.00.17
Copyright (C) Digital Mars 1989-2013  All rights reserved.
http://www.digitalmars.com/ctg/optlink.html
Debug\Resume_Parser.obj Offset 0H Record Type 004C
 Error 138: Module or Dictionary corrupt
Building Debug\Resume_Parser.exe failed!

I'm not quite sure how it could be corrupt since there haven't 
been any changes to it since I used the tool on the original 
.lib. As a "let me see" scenario, I tried switching back to the 
original .lib but get the same error. A bit of additional 
information here; In Properties >> Command Line, Visual Studio is 
using this in the "Command Line" section:


"$(VisualDInstallDir)pipedmd.exe" dmd -g -debug -X 
-Xf"$(IntDir)\$(TargetName).json" 
-deps="$(OutDir)\$(ProjectName).dep" 
-of"$(OutDir)\$(ProjectName).exe" -map 
"$(INTDIR)\$(SAFEPROJECTNAME).map" -L/MAP:FULL src\Parser2.lib


And I've added this to the "Additional options" section:

-m32mscoff 
\LIBPATH:C:\Users\antzy_000\Documents\Programming\D\Resume-Parser\src\Parser2.lib





Re: system's "kill " signal

2016-11-07 Thread Konstantin Kutsevalov via Digitalmars-d-learn
On Sunday, 6 November 2016 at 16:05:44 UTC, Konstantin Kutsevalov 
wrote:

On Saturday, 5 November 2016 at 07:52:53 UTC, Basile B. wrote:

On Saturday, 5 November 2016 at 06:17:51 UTC, Basile B. wrote:
3rd option, from my Windows times I remember that people tend 
to use launchers
to handle the real application, i.e a process that launches 
the main process. Then the launcher can have a thread that 
checks the PID (like in "After Term..."). If SIGKILL isn't 
handled by a signal() callback then this could be an option.


Do you have to check if a server crashes or something like 
that ?


not a system crash. just a signal of sistems shutdown or 
process kill.


*of system


Re: system's "kill " signal

2016-11-07 Thread Konstantin Kutsevalov via Digitalmars-d-learn

On Saturday, 5 November 2016 at 07:52:53 UTC, Basile B. wrote:

On Saturday, 5 November 2016 at 06:17:51 UTC, Basile B. wrote:
3rd option, from my Windows times I remember that people tend 
to use launchers
to handle the real application, i.e a process that launches the 
main process. Then the launcher can have a thread that checks 
the PID (like in "After Term..."). If SIGKILL isn't handled by 
a signal() callback then this could be an option.


Do you have to check if a server crashes or something like that 
?


not a system crash. just a signal of sistems shutdown or process 
kill.


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

On Sunday, 6 November 2016 at 15:13:56 UTC, Alex wrote:

ok... played with the code a little bit.

If I remove the @trusted attribute in line 657 inside atomic.d 
everything works as expected...

Any ideas, why it is so?


By the way, replacement with @safe works too...


Re: Bug after update to 2.072?

2016-11-07 Thread Alex via Digitalmars-d-learn

ok... played with the code a little bit.

If I remove the @trusted attribute in line 657 inside atomic.d 
everything works as expected...

Any ideas, why it is so?