Raw Binary into the console

2014-07-12 Thread Sean Campbell via Digitalmars-d-learn

How Can I Print Raw Binary Into The Console?
I Have Variable Of Type ubyte which equals 0b011 How Can I Get 
The Variable To Print Out As 011


Re: Raw Binary into the console

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/11/2014 10:56 PM, Sean Campbell wrote:

 How Can I Print Raw Binary Into The Console?

Taking a step back, a D program prints to stdout, not console. However, 
in most cases a D program's output ends up on the console when it is 
started in a console.


So, one can print any byte value to the stdout, which usually ends up on 
the console. Now, the question is how that value will be interpreted by 
the console. On some consoles (e.g. Linux) the byte stream is 
interpreted as a UTF-8 stream or a control character in the case of 0b011.


 I Have Variable Of Type ubyte which equals 0b011 How Can I Get The
 Variable To Print Out As 011

That is different though. You seem to want to print the value 0b011 as 
the string 011. %b format specifier does that. However, in most cases 
it is also useful to zero-pad the output:


writefln(%08b, 0b011);

Ali



Const problems

2014-07-12 Thread bearophile via Digitalmars-d-learn

In case you have missed the thread:

http://www.reddit.com/r/programming/comments/2ag8qe/the_constness_problem/

Bye,
bearophile


Something like Python's psutils for D?

2014-07-12 Thread Thomas Mader via Digitalmars-d-learn
The Subject says it all, is something like psutils available in 
D? [1]

I need it to measure memory usage of a process.

[1] https://github.com/giampaolo/psutil

thank you
Thomas


Re: Something like Python's psutils for D?

2014-07-12 Thread Thomas Mader via Digitalmars-d-learn
I also need to get the user and system time of a process, doesn't 
seem to be available in Phobos. (e.g. getrusage in Linux but 
platform independent)


Re: Value Reference Type Traits

2014-07-12 Thread Nordlöw

On Friday, 11 July 2014 at 16:22:37 UTC, anonymous wrote:

There's http://dlang.org/phobos/std_traits.html#hasIndirections


Thx.


Help to find crash in simple stack type?

2014-07-12 Thread Gary Willoughby via Digitalmars-d-learn
I've created a simple stack type using calloc/free which seems to 
work nicely. Then instead of using C functions i've tried to 
implement the same type using the GC. However i'm experiencing a 
crash. I've been staring at this snippet for hours now any help 
would be appreciated. This is a simplified snippet showing the 
crash:


import std.stdio;
import core.memory;

class Stack(T)
{
private T* _data;
private T* _pointer;
private immutable size_t _minimumSize;
private size_t _size;
private size_t _count;

public this()
{
this._minimumSize = 32_000;
this._size = this._minimumSize;
this._data = cast(T*)GC.calloc(this._size, GC.BlkAttr.NO_MOVE);
this._pointer = this._data;
this._pointer--;
}

public void push(T value)
{
this._pointer++;

if ((this._size / T.sizeof)  (this._count + 1))
{
this._size *= 2;
writefln(realloc to %s bytes, this._size);
			this._data = cast(T*)GC.realloc(this._data, this._size, 
GC.BlkAttr.NO_MOVE);

this._pointer = (this._data + this._count);
}

this._count++;
*this._pointer = value;
}
}

unittest
{
auto stack = new Stack!(int);

for (int x = 1; x = 300_000 ; x++)
{
stack.push(x);
}
}

It seems to crash when the loop iteration is at about 260,000 and 
i've no idea why. I'm using Ubuntu 64bit latest DMD.


Re: Help to find crash in simple stack type?

2014-07-12 Thread Rainer Schuetze via Digitalmars-d-learn



On 12.07.2014 16:24, anonymous wrote:

No explanation or solution, but a reduction:

import core.memory;
void main()
{
  alias T = ubyte;

  enum size1 = 2_049; /*  2_048 = 2^^11 */
  enum size2 = 1_048_577; /*  1_048_576 = 2^^20 */

  T* _data;
  _data = cast(T*)GC.calloc(size1, GC.BlkAttr.NO_MOVE);
  _data = cast(T*)GC.realloc(_data, size2, GC.BlkAttr.NO_MOVE);

  T* _pointer = _data;
  foreach(i; 0 .. size2)
  {
  *_pointer = 0; /* segfault at i = 1_048_576 */
  _pointer++;
  }
}


Thanks for the reduction. GC.realloc seems broken for reallocations to 
sizes larger than the current GC pool.


Please file a bug report.


Re: Help to find crash in simple stack type?

2014-07-12 Thread Rainer Schuetze via Digitalmars-d-learn



On 12.07.2014 19:05, Rainer Schuetze wrote:


Thanks for the reduction. GC.realloc seems broken for reallocations to
sizes larger than the current GC pool.

Please file a bug report.


Actually done that myself: https://issues.dlang.org/show_bug.cgi?id=13111


OSX, Need help with Compiling and linking errors

2014-07-12 Thread Israel Rodriguez via Digitalmars-d-learn
Ive been reading the OSX notes for the DMD compiler but not 
everything is clear to me as i dont know how exactly the compiler 
looks for things.


i wanted to test it out first using this package from 
code.dlang.org

http://code.dlang.org/packages/colorize
I downloaded the zip, extracted it, and dub was able to spit out 
a static library with the .a extension.

What do i do with it now? Where do i place it?

I have imported the library like it says import colorize : 
colorize, fg;
After i call dmd in the terminal like $ dmd main.d, All i get 
are linker errors but no compile errors even if i reference the 
static library in the same drectory as my main.d source file like 
so, $ dmd main.d libcolorize.a


Then the package mentions adding colorize as a dependency to my 
projects json file so i used the -X switch to generate it but i 
dont know exactly where the dependencies section goes.


As for the linker errors, they mention mostly:

===

Undefined symbols for architecture x86_64:
 
_D4dlib4math6matrix16__T6MatrixTdVi4Z6Matrix11__xopEqualsFKxS4dlib4math6matrix16__T6MatrixTdVi4Z6MatrixKxS4dlib4math6matrix16__T6MatrixTdVi4Z6MatrixZb, 
referenced from:
  
_D52TypeInfo_S4dlib4math6matrix16__T6MatrixTdVi4Z6Matrix6__initZ 
in main.o

ld: symbol(s) not found for architecture x86_64

===


Does this mean this library is just not compatible with OSX?

Extra Notes:
I have Xcode Installed along with the command line tools so GCC 
is in there too.

OSX 10.9.4
X11 - XQuartz


DStyle: Braces on same line

2014-07-12 Thread Danyal Zia via Digitalmars-d-learn

Hi,

I noticed that in Andrei's talks and his book, he used braces on 
the same line of delcaration, however Phobos and other D 
libraries I know use braces on their own line. Now I'm in a 
position where I need to take decision on coding style of my 
library and I get accustomed to use braces on same line but I'm 
worried if that would make my library less readable to other D 
users.


Should I worry about it? Or is that's just a debatable style that 
won't really matter if it's persistent throughout library?


Thanks


struct template help

2014-07-12 Thread seany via Digitalmars-d-learn

Please consider the following

struct arc(T,U)
{

T some_var;
U  someother_var;
}

/* things */

class myclass
{
  this(){}
 ~this(){}
  void MYfunction()

  {
arc!(string, string[]) * a;
a.some_var = hello;
  }
}


void main()
{
  c = new myclass();
  c.MYfunction();
}


This leads to a segmentation fault.

What am I doing wrong?


Re: struct template help

2014-07-12 Thread seany via Digitalmars-d-learn

Also, (*c).MYfunction() is leading to segmentation fault


Re: struct template help

2014-07-12 Thread seany via Digitalmars-d-learn

sorry, I meant (*a).some_var
not (*c).MYfunction()


Re: struct template help

2014-07-12 Thread seany via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:16:52 UTC, Danyal Zia wrote:

On Saturday, 12 July 2014 at 19:09:44 UTC, seany wrote:

Please consider the following

struct arc(T,U)
{

T some_var;
U  someother_var;
}

/* things */

class myclass
{
 this(){}
~this(){}
 void MYfunction()

 {
   arc!(string, string[]) * a;
   a.some_var = hello;
 }
}


void main()
{
 c = new myclass();
 c.MYfunction();
}


This leads to a segmentation fault.

What am I doing wrong?
a has not been instantiated. You are declaring it as a 
pointer to struct and using its fields without initializing it. 
arc!(string, string[]) a; will work.


For reasons further down in the software, I need to do this with 
a pointer. How do I do it with a pointer, please?


Re: struct template help

2014-07-12 Thread Danyal Zia via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:19:28 UTC, seany wrote:
For reasons further down in the software, I need to do this 
with a pointer. How do I do it with a pointer, please?


I don't know what are you trying to achieve, but if that's what 
you want, you can do:


void MYfunction()
{
auto strArr = [Hello, World!];
arc!(string, string[]) * a = new arc!(string, string[])(s, 
strArr);

a.some_var = hello;
}

If you want to use a from outside the function you have to 
declare it in the class and then initialize it in your function.


Re: struct template help

2014-07-12 Thread seany via Digitalmars-d-learn
do I have to initialize all variables of the struct? or may I 
also use a this(){} in the struct and initialize only those which 
are known at a given moment?


Re: struct template help

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/12/2014 12:19 PM, seany wrote:

 On Saturday, 12 July 2014 at 19:16:52 UTC, Danyal Zia wrote:
 On Saturday, 12 July 2014 at 19:09:44 UTC, seany wrote:

arc!(string, string[]) * a;
a.some_var = hello;

 a has not been instantiated. You are declaring it as a pointer to
 struct and using its fields without initializing it. arc!(string,
 string[]) a; will work.

 For reasons further down in the software, I need to do this with a
 pointer. How do I do it with a pointer, please?

By making that pointer point to an actual object. :)

arc!(string, string[]) * a = new arc!(string, string[])();

Shorter syntax:

auto a = new arc!(string, string[]);

You can assign it later as well:

arc!(string, string[]) * a;
// ...
a = new arc!(string, string[])();

Preferably, don't assign to the member but construct when the 
information is available:


auto a = new arc!(string, string[])(hello,
[merhaba, hola, bonjour]);

Ali



Re: struct template help

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/12/2014 12:32 PM, seany wrote:

 do I have to initialize all variables of the struct?

No. The uninitialized ones get their .init values.

 or may I also use a
 this(){} in the struct and initialize only those which are known at a
 given moment?

That already works with structs. You don't need to define any 
constructor if the type is simple data i.e. if you don't want to set any 
invariants, just construct with whatever is available at that moment:


auto a = new S(hello);

However, if it is important that someother_var should not remain as an 
empty array, then you better define a constructor and demand both values 
when constructing.


Ali



Re: DStyle: Braces on same line

2014-07-12 Thread Dicebot via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:01:56 UTC, Danyal Zia wrote:
Should I worry about it? Or is that's just a debatable style 
that won't really matter if it's persistent throughout library?


Depends entirely on whenever you want to match style of standard 
library - no one will blame you for having own preferences. It is 
only required for Phobos pull requests.


Re: struct template help

2014-07-12 Thread Danyal Zia via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:32:48 UTC, seany wrote:
do I have to initialize all variables of the struct? or may I 
also use a this(){} in the struct and initialize only those 
which are known at a given moment?


You can initialize in constructor this(), but you can't 
initialize partial fields of struct when using pointer to struct. 
There would be other trivial ways to do what you are trying to 
do. Also, I never used any pointer to struct (which is of value 
type) in my code .


Re: DStyle: Braces on same line

2014-07-12 Thread anonymous via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:01:56 UTC, Danyal Zia wrote:

Hi,

I noticed that in Andrei's talks and his book, he used braces 
on the same line of delcaration, however Phobos and other D 
libraries I know use braces on their own line. Now I'm in a 
position where I need to take decision on coding style of my 
library and I get accustomed to use braces on same line but I'm 
worried if that would make my library less readable to other D 
users.


Should I worry about it?


no

Or is that's just a debatable style that won't really matter if 
it's persistent throughout library?


yes (I read that if as as long as)

There is another stylistic choice which I do find confusing:
capitalized identifiers for non-types, e.g. variables and
functions. Please don't do that.


Re: struct template help

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/12/2014 12:38 PM, Danyal Zia wrote:

 You can initialize in constructor this(), but you can't initialize
 partial fields of struct when using pointer to struct.

Actually, that works too but members must be initialized from the 
beginning. The trailing ones are left with .init values:


struct S
{
int i;
string s;
}

void main()
{
auto s = new S(42);
static assert(is (typeof(s) == S*));
}

Ali



Re: struct template help

2014-07-12 Thread Danyal Zia via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:42:13 UTC, Ali Çehreli wrote:
Actually, that works too but members must be initialized from 
the beginning. The trailing ones are left with .init values:


struct S
{
int i;
string s;
}

void main()
{
auto s = new S(42);
static assert(is (typeof(s) == S*));
}

Ali


Ah, right. I still has C++ background in my veins I guess :)



Re: DStyle: Braces on same line

2014-07-12 Thread Danyal Zia via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:35:11 UTC, anonymous wrote:

There is another stylistic choice which I do find confusing:
capitalized identifiers for non-types, e.g. variables and
functions. Please don't do that.


Agreed about variables and functions. However I personally prefer 
to use PascalCased identifiers in enum unlike what is preached in 
Dstyle page.


Template help

2014-07-12 Thread Anonymous via Digitalmars-d-learn
I got to typing one day and came up with this. What it does is 
search an aggregate for a member named match. If it's a direct 
member, it evaluates to that. If it's not, then it searches any 
aggregate type sub-members (deep members) for match. If there's 
only one deep member tree with match, it evaluates to that. 
Otherwise you get static assertion errors for no match or an 
ambiguous match.  Maybe I'm doing something completely wrong in 
my code, and I certainly don't think it's pretty, but it seems to 
work how I expect.


So say some variable Foo has member Bar. Bar has member Baz, 
which has member Thing. Instead of writing auto x = 
Foo.Bar.Baz.Thing; you can write auto x = Foo.Extract!Thing. 
The trouble comes in if there's more than one tree with Thing in 
it.


Except when I want a deep member that happens to be a function. I 
can't for the life of me figure out how to recurse down the 
member hierarchy while carrying along the arguments, or bubble up 
some alias to the function at the bottom which I then pass the 
arguments.


If I get past that, I want to try and play with automatic, ad-hoc 
type generation based on X functions you try to call on Y members.


template agg_mems(T) {
enum T_instance = T.init;
alias pred(string name) = isAggregateType!(totype!name);
	alias totype(string name) = 
typeof(__traits(getMember,T_instance,name));

alias agg_mems = Filter!(pred, __traits(allMembers,T));
}

/**
	Evaluates to true if match is a member or sub-member of T, and 
false otherwise.

Issues assertion failure if more than one sub-member is a match.
Used primarily by DeepMember.
*/
template hasDeepMember(T, string match) {
static if (hasMember!(T,match)) enum hasDeepMember = true;
else {
enum T_instance = T.init;
alias name_list = agg_mems!T;
//flatten our hasDeepMember to one parameter, a member name
		alias test_unary(string name) = 
hasDeepMember!(typeof(__traits(getMember,T_instance,name)), 
match);

alias haves = Filter!(test_unary, name_list);
		static assert(haves.length  2,T.stringof~ ambiguous match for 
~match);

//if we find a match among sub-members, evals to true
static if (haves.length == 1) enum hasDeepMember = true;
else enum hasDeepMember = false;
}
}

template DeepMember(T, string match, parent...)
{
//test match
	static if (hasMember!(T,match)) enum DeepMember = 
TypeTuple!(parent, match);

else {
enum T_instance = T.init;
alias name_list = agg_mems!(T);
//flatten our presence test down to one parameter for Filter
		alias test_unary(string name) = 
hasDeepMember!(typeof(__traits(getMember,T_instance,name)), 
match);

alias next = Filter!(test_unary, name_list);
		static assert(next.length  2,T.stringof~ has ambiguous match 
for ~match);

static if (next.length == 1) {
//accumulate hierarchy of members
enum DeepMember = DeepMember!(
typeof(__traits(getMember,T_instance,next[0])),
match,
TypeTuple!(parent,next[0]));
}
else static assert(false,T.stringof~ has no match for ~match);
}
}

auto ref Extract(string match, T, S...)(auto ref T var, auto ref 
S args) {

static if (hasMember!(T, match)) {
		static if (args.length == 0) return 
__traits(getMember,var,match);

else return __traits(getMember,var,match)(args);
}
else {
alias tree = DeepMember!(T, match);
static assert(tree.length  0);
return DeepExtract!(T,tree)(var);
}
}

auto ref DeepExtract(T, tree...)(auto ref T var) {
	static if (tree.length == 1) return 
__traits(getMember,var,tree[0]);

else {
alias next_T = typeof(__traits(getMember,var,tree[0]));
		return DeepExtract!(next_T, 
tree[1..$])(__traits(getMember,var,tree[0]));

}
}



Re: Template help

2014-07-12 Thread Anonymous via Digitalmars-d-learn

One way I've used it in code

struct MapBy(T,string key) if (hasDeepMember!(T,key)) {
alias key_t = DeepMemberType!(T,key);
private const(T)[key_t] _map;

bool has(key_t id) const nothrow {
if ((id in _map) != null) return true;
else return false;
}

void put(in ref T val) pure nothrow {
auto id = val.Extract!key;
_map[id] = val;
}

ref const(T) get(key_t id) const nothrow {
assert(has(id));
return _map[id];
}
}


Re: Insert a char in string

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/10/2014 09:05 AM, Alexandre wrote:

I have a string X and I need to insert a char in that string...

auto X = 100;

And I need to inser a ',' in position 3 of this string..., I try to use
the array.insertInPlace, but, not work...

I try this:
auto X = 100;
auto N = X.insertInPlace(1,'0');


Here is another solution, which does not modify the original string:

import std.stdio;
import std.algorithm;
import std.range;
import std.string;

void main()
{
auto number = 12345678;

auto formatted =
zip(number.retro, sequence!n + 1)
.map!(z = format(!(z[1] % 3) ? %s, : %s, z[0]))
.join
.retro;

assert(formatted.equal(12,345,678));
}

I am not happy with the .join there because I think it makes an array 
but I could not get it to compile with the lazy .joiner because I think 
it dose not look like a bidirectional range to .retro.


Ali



Re: Something like Python's psutils for D?

2014-07-12 Thread Ellery Newcomer via Digitalmars-d-learn

On Saturday, 12 July 2014 at 08:34:41 UTC, Thomas Mader wrote:
The Subject says it all, is something like psutils available in 
D?


would psutils itself be acceptable?

https://bitbucket.org/ariovistus/pyd


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread dysmondad via Digitalmars-d-learn

.


try:

unittest {
  Velocity v = new Velocity( 2.0f, 5.0f );
  v *= 5.0f;  // - line 110
  printf( v = %s\n, to!string(v) );
}

instead. Basically version is like static if, it doesn't 
indicate its a function. Instead it changes what code gets 
compiled.
Where as a unittest block, is essentially just a function that 
gets called at a special time, that is only compiled as if 
version(unittest) was also used.


Thank you very much. That was quite helpful.

So, what is the generally accepted way include unit testing? TDD 
is all the rage these days and I though I would try my hand at it 
as well as D.


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread Rikki Cattermole via Digitalmars-d-learn

On 13/07/2014 2:35 p.m., dysmondad wrote:

.


try:

unittest {
  Velocity v = new Velocity( 2.0f, 5.0f );
  v *= 5.0f;  // - line 110
  printf( v = %s\n, to!string(v) );
}

instead. Basically version is like static if, it doesn't indicate its
a function. Instead it changes what code gets compiled.
Where as a unittest block, is essentially just a function that gets
called at a special time, that is only compiled as if
version(unittest) was also used.


Thank you very much. That was quite helpful.

So, what is the generally accepted way include unit testing? TDD is all
the rage these days and I though I would try my hand at it as well as D.


Basically, have a function that does something like string manipulation 
or complex math? Use a unittest block for it. Which you can do before 
you write the function. It may not compile however.


Also do note, assert's are part of the language. And will cause an 
exception to throw should the expression return false.


assert(exp, description);

Description is optional however.

Here's an example 
https://github.com/rikkimax/skeleton/blob/master/source/skeleton/syntax/download_mkdir.d#L175
Of course there will be better ones, just something I was doing last 
night however.


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread H. S. Teoh via Digitalmars-d-learn
On Sun, Jul 13, 2014 at 02:35:11AM +, dysmondad via Digitalmars-d-learn 
wrote:
[...]
 So, what is the generally accepted way include unit testing? TDD is
 all the rage these days and I though I would try my hand at it as well
 as D.

Just include unittest blocks in your program and compile with -unittest.

Example:

unittest {
assert(myNewFunc(1,2,3) == 456);
... // whatever else to verify it
}

auto myNewFunc(int x, int y, int z) {
... // code here
}

The program will run all unittests on startup before main() executes, so
you can just run it as usual. If any unittests fail it will abort with
an error message.


T

-- 
What's a hot crossed bun? An angry rabbit.


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread H. S. Teoh via Digitalmars-d-learn
On Sun, Jul 13, 2014 at 02:39:00AM +, dysmondad via Digitalmars-d-learn 
wrote:
 On Saturday, 12 July 2014 at 05:23:29 UTC, Ali Çehreli wrote:
 On 07/11/2014 10:08 PM, dysmondad wrote:
 
  class Velocity
  {
 
 [...]
 
   ref Velocity opOpAssign(string op) ( in float multiplier
 )
 
 Unrelated to your question, you want to return just Velocity there.
 Unlike C++, classes are reference types in D. So, Velocity itself is
 essentially a Velocity* in C++.
 
 Ali
 
 Right you are. I knew that but it still didn't translate into code.
 Thank you for pointing that out. I guess eventually I will remember
 that class variables are pointers.
 
 As a point of curiosity, is the ref keyword in this case simply
 redundant or does it actually make a difference?

ref makes it possible for the caller to modify the pointer returned by
the callee. For example:

class D { int x; }
class C {
D d;
this(D _d) { d = _d; }
ref D getPtr() { return d; }
}
auto d1 = new D;
auto d2 = new D;
auto c = new C(d1); // c.d now points to d1
assert(c.getPtr() is d1); // getPtr returns d1
c.getPtr() = d2; // this modifies c.d
assert(c.getPtr() is d2); // getPtr now returns d2

If you do not wish the caller to do this, remove the ref from the
function signature.


T

-- 
Don't drink and derive. Alcohol and algebra don't mix.


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread dysmondad via Digitalmars-d-learn

...

https://github.com/rikkimax/skeleton/blob/master/source/skeleton/syntax/download_mkdir.d#L175
Of course there will be better ones, just something I was doing 
last night however.


Thanks for the link and the information.
That's looks like what I need so I'm going to rip off your code 
example. :)


Re: DStyle: Braces on same line

2014-07-12 Thread dysmondad via Digitalmars-d-learn

On Saturday, 12 July 2014 at 19:01:56 UTC, Danyal Zia wrote:

Hi,

I noticed that in Andrei's talks and his book, he used braces 
on the same line of delcaration, however Phobos and other D 
libraries I know use braces on their own line. Now I'm in a 
position where I need to take decision on coding style of my 
library and I get accustomed to use braces on same line but I'm 
worried if that would make my library less readable to other D 
users.


Should I worry about it? Or is that's just a debatable style 
that won't really matter if it's persistent throughout library?


Thanks


Pick one and stick with it. There are countless holy wars out 
there about this sort of thing and it is really a personal choice.


Generally it's a good idea to follow the style of extant code if 
you are working on large project and I do feel that coding teams 
should pick a style all the code from that group should use the 
same style.


Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread Ali Çehreli via Digitalmars-d-learn

On 07/12/2014 08:37 PM, H. S. Teoh via Digitalmars-d-learn wrote:

 ref makes it possible for the caller to modify the pointer returned by
 the callee. For example:

class D { int x; }
class C {
D d;
this(D _d) { d = _d; }
ref D getPtr() { return d; }
}
auto d1 = new D;
auto d2 = new D;
auto c = new C(d1); // c.d now points to d1
assert(c.getPtr() is d1); // getPtr returns d1
c.getPtr() = d2; // this modifies c.d
assert(c.getPtr() is d2); // getPtr now returns d2

 If you do not wish the caller to do this, remove the ref from the
 function signature.

The twist here is that the OP's function returned 'this' by reference. 
Changing that not only not have any effect on the object, it would also 
be undefined behavior because 'this' is a local variable in that use.


class C {
ref C getPtr() { return this; }
}

void main()
{
auto c = new C();
assert(c.getPtr() is c);

c.getPtr() = new C();// modifying dead variable
assert(c.getPtr() is c); // no effect
}

Ali



Re: I don't get it. version(unittest) can't seem to use local variable

2014-07-12 Thread H. S. Teoh via Digitalmars-d-learn
On Sat, Jul 12, 2014 at 09:30:44PM -0700, H. S. Teoh via Digitalmars-d-learn 
wrote:
 On Sat, Jul 12, 2014 at 09:20:06PM -0700, Ali Çehreli via Digitalmars-d-learn 
 wrote:
[...]
  The twist here is that the OP's function returned 'this' by
  reference.  Changing that not only not have any effect on the
  object, it would also be undefined behavior because 'this' is a
  local variable in that use.
  
  class C {
  ref C getPtr() { return this; }
  }
  
  void main()
  {
  auto c = new C();
  assert(c.getPtr() is c);
  
  c.getPtr() = new C();// modifying dead variable
  assert(c.getPtr() is c); // no effect
  }
 [...]
 
 Hmm. Shouldn't this be a compiler bug?? Returning a ref to a local
 variable should be illegal, even implicit ones like 'this'.
[...]

Filed as bug:

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

It's pretty serious, since it causes memory corruption. In fact, it also
breaks @safe-ty (see second bug note in above link).


T

-- 
The early bird gets the worm. Moral: ewww...


Re: OSX, Need help with Compiling and linking errors

2014-07-12 Thread Israel Rodriguez via Digitalmars-d-learn

On Sunday, 13 July 2014 at 01:53:10 UTC, Mike Parker wrote:

On 7/13/2014 3:54 AM, Israel Rodriguez wrote:



The linker errors do not refer to libcolorize. Notice this: 
_D4dlib4math6matrix. That is a dlib.math.matrix module. Is 
that a source module in your project or something from another 
library? If the former, you need to be compiling it along with 
your main.d. If the latter, you need to be linking with that 
library. However, I recommend you avoid using dmd on the 
command line for now and just use dub to manage your project 
(see below).



This has nothing to do with the json generated by DMD. It's 
referring to a dub.json which is a project configuration file 
for dub. If you create a dub.json, then you can run dub or 
dub build in your project directory and it will automatically 
compile all of your source modules and make sure that all of 
your dependencies (such as libcolorize) are downloaded, 
compiled and link. It's a complete build and package management 
system. You don't need to download your dependencies manually 
or compile from the command line if you are using dub. You can 
read more about the dub.json format at [1].


[1] http://code.dlang.org/package-format



Awesome thanks. Sorry about that linker error, i copied and 
posted the wrong error from a previous compile trial. Anyways i 
managed to fix my problem and my static libraries now compile 
without errors.


I will play with dub a little bit more. Thanks. I just thought i 
would learn from the beginning compiling and linking manually 
within the terminal. I had no idea dub could do all that for me.


What about the dub libraries, what kind of errors do you get if 
you try to use a library not compatible for your system, say OSX 
or Linux? Im assuming the same linking errors but im not sure.