Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread Laeeth Isharc via Digitalmars-d-learn
 I see, thanks! :) I've started liking structs more and more 
 recently as well and been pondering on how to convert a 
 class-based code that looks like this (only the base class 
 has any data):
 it's hard to tell by brief description. but having multiple 
 inheritance
 immediately rings an alarm ring for me. something is 
 very-very-very

 wrong if you need to have a winged whale. ;-)
A real-world example: 
http://www.hdfgroup.org/HDF5/doc/cpplus_RM/hierarchy.html


H5::File is both an H5::Location and H5::CommonFG (but not an 
H5::Object)
H5::Group is both an H5::Object (subclass of H5::Location) and 
H5::CommonFG

H5::Dataset is an H5::Object
i see something named CommonFG here, which seems to good 
thing to

move out of hierarchy altogether.

bwah, i don't even sure that given hierarchy is good for D. C++ 
has no

UFCS, and it's incredibly hard to check if some entity has some
methods/properties in C++, so they have no other choice than to 
work
around that limitations. it may be worthful to redesign the 
whole thing
for D, exploiting D shiny UFCS and metaprogramming features. 
and,

maybe, moving some things to interfaces too.


I just finished reading aldanor's blog, so I know he is slightly 
allergic to naked functions and prefers classes ;)


With Ketmar, I very much agree (predominantly as a user of HDF5 
and less so as an inexperienced D programmr writing a wrapper for 
it).  It's a pain to figure out just how to do simple things 
until you know the H5 library.  You have to create an object for 
file permissions before you even get started, then similarly for 
the data series (datasets) within, another for the dimensions of 
the array, etc etc  - that doesn't fit with the intrinsic nature 
of the domain.


There is a more general question of bindings/wrappers - preserve 
the original structure and naming so existing code can be ported, 
or write a wrapper that makes it easy for the user to accomplish 
his objectives.  It seems like for the bindings preserving the 
library structure is fine, but for the wrapper one might as well 
make things easy.


Eg here https://gist.github.com/Laeeth/9637233db41a11a9d1f4
line 146.  (sorry for duplication and messiness of code, which I 
don't claim to be perfectly written - I wanted to try something 
quickly and have not yet tidied up).


So rather than navigate the Byzantine hierarchy, one can just do 
something like this (which will take a struct of PriceBar - 
date,open,high,low,close - and put it in your desired dataset and 
file, appending or overwriting as you prefer).


dumpDataSpaceVector!PriceBar(file,ticker,array(priceBars[ticker]),DumpMode.truncate);

which is closer to h5py in Python.  (It uses reflection to figure 
out the contents of a non-nested struct, but won't yet cope with 
arrays and nested structs inside).  And of course a full wrapper 
might be a bit more complicated, but I truly think one can do 
better than mapping the HDF5 hierarchy one for one.



Laeeth.


reinterpret array

2015-01-13 Thread Dominikus Dittes Scherkl via Digitalmars-d-learn

Does the following construct hold water?

version(LittleEndian)
{
   /// interpret an array of one type as an array of a different 
type.

   /// if the array has odd length, the highest elements are
   /// not accessible, at worst an empty slice is returned
   inout ref T[] arrayOf(T, V: U[])(inout ref V a)
  pure @safe nothrow
  if(isUnsigned!T  isUnsigned!U)
   {
  return (cast(T*)a.ptr)[0 .. a.length * U.sizeof / T.sizeof];
   }

   unittest
   {
  ubyte a[5] = { 1, 2, 3, 4, 5 };
  auto b = a.arrayOf!uint;
  assert(typeof(b) == uint[]);
  assert(b.length == 1);
  assert(b[0] == 0x04030201);
  assert(b[0] == a[0]); // b is a slice of a
  b[0] = 0x0a0b0c0d; // this will change a
  assert(a == { 13, 12, 11, 10, 5 });

  ushort c[2] = { 257, 512 };
  auto d = c.arrayOf!ubyte;
  assert(d.length == 4);
  assert(d[0] == 1);
  assert(d[1] == 1);
  assert(d[2] == 0);
  assert(d[3] == 2);
   }
}

I assume taking a slice of a pointer uses the GC, so this cannot 
be @nogc, am I right? And I assume it is @save, because if I 
would increase the length of the returned value, the GC will 
automatically re-allocate, but then of course the adress is no 
more the same, yes?




Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 17:08:37 +
Laeeth Isharc via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 I just finished reading aldanor's blog, so I know he is slightly 
 allergic to naked functions and prefers classes ;)
that's due to absense of modules in C/C++. and namespaces aren't of big
help here too. and, of course, due to missing UFCS, that prevents nice
`obj.func()` for free functions. ;-)


signature.asc
Description: PGP signature


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 18:12:44 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 On Tuesday, 13 January 2015 at 16:43:09 UTC, ketmar via 
 Digitalmars-d-learn wrote:
  On Tue, 13 Jan 2015 16:17:51 +
  aldanor via Digitalmars-d-learn 
  digitalmars-d-learn@puremagic.com
  wrote:
 
  This discussion: 
  http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org 
  -- led me wondering if it would be possible to create some 
  crippled version of a class proxy that is based on RefCounted 
  and came up with something like this:
  
  struct Box(T) if (is(T == class)) {
   @disable this();
  
   this(Args...)(Args args) {
   _payload._refCounted.initialize(new T(args));
   }
  
   private {
   struct _Box(T) {
   private T _instance;
  
   ~this() {
   destroy(_instance);
   }
   }
   RefCounted!(_Box!T) _payload;
   }
  
   ~this() {
   }
  
   auto opDispatch(string name, Args...)(Args args) {
   return 
  mixin(_payload._instance.%s(args).format(name));
   }
  }
  
  which lets you create Box!SomeClass(args) and it will be 
  refcounted unless you escape references and do other weird 
  stuff.
  
  It actually sort of seems to work at first glance, at least it 
  seems like it does... But with my D experience being fairly 
  limited I wonder what the potential pitfalls would be?
  
  Full source code with example and stdout:
  https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642
  it's not that hard to make a boxed class. what is really hard 
  is to
  make functions that expects the class itself to accept it's 
  boxed
  variant too and behave correctly with it.
 
  either you have to unbox it (and then hope that it will not 
  leak), or
  write two set of functions, for real class and for boxed one. 
  and
  then you may want to inherit from your class and pass that 
  inherited
  class to one of the functions... and now you have three sets. 
  and so
  on...
 
  as structs can't be inherited, there is no such problem for 
  structs.
 
 That's completely valid. Where it would work though, I think, is 
 if all classes are private/package and only expect/return boxed 
 classes and never the references. This way you sort of get 
 multiple inheritance (for the internal implementation) without 
 polymorphism, but with value semantics and ref counting for the 
 outward interface.
and then you can go with structures in the first place, i think.
remember that you have that k00l `alias this` trick for them!


signature.asc
Description: PGP signature


Re: idiomatic D: what to use instead of pointers in constructing a tree data structure?

2015-01-13 Thread Laeeth Isharc via Digitalmars-d-learn
On Wednesday, 7 January 2015 at 14:59:58 UTC, H. S. Teoh via 
Digitalmars-d-learn wrote:
On Wed, Jan 07, 2015 at 02:52:51PM +, Laeeth Isharc via 
Digitalmars-d-learn wrote:

Another schoolboy question.

Suppose I am constructing a tree (in this case it is an AST).  
In C I
would have a pointer for the child to find the parent, and an 
array or

linked list of pointers to find the children from the parent.

Obviously, I could still use pointers, but that would not be
idiomatic.


Not true. If you're using a tree structure, you *should* use 
pointers.
Unless you're using classes, which are by-reference, in which 
case you

can just use the class as-is. :-)


--T


The GC is allowed to move structs around, as I undestand it.  
Under what circumstances do I get into trouble having a pointer 
to them?




Re: reinterpret array

2015-01-13 Thread Dominikus Dittes Scherkl via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 17:12:42 UTC, Adam D. Ruppe wrote:
On Tuesday, 13 January 2015 at 17:09:32 UTC, Dominikus Dittes 
Scherkl wrote:
I assume taking a slice of a pointer uses the GC, so this 
cannot be @nogc, am I right?


Nope, slicing never allocates, it just takes an address and 
length.


If you append to a slice or increase the length though, the GC 
might reallocate it.


Cool. So I can make the above even @nogc ?
Great.


Re: reinterpret array

2015-01-13 Thread Adam D. Ruppe via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 17:09:32 UTC, Dominikus Dittes 
Scherkl wrote:
I assume taking a slice of a pointer uses the GC, so this 
cannot be @nogc, am I right?


Nope, slicing never allocates, it just takes an address and 
length.


If you append to a slice or increase the length though, the GC 
might reallocate it.


Re: idiomatic D: what to use instead of pointers in constructing a tree data structure?

2015-01-13 Thread Tobias Pankrath via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 17:19:42 UTC, Laeeth Isharc wrote:


The GC is allowed to move structs around, as I undestand it.  
Under what circumstances do I get into trouble having a pointer 
to them?


None, a GC that moves structs around must update every pointer 
afterwards and as far as I know, the standard GC doesn't do that 
(moving things around).


You may not have a pointer inside a struct that points to the 
struct itself. This allows the compiler to elide some copies.


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread aldanor via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 16:43:09 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Tue, 13 Jan 2015 16:17:51 +
aldanor via Digitalmars-d-learn 
digitalmars-d-learn@puremagic.com

wrote:

This discussion: 
http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org 
-- led me wondering if it would be possible to create some 
crippled version of a class proxy that is based on RefCounted 
and came up with something like this:


struct Box(T) if (is(T == class)) {
 @disable this();

 this(Args...)(Args args) {
 _payload._refCounted.initialize(new T(args));
 }

 private {
 struct _Box(T) {
 private T _instance;

 ~this() {
 destroy(_instance);
 }
 }
 RefCounted!(_Box!T) _payload;
 }

 ~this() {
 }

 auto opDispatch(string name, Args...)(Args args) {
 return 
mixin(_payload._instance.%s(args).format(name));

 }
}

which lets you create Box!SomeClass(args) and it will be 
refcounted unless you escape references and do other weird 
stuff.


It actually sort of seems to work at first glance, at least it 
seems like it does... But with my D experience being fairly 
limited I wonder what the potential pitfalls would be?


Full source code with example and stdout:
https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642
it's not that hard to make a boxed class. what is really hard 
is to
make functions that expects the class itself to accept it's 
boxed

variant too and behave correctly with it.

either you have to unbox it (and then hope that it will not 
leak), or
write two set of functions, for real class and for boxed one. 
and
then you may want to inherit from your class and pass that 
inherited
class to one of the functions... and now you have three sets. 
and so

on...

as structs can't be inherited, there is no such problem for 
structs.


That's completely valid. Where it would work though, I think, is 
if all classes are private/package and only expect/return boxed 
classes and never the references. This way you sort of get 
multiple inheritance (for the internal implementation) without 
polymorphism, but with value semantics and ref counting for the 
outward interface.


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread aldanor via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 18:12:45 UTC, aldanor wrote:
On Tuesday, 13 January 2015 at 16:43:09 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Tue, 13 Jan 2015 16:17:51 +
aldanor via Digitalmars-d-learn 
digitalmars-d-learn@puremagic.com

wrote:

This discussion: 
http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org 
-- led me wondering if it would be possible to create some 
crippled version of a class proxy that is based on RefCounted 
and came up with something like this:


struct Box(T) if (is(T == class)) {
@disable this();

this(Args...)(Args args) {
_payload._refCounted.initialize(new T(args));
}

private {
struct _Box(T) {
private T _instance;

~this() {
destroy(_instance);
}
}
RefCounted!(_Box!T) _payload;
}

~this() {
}

auto opDispatch(string name, Args...)(Args args) {
return 
mixin(_payload._instance.%s(args).format(name));

}
}

which lets you create Box!SomeClass(args) and it will be 
refcounted unless you escape references and do other weird 
stuff.


It actually sort of seems to work at first glance, at least 
it seems like it does... But with my D experience being 
fairly limited I wonder what the potential pitfalls would be?


Full source code with example and stdout:
https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642
it's not that hard to make a boxed class. what is really hard 
is to
make functions that expects the class itself to accept it's 
boxed

variant too and behave correctly with it.

either you have to unbox it (and then hope that it will not 
leak), or
write two set of functions, for real class and for boxed 
one. and
then you may want to inherit from your class and pass that 
inherited
class to one of the functions... and now you have three sets. 
and so

on...

as structs can't be inherited, there is no such problem for 
structs.


That's completely valid. Where it would work though, I think, 
is if all classes are private/package and only expect/return 
boxed classes and never the references. This way you sort of 
get multiple inheritance (for the internal implementation) 
without polymorphism, but with value semantics and ref counting 
for the outward interface.
// thanks ketmar for answering another one of my stupid questions 
on n.g. :)


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 18:14:40 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 // thanks ketmar for answering another one of my stupid questions 
 on n.g. :)
ah, 'cmon, your questions aren't stupid at all! ;-)


signature.asc
Description: PGP signature


Re: reinterpret array

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 17:09:31 +
Dominikus Dittes Scherkl via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 /// interpret an array of one type as an array of a different 
 type.
may i point you to this?

  import std.stdio;

  void main () {
ubyte[] a = [42,0,0,0, 155,2,0,0];
auto b = cast(uint[])a;
writeln(b); // [42, 667]
  }


signature.asc
Description: PGP signature


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 18:36:15 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 On Tuesday, 13 January 2015 at 18:19:42 UTC, ketmar via
 Digitalmars-d-learn wrote:
  and then you can go with structures in the first place, i think.
  remember that you have that k00l `alias this` trick for them!
 Which doesn't always help in case of multiple inheritance :( e.g.
 the blasted hdf c++ class hierarchy example.
multiple `alias this` may help here... to some extent. ;-)


signature.asc
Description: PGP signature


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 18:35:15 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 I guess two of my gripes with UFCS is (a) you really have to use 
 public imports in the modules where the target types are defined 
 so you bring all the symbols in whether you want it or not (b) 
 you lose access to private members because it's not the same 
 module anymore (correct me if I'm wrong?). Plus, you need to 
 decorate every single free function with a template constraint.
you can make a package and set protection to `package` instead of
`private`, so your function will still be able to access internal
fields, but package users will not. this feature is often missed
by the people who are used to `public`/`protected`/`private` triad.


signature.asc
Description: PGP signature


Re: reinterpret array

2015-01-13 Thread Dominikus Dittes Scherkl via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 18:25:38 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Tue, 13 Jan 2015 17:09:31 +
Dominikus Dittes Scherkl via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

/// interpret an array of one type as an array of a 
different type.

may i point you to this?

  import std.stdio;

  void main () {
ubyte[] a = [42,0,0,0, 155,2,0,0];
auto b = cast(uint[])a;
writeln(b); // [42, 667]
  }


I see. So this function is completely superfluous :-/
Good to know.

So if I have a function that allowes to do this:

uint a;
a.bit[16] = true;
writeln(a); // 65536

Is it also already available?
Because I somewhat hate it that with D I can create great stuff, 
but it is not necessary because D already has something much 
cooler...


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread aldanor via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 17:08:38 UTC, Laeeth Isharc wrote:
 I see, thanks! :) I've started liking structs more and 
 more recently as well and been pondering on how to convert 
 a class-based code that looks like this (only the base 
 class has any data):
 it's hard to tell by brief description. but having multiple 
 inheritance
 immediately rings an alarm ring for me. something is 
 very-very-very

 wrong if you need to have a winged whale. ;-)
A real-world example: 
http://www.hdfgroup.org/HDF5/doc/cpplus_RM/hierarchy.html


H5::File is both an H5::Location and H5::CommonFG (but not an 
H5::Object)
H5::Group is both an H5::Object (subclass of H5::Location) 
and H5::CommonFG

H5::Dataset is an H5::Object
i see something named CommonFG here, which seems to good 
thing to

move out of hierarchy altogether.

bwah, i don't even sure that given hierarchy is good for D. 
C++ has no

UFCS, and it's incredibly hard to check if some entity has some
methods/properties in C++, so they have no other choice than 
to work
around that limitations. it may be worthful to redesign the 
whole thing
for D, exploiting D shiny UFCS and metaprogramming features. 
and,

maybe, moving some things to interfaces too.


I just finished reading aldanor's blog, so I know he is 
slightly allergic to naked functions and prefers classes ;)


With Ketmar, I very much agree (predominantly as a user of HDF5 
and less so as an inexperienced D programmr writing a wrapper 
for it).  It's a pain to figure out just how to do simple 
things until you know the H5 library.  You have to create an 
object for file permissions before you even get started, then 
similarly for the data series (datasets) within, another for 
the dimensions of the array, etc etc  - that doesn't fit with 
the intrinsic nature of the domain.


There is a more general question of bindings/wrappers - 
preserve the original structure and naming so existing code can 
be ported, or write a wrapper that makes it easy for the user 
to accomplish his objectives.  It seems like for the bindings 
preserving the library structure is fine, but for the wrapper 
one might as well make things easy.


Eg here https://gist.github.com/Laeeth/9637233db41a11a9d1f4
line 146.  (sorry for duplication and messiness of code, which 
I don't claim to be perfectly written - I wanted to try 
something quickly and have not yet tidied up).


So rather than navigate the Byzantine hierarchy, one can just 
do something like this (which will take a struct of PriceBar - 
date,open,high,low,close - and put it in your desired dataset 
and file, appending or overwriting as you prefer).


dumpDataSpaceVector!PriceBar(file,ticker,array(priceBars[ticker]),DumpMode.truncate);

which is closer to h5py in Python.  (It uses reflection to 
figure out the contents of a non-nested struct, but won't yet 
cope with arrays and nested structs inside).  And of course a 
full wrapper might be a bit more complicated, but I truly think 
one can do better than mapping the HDF5 hierarchy one for one.



Laeeth.
In the hierarchy example above (c++ hdf hierarchy link), by using 
UFCS to implement the shared methods (which are achieved by 
multiple inheritance in the c++ counterpart) did you mean 
something like this?


// id.d
struct ID { int id; ... }

// location.d
struct Location { ID _id; alias _id this; ... }

// file.d
public import commonfg; // ugh
struct File { Location _location; alias _location this; ... }

// group.d
public import commonfg;
struct File { Location _location; alias _location this; ... }

// commonfg.d { ... }
enum isContainer(T) = is(T: File) || is(T : Group);
auto method1(T)(T obj, args) if (isContainer!T) { ... }
auto method2(T)(T obj, args) if (isContainer!T) { ... }

I guess two of my gripes with UFCS is (a) you really have to use 
public imports in the modules where the target types are defined 
so you bring all the symbols in whether you want it or not (b) 
you lose access to private members because it's not the same 
module anymore (correct me if I'm wrong?). Plus, you need to 
decorate every single free function with a template constraint.


// another hdf-specific thing here but a good example in general 
is that some functions return you an id for an object which is 
one of the location subtypes (e.g. it could be a File or could be 
a Group depending on run-time conditions), so it kind of feels 
natural to use polymorphism and classes for that, but what would 
you do with the struct approach? The only thing that comes to 
mind is Variant, but it's quite meh to use in practice.


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread aldanor via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 18:19:42 UTC, ketmar via
Digitalmars-d-learn wrote:

and then you can go with structures in the first place, i think.
remember that you have that k00l `alias this` trick for them!

Which doesn't always help in case of multiple inheritance :( e.g.
the blasted hdf c++ class hierarchy example.


Re: reinterpret array

2015-01-13 Thread anonymous via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 20:00:57 UTC, Dominikus Dittes 
Scherkl wrote:

So if I have a function that allowes to do this:

uint a;
a.bit[16] = true;
writeln(a); // 65536

Is it also already available?


a |= 1  16;


Re: Pointers and offsets

2015-01-13 Thread Mike Parker via Digitalmars-d-learn

On 1/14/2015 10:17 AM, Bauss wrote:

On Wednesday, 14 January 2015 at 01:16:54 UTC, Bauss wrote:

Is it possible to access a pointer by its offsets.
Ex. write a 32bit integer to a byte pointer at ex. offset 4.

To give an example in C# you can do this:
fixed (byte* Packet = Buffer) // Buffer would be a byte array

And then to set the value of a specific offset
*((TYPE*)(Packet + OFFSET))

Where TYPE could be replaced by ex. uint and OFFSET by 4

I tried to look here:
http://dlang.org/arrays.html

But couldn't seem to find anything like it.


Can't seem to edit OP so at:


The forum is a web interface to a newsgroup, which also has a mailing 
list interface. So no, no editing.



*((TYPE*)(Packet + OFFSET))

It should be:
*((TYPE*)(Packet + OFFSET)) = VALUE;

VALUE has to be of the same type as TYPE of course.


void main()
{
ubyte[16] bytes;
for( int i=0; i4; ++i )
{
*(cast( int* )( bytes.ptr + (i*4))) = i;
}

import std.stdio : writeln;
writeln( cast( int[] )bytes );
}


Re: Map Lambda with Side-Effects

2015-01-13 Thread Tobias Pankrath via Digitalmars-d-learn



Is it possible to
- detect that a lambda is has-side-effects and that
- the map hasn't been used?


Thing is: I'm regularly doing that on purpose.

Actually, isn't your closure even weakly pure in your example, 
because arr is part of the closure and thus an argument to it.


Re: Pointers and offsets

2015-01-13 Thread Bauss via Digitalmars-d-learn

On Wednesday, 14 January 2015 at 01:16:54 UTC, Bauss wrote:

Is it possible to access a pointer by its offsets.
Ex. write a 32bit integer to a byte pointer at ex. offset 4.

To give an example in C# you can do this:
fixed (byte* Packet = Buffer) // Buffer would be a byte array

And then to set the value of a specific offset
*((TYPE*)(Packet + OFFSET))

Where TYPE could be replaced by ex. uint and OFFSET by 4

I tried to look here:
http://dlang.org/arrays.html

But couldn't seem to find anything like it.


Can't seem to edit OP so at:
*((TYPE*)(Packet + OFFSET))

It should be:
*((TYPE*)(Packet + OFFSET)) = VALUE;

VALUE has to be of the same type as TYPE of course.


Pointers and offsets

2015-01-13 Thread Bauss via Digitalmars-d-learn

Is it possible to access a pointer by its offsets.
Ex. write a 32bit integer to a byte pointer at ex. offset 4.

To give an example in C# you can do this:
fixed (byte* Packet = Buffer) // Buffer would be a byte array

And then to set the value of a specific offset
*((TYPE*)(Packet + OFFSET))

Where TYPE could be replaced by ex. uint and OFFSET by 4

I tried to look here:
http://dlang.org/arrays.html

But couldn't seem to find anything like it.


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Mon, 12 Jan 2015 22:07:13 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 I see, thanks! :) I've started liking structs more and more 
 recently as well and been pondering on how to convert a 
 class-based code that looks like this (only the base class has 
 any data):
it's hard to tell by brief description. but having multiple inheritance
immediately rings an alarm ring for me. something is very-very-very
wrong if you need to have a winged whale. ;-)


signature.asc
Description: PGP signature


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Mon, 12 Jan 2015 23:06:16 +
jmh530 via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 I had seen some stuff on alias thing, but I hadn't bothered to
 try to understand it until now. If I'm understanding the first
 example a href=http://dlang.org/class.html#AliasThis;here/a,
 alias this let's you refer to x in s by writing either s.x (as
 normally) or just s. That didn't seem that interesting, but then
 I found a href=http://3d.benjamin-thaut.de/?p=90;example/a
 where they alias this'ed a struct method. That's pretty
 interesting.
there is nice page by p0nce and it shows nice and simple `alias this`
trick usage:
http://p0nce.github.io/d-idioms/#Extending-a-struct-with-alias-this

and i have stream.d module in my IV package
( http://repo.or.cz/w/iv.d.git/tree ), which works with i/o streams
by testing if passed struct/class has necessary methods (`isReadable!`,
`isWriteable!`, `isSeekable!`, etc.


signature.asc
Description: PGP signature


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Mon, 12 Jan 2015 22:07:13 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 I see, thanks! :) I've started liking structs more and more 
 recently as well and been pondering on how to convert a 
 class-based code that looks like this (only the base class has 
 any data):
p.s. can't you convert most of that to free functions? thanks to UFCS
you'll be able to use them with `obj.func` notation. and by either
defining `package` protection for class fields, or simply writing that
functions in the same module they will have access to internal object
stuff.

and if you can return `obj` from each function, you can go with
templates and chaining. ;-)


signature.asc
Description: PGP signature


Re: Endless static this call when used a thread in it

2015-01-13 Thread Daniel Kozák via Digitalmars-d-learn
V Tue, 13 Jan 2015 13:53:09 +
tcak via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
napsáno:

 I have written the following code:
 
 test.d
 ==
 import core.thread;
 import std.stdio;
 
 void threadFunc(){
   writeln(Thread func);
 }
 
 public static this(){
   auto t = new Thread( threadFunc );
   t.start();
 
   writeln(Static init);
 }
 
 void main(){
   writeln(End of main);
 }
 
 
 run
 ==
 rdmd test.d
 
 
 result
 ==
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Sta...
 
 Is this normal, what's happening?

try

shared static this(){
...

instead of

public static this(){



Re: Endless static this call when used a thread in it

2015-01-13 Thread tcak via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 13:53:11 UTC, tcak wrote:

I have written the following code:

test.d
==
import core.thread;
import std.stdio;

void threadFunc(){
writeln(Thread func);
}

public static this(){
auto t = new Thread( threadFunc );
t.start();

writeln(Static init);
}

void main(){
 writeln(End of main);
}


run
==
rdmd test.d


result
==
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Sta...

Is this normal, what's happening?


When I defined static init with shared

public shared static this()

it works normal now. But it doesn't explain above issue. What's 
the relation between a new thread and a module's initialiser?


Re: Endless static this call when used a thread in it

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 13:56:05 +
tcak via Digitalmars-d-learn digitalmars-d-learn@puremagic.com wrote:

 it works normal now. But it doesn't explain above issue. What's 
 the relation between a new thread and a module's initialiser?
yes.


signature.asc
Description: PGP signature


Re: Endless static this call when used a thread in it

2015-01-13 Thread Daniel Kozák via Digitalmars-d-learn
V Tue, 13 Jan 2015 13:56:05 +
tcak via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
napsáno:

 On Tuesday, 13 January 2015 at 13:53:11 UTC, tcak wrote:
  I have written the following code:
 
  test.d
  ==
  import core.thread;
  import std.stdio;
 
  void threadFunc(){
  writeln(Thread func);
  }
 
  public static this(){
  auto t = new Thread( threadFunc );
  t.start();
 
  writeln(Static init);
  }
 
  void main(){
   writeln(End of main);
  }
 
 
  run
  ==
  rdmd test.d
 
 
  result
  ==
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Static init
  Thread func
  Sta...
 
  Is this normal, what's happening?
 
 When I defined static init with shared
 
 public shared static this()
 
 it works normal now. But it doesn't explain above issue. What's 
 the relation between a new thread and a module's initialiser?

I am not sure but my guess is

static this needs to be called before anything else in module so when
you try call threadFunc it looks if static this has been called and
finished which is not true so it call it again



Re: Endless static this call when used a thread in it

2015-01-13 Thread Daniel Kozak via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 14:02:45 UTC, Daniel Kozák via 
Digitalmars-d-learn wrote:

V Tue, 13 Jan 2015 13:56:05 +
tcak via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
napsáno:


On Tuesday, 13 January 2015 at 13:53:11 UTC, tcak wrote:
 I have written the following code:

 test.d
 ==
 import core.thread;
 import std.stdio;

 void threadFunc(){
writeln(Thread func);
 }

 public static this(){
auto t = new Thread( threadFunc );
t.start();

writeln(Static init);
 }

 void main(){
  writeln(End of main);
 }


 run
 ==
 rdmd test.d


 result
 ==
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Static init
 Thread func
 Sta...

 Is this normal, what's happening?

When I defined static init with shared

public shared static this()

it works normal now. But it doesn't explain above issue. 
What's the relation between a new thread and a module's 
initialiser?


I am not sure but my guess is

static this needs to be called before anything else in module 
so when
you try call threadFunc it looks if static this has been called 
and

finished which is not true so it call it again

And here is better explanation

http://dlang.org/module.html#staticorder

Static constructors are code that gets executed to initialize a 
module or a class before the main() function gets called.

...

Static constructors and static destructors run on thread local 
data, and are run whenever threads are created or destroyed.


Re: Read from stdin without blocking

2015-01-13 Thread Adam D. Ruppe via Digitalmars-d-learn
The operating system does line buffering, so you'll need to turn 
that off. The function is tcssetattr() on Posix and 
SetConsoleMode on Windows.


My terminal.d does this in struct ctors and dtors:

https://github.com/adamdruppe/arsd/blob/master/terminal.d

example usage:
http://arsdnet.net/dcode/book/chapter_12/07/input.d

The RealTimeConsoleInput struct turns off buffering and has 
functions like getch() and kbhit() to fetch individual characters 
from it.


That's not quite the same as getting everything that's available, 
but might be useful to you.




Most efficient way I think though is to turn off buffering with 
the OS calls, then you can set stdin to be nonblocking and read 
chunks off it with ordinary read() or ReadFile calls.


Re: Map Lambda with Side-Effects

2015-01-13 Thread John Colvin via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 10:21:12 UTC, Tobias Pankrath 
wrote:

On Tuesday, 13 January 2015 at 10:06:26 UTC, bearophile wrote:

Nordlöw:


Has there been any discussions on
making map require pure functions now that we have each?


Perhaps I'd like Phobos map and filter to be annotated with 
pure and to have a template constraint that requires their 
mapping/filtering functions to be strongly pure.


Bye,
bearophile


Please not.


It should be obviously documented that the number of applications 
of the function is not limited to once-per-element and that 
evaluation doesn't necessarily happen in-order. I forget and am 
re-reminded of this once every few months, despite how central it 
is to ranges in general.


It can still be useful to use impure functions with it though, as 
long as you consider what is actually going on.


Re: Accessing class with module name as Java's

2015-01-13 Thread tcak via Digitalmars-d-learn


Ah, I just re-read your OP. Your already at this point :)


Since everybody has understood the problem, and nobody could have 
come up with a solution yet, my idea is that:


HttpSocketConnectionRequest.d
=
module net.http.HttpSocketConnectionRequest;

module class HttpSocketConnectionRequest{}


If compiler allowed module keyword to be used as an attribute 
for ONLY ONE class or struct definition in the module as above, 
module's name could be used as you were to be pointing to class 
directly.


This would let us (and Phobos developers) to be able to separate 
code files into multiple files much easily, and solve my problem 
as well :).


Re: Map Lambda with Side-Effects

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 10:06:25 +
bearophile via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 Nordlöw:
 
  Has there been any discussions on
  making map require pure functions now that we have each?
 
 Perhaps I'd like Phobos map and filter to be annotated with 
 pure and to have a template constraint that requires their 
 mapping/filtering functions to be strongly pure.

that will effectively rule out any usage of some global vars or other
external state, turning it into either unnecessary mess, or unusable
theoretical crap.

what i think should be written in big red letters in docs is there is
no guarantees about how many times labmda will be called, with which
args and in which order. so if someone wants to shoot in his foot, he
can ignore that warning and do crazy shooting.


signature.asc
Description: PGP signature


Re: Map Lambda with Side-Effects

2015-01-13 Thread bearophile via Digitalmars-d-learn

Nordlöw:


Has there been any discussions on
making map require pure functions now that we have each?


Perhaps I'd like Phobos map and filter to be annotated with 
pure and to have a template constraint that requires their 
mapping/filtering functions to be strongly pure.


Bye,
bearophile


Re: Map Lambda with Side-Effects

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 11:26:01 +
bearophile via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 ketmar:
 
  that will effectively rule out any usage of some global vars or 
  other
  external state, turning it into either unnecessary mess, or 
  unusable
  theoretical crap.
 
 Unusable theoretical crap is better than the current trap :-)
in no way. this just turns Phobos into the same unusable crap, removing
the whole sense of having good standard library.

 We hare pure in D, but still we have not grown up to actually 
 use it in Phobos, for higher order functions, or parallelism.
let an user choose if he wants pure or impure HOF args. just make a big
warning in documentation about unpredictability of HOFs with
side-effects and this will be enough, i believe.


signature.asc
Description: PGP signature


Re: Accessing class with module name as Java's

2015-01-13 Thread Colin via Digitalmars-d-learn

Have the following directory structure?

~/testModule$ find . -print
.
./net
./net/http_.d# **
./net/http
./net/http/Mod1.d
./net/http/Mod2.d
./main.d

** I put the _ here to make it seperate from the net/http
directory. Probably, a better solution exists, this was hacked 
together quickly :)


In http_.d have:
module net.http_;  // again, a better solution surely exists
public import net.http.Mod1;
public import net.http.Mod2;

Then in your main have
import net.http_;

You can then use whatever's in Mod1 and Mod2 modules.
In your case, Mod1/Mod2 will be like
HTTPConnectionRequest/HTTPConnectionResponse and will only
contain a single class. This works for me.

You can also go a little further and have renamed imports.
Something like:
public import Renamed = net.http.Mod2;

Then in main.d call it with:
Renamed.Mod2 mod2 = new renamed.Mod2;

Feels just like Java :)


Re: Map Lambda with Side-Effects

2015-01-13 Thread Tobias Pankrath via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 10:06:26 UTC, bearophile wrote:

Nordlöw:


Has there been any discussions on
making map require pure functions now that we have each?


Perhaps I'd like Phobos map and filter to be annotated with 
pure and to have a template constraint that requires their 
mapping/filtering functions to be strongly pure.


Bye,
bearophile


Please not.


Re: Map Lambda with Side-Effects

2015-01-13 Thread bearophile via Digitalmars-d-learn

ketmar:

that will effectively rule out any usage of some global vars or 
other
external state, turning it into either unnecessary mess, or 
unusable

theoretical crap.


Unusable theoretical crap is better than the current trap :-)

We hare pure in D, but still we have not grown up to actually 
use it in Phobos, for higher order functions, or parallelism.


Bye,
bearophile


Re: Accessing class with module name as Java's

2015-01-13 Thread Colin via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 09:22:04 UTC, Colin wrote:

Have the following directory structure?

~/testModule$ find . -print
.
./net
./net/http_.d# **
./net/http
./net/http/Mod1.d
./net/http/Mod2.d
./main.d

** I put the _ here to make it seperate from the net/http
directory. Probably, a better solution exists, this was hacked 
together quickly :)


In http_.d have:
module net.http_;  // again, a better solution surely exists
public import net.http.Mod1;
public import net.http.Mod2;

Then in your main have
import net.http_;

You can then use whatever's in Mod1 and Mod2 modules.
In your case, Mod1/Mod2 will be like
HTTPConnectionRequest/HTTPConnectionResponse and will only
contain a single class. This works for me.

You can also go a little further and have renamed imports.
Something like:
public import Renamed = net.http.Mod2;

Then in main.d call it with:
Renamed.Mod2 mod2 = new renamed.Mod2;

Feels just like Java :)


Ah, I just re-read your OP. Your already at this point :)


Re: Map Lambda with Side-Effects

2015-01-13 Thread Tobias Pankrath via Digitalmars-d-learn

Unusable theoretical crap is better than the current trap :-)

We hare pure in D, but still we have not grown up to actually 
use it in Phobos, for higher order functions, or parallelism.


I don't think that Nordlöw presented a serious trap. This might 
lead to bugs, yes, like anything else, for example: void 
foo(int[] arr) { ... arr ~= ... }


Same error, if you expect arr to be changed outside the function. 
In the case of Nordlöw: If you add a warning* it will issue many 
warnings for a huge amount of perfectly fine code making the 
warning useless. Forbidding it, would be even worse (since the 
code wouldn't work, a more verbose alternative needs to be used 
etc ..). For what? To prevent a possible bug that is easily found 
and fixed? Wrong trade-off if you ask me.



* When should the warning actually be issued? Whenever a closure 
is passed to map? Whenever a closure passed to map closes over 
something where hasAliasing!T is true?


Unicode exception raise when replacing underscore with space

2015-01-13 Thread Nordlöw

I get

core.exception.UnicodeException@src/rt/util/utf.d(290):

in a call to

std.string.tr(x, `_`, ` `)

for a badly encode string x. Is it really needed to do 
auto-decoding here?


Isn't the encoding of underscore and space uniquely one by byte 
in UTF-8?


What do I need to do/add to avoid auto-decoding here?


Endless static this call when used a thread in it

2015-01-13 Thread tcak via Digitalmars-d-learn

I have written the following code:

test.d
==
import core.thread;
import std.stdio;

void threadFunc(){
writeln(Thread func);
}

public static this(){
auto t = new Thread( threadFunc );
t.start();

writeln(Static init);
}

void main(){
 writeln(End of main);
}


run
==
rdmd test.d


result
==
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Static init
Thread func
Sta...

Is this normal, what's happening?


Re: Accessing class with module name as Java's

2015-01-13 Thread Daniel Kozák via Digitalmars-d-learn
V Tue, 13 Jan 2015 10:58:27 +
tcak via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
napsáno:

 
  Ah, I just re-read your OP. Your already at this point :)
 
 Since everybody has understood the problem, and nobody could have 
 come up with a solution yet, my idea is that:
 
 HttpSocketConnectionRequest.d
 =
 module net.http.HttpSocketConnectionRequest;
 
 module class HttpSocketConnectionRequest{}
 
 
 If compiler allowed module keyword to be used as an attribute 
 for ONLY ONE class or struct definition in the module as above, 
 module's name could be used as you were to be pointing to class 
 directly.
 
 This would let us (and Phobos developers) to be able to separate 
 code files into multiple files much easily, and solve my problem 
 as well :).

There is a way around:
-- main.d --

import std.stdio;
import net.http;

void main(string[] arg)
{
auto p = new net.http.HttpSocketConnectionRequest();
}

-- net/http/package.d --
module net.http;
private import net.http.http_socket_connection_request;

-- net/http/http_socket_connection_request.d --
module net.http.http_socket_connection_request;

class HttpSocketConnectionRequest {

}

or

-- main.d --

import std.stdio;
static import net.http;

void main(string[] arg)
{
auto p = new net.http.HttpSocketConnectionRequest();
}

-- net/http/package.d --
module net.http;
import net.http.http_socket_connection_request;

-- net/http/http_socket_connection_request.d --
module net.http.http_socket_connection_request;

class HttpSocketConnectionRequest {

}




Re: Map Lambda with Side-Effects

2015-01-13 Thread bearophile via Digitalmars-d-learn

ketmar:

in no way. this just turns Phobos into the same unusable crap, 
removing the whole sense of having good standard library.


If your language has purity, and it doesn't use it where it 
matters, you have removed its sense of having purity. So if you 
are right then purity in D is useless and Rust has chosen better 
than D on this.


Bye,
bearophile


Re: Unicode exception raise when replacing underscore with space

2015-01-13 Thread Daniel Kozák via Digitalmars-d-learn
V Tue, 13 Jan 2015 12:32:15 +
Nordlöw via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
napsáno:

 I get
 
  core.exception.UnicodeException@src/rt/util/utf.d(290):
 
 in a call to
 
  std.string.tr(x, `_`, ` `)
 
 for a badly encode string x. Is it really needed to do 
 auto-decoding here?
 
 Isn't the encoding of underscore and space uniquely one by byte 
 in UTF-8?
 
 What do I need to do/add to avoid auto-decoding here?

std.array.replace(x, `_`, ` `);



Read from stdin without blocking

2015-01-13 Thread Benjamin Thaut via Digitalmars-d-learn
I want to read all input from stdin without blocking. That means 
I simply want to read the remaining input from stdin. All ways I 
tried so far always end up in me waiting for the user to enter 
additional input, which is not what I want.


I tried around a lot with D's files / streams but couldn't find 
any way to do that.


Any help is appreciated.

Kind Regards
Benjamin Thaut


Re: Cast a struct to void*

2015-01-13 Thread John Colvin via Digitalmars-d-learn
On Friday, 9 January 2015 at 19:03:04 UTC, Steven Schveighoffer 
wrote:

On 1/9/15 1:50 PM, John Colvin wrote:

On Friday, 9 January 2015 at 18:35:56 UTC, anonymous wrote:

On Friday, 9 January 2015 at 18:25:42 UTC, John Colvin wrote:

struct S
{
  void* p;
}

void main()
{
  S s;
  auto a = cast(void*)s; //Error: e2ir: cannot cast s of 
type S to

type void*


This is actually a compiler bug!


So it is! The same happens with e.g. casting void* to string. 
Annoyingly it passes __traits(compiles, ...)


Re: How to do equivalent of npm install --save with dub?

2015-01-13 Thread Mike Parker via Digitalmars-d-learn

On 1/13/2015 10:01 AM, Andrew Grace wrote:

I am trying to play with D, but I'm getting stuck with the DUB package
manager.  If use DUB to download a package to my project, how do I get
DUB to add what I downloaded to the dub.json file? I have tried DUB
--fetch --cache=local http-parser (for example).  It downloads the
package, but then nothing is added to the list of dependencies.

I'd appreciate any help.


As Rikki said, you don't need to download anything. You've got it rather 
backwards. *You* add the dependency to the dub.json and then *DUB* will 
pull it down and compile it automatically when you execute 'dub' or 'dub 
build' in the same directory as the configuration file.


See the dub.json at [1] as an example. It's a simple little TicTacToe 
game that has a dependency on DerelictSDL2, which, if you look at [2], 
you'll find has a dependency on DerelictUtil. If you clone the source, 
cd into the top-level directory and execute 'dub', then DUB will pull 
down both DerelictUtil and DerelictSDL2, compile them into libraries, 
compile the game code, then link it with the libraries and run the 
executable.


[1] https://github.com/aldacron/t3/blob/master/dub.json
[2] https://github.com/DerelictOrg/DerelictSDL2/blob/master/package.json


A naive attempt at a refcounted class proxy

2015-01-13 Thread aldanor via Digitalmars-d-learn
This discussion: 
http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org 
-- led me wondering if it would be possible to create some 
crippled version of a class proxy that is based on RefCounted and 
came up with something like this:


struct Box(T) if (is(T == class)) {
@disable this();

this(Args...)(Args args) {
_payload._refCounted.initialize(new T(args));
}

private {
struct _Box(T) {
private T _instance;

~this() {
destroy(_instance);
}
}
RefCounted!(_Box!T) _payload;
}

~this() {
}

auto opDispatch(string name, Args...)(Args args) {
return mixin(_payload._instance.%s(args).format(name));
}
}

which lets you create Box!SomeClass(args) and it will be 
refcounted unless you escape references and do other weird stuff.


It actually sort of seems to work at first glance, at least it 
seems like it does... But with my D experience being fairly 
limited I wonder what the potential pitfalls would be?


Full source code with example and stdout:
https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread aldanor via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 08:33:57 UTC, ketmar via 
Digitalmars-d-learn wrote:

On Mon, 12 Jan 2015 22:07:13 +
aldanor via Digitalmars-d-learn 
digitalmars-d-learn@puremagic.com

wrote:

I see, thanks! :) I've started liking structs more and more 
recently as well and been pondering on how to convert a 
class-based code that looks like this (only the base class has 
any data):
it's hard to tell by brief description. but having multiple 
inheritance
immediately rings an alarm ring for me. something is 
very-very-very

wrong if you need to have a winged whale. ;-)
A real-world example: 
http://www.hdfgroup.org/HDF5/doc/cpplus_RM/hierarchy.html


H5::File is both an H5::Location and H5::CommonFG (but not an 
H5::Object)
H5::Group is both an H5::Object (subclass of H5::Location) and 
H5::CommonFG

H5::Dataset is an H5::Object


Re: D Beginner Trying Manual Memory Management

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 16:08:15 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 On Tuesday, 13 January 2015 at 08:33:57 UTC, ketmar via 
 Digitalmars-d-learn wrote:
  On Mon, 12 Jan 2015 22:07:13 +
  aldanor via Digitalmars-d-learn 
  digitalmars-d-learn@puremagic.com
  wrote:
 
  I see, thanks! :) I've started liking structs more and more 
  recently as well and been pondering on how to convert a 
  class-based code that looks like this (only the base class has 
  any data):
  it's hard to tell by brief description. but having multiple 
  inheritance
  immediately rings an alarm ring for me. something is 
  very-very-very
  wrong if you need to have a winged whale. ;-)
 A real-world example: 
 http://www.hdfgroup.org/HDF5/doc/cpplus_RM/hierarchy.html
 
 H5::File is both an H5::Location and H5::CommonFG (but not an 
 H5::Object)
 H5::Group is both an H5::Object (subclass of H5::Location) and 
 H5::CommonFG
 H5::Dataset is an H5::Object
i see something named CommonFG here, which seems to good thing to
move out of hierarchy altogether.

bwah, i don't even sure that given hierarchy is good for D. C++ has no
UFCS, and it's incredibly hard to check if some entity has some
methods/properties in C++, so they have no other choice than to work
around that limitations. it may be worthful to redesign the whole thing
for D, exploiting D shiny UFCS and metaprogramming features. and,
maybe, moving some things to interfaces too.


signature.asc
Description: PGP signature


Re: A naive attempt at a refcounted class proxy

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 16:17:51 +
aldanor via Digitalmars-d-learn digitalmars-d-learn@puremagic.com
wrote:

 This discussion: 
 http://forum.dlang.org/thread/bqtcdpsopxmnfbjyr...@forum.dlang.org 
 -- led me wondering if it would be possible to create some 
 crippled version of a class proxy that is based on RefCounted and 
 came up with something like this:
 
 struct Box(T) if (is(T == class)) {
  @disable this();
 
  this(Args...)(Args args) {
  _payload._refCounted.initialize(new T(args));
  }
 
  private {
  struct _Box(T) {
  private T _instance;
 
  ~this() {
  destroy(_instance);
  }
  }
  RefCounted!(_Box!T) _payload;
  }
 
  ~this() {
  }
 
  auto opDispatch(string name, Args...)(Args args) {
  return mixin(_payload._instance.%s(args).format(name));
  }
 }
 
 which lets you create Box!SomeClass(args) and it will be 
 refcounted unless you escape references and do other weird stuff.
 
 It actually sort of seems to work at first glance, at least it 
 seems like it does... But with my D experience being fairly 
 limited I wonder what the potential pitfalls would be?
 
 Full source code with example and stdout:
 https://gist.github.com/aldanor/d5fb5e45ddf3dd2cb642
it's not that hard to make a boxed class. what is really hard is to
make functions that expects the class itself to accept it's boxed
variant too and behave correctly with it.

either you have to unbox it (and then hope that it will not leak), or
write two set of functions, for real class and for boxed one. and
then you may want to inherit from your class and pass that inherited
class to one of the functions... and now you have three sets. and so
on...

as structs can't be inherited, there is no such problem for structs.


signature.asc
Description: PGP signature


Re: reinterpret array

2015-01-13 Thread Dominikus Dittes Scherkl via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 20:11:45 UTC, anonymous wrote:
On Tuesday, 13 January 2015 at 20:00:57 UTC, Dominikus Dittes 
Scherkl wrote:

So if I have a function that allowes to do this:

uint a;
a.bit[16] = true;
writeln(a); // 65536

Is it also already available?


a |= 1  16;


Of course you can calculate it, but the
syntax looks quite different if you want to do
a.bit[22] = false:

a = ~(116);

Or if you want to test a bit:

if(a.bit[16])

instead of

if(a  (116))

much more convenient for arrays:

ulong[100] a;

a.bit[3000] = true;

doing this directly with shifts is lousy (and error prone)

But ok. I see, it's not really awesome :-/


Re: reinterpret array

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 20:52:13 +
Dominikus Dittes Scherkl via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

 On Tuesday, 13 January 2015 at 20:11:45 UTC, anonymous wrote:
  On Tuesday, 13 January 2015 at 20:00:57 UTC, Dominikus Dittes 
  Scherkl wrote:
  So if I have a function that allowes to do this:
 
  uint a;
  a.bit[16] = true;
  writeln(a); // 65536
 
  Is it also already available?
 
  a |= 1  16;
 
 Of course you can calculate it, but the
 syntax looks quite different if you want to do
 a.bit[22] = false:
 
 a = ~(116);
 
 Or if you want to test a bit:
 
 if(a.bit[16])
 
 instead of
 
 if(a  (116))
 
 much more convenient for arrays:
 
 ulong[100] a;
 
 a.bit[3000] = true;
 
 doing this directly with shifts is lousy (and error prone)
 
 But ok. I see, it's not really awesome :-/
it's not better than using something like this:

  a.bitSet(22);
  a.bitReset(30);
  if (a.bit(16)) { ... }

you can easily do this with UFCS. you can even write some templates to
convert it to bit operations in compile time.


signature.asc
Description: PGP signature


Re: reinterpret array

2015-01-13 Thread ketmar via Digitalmars-d-learn
On Tue, 13 Jan 2015 20:00:56 +
Dominikus Dittes Scherkl via Digitalmars-d-learn
digitalmars-d-learn@puremagic.com wrote:

p.s. i don't intend to stop you from doing what you want to do, in no
way. i was just trying to show you some things that you can
accidentally missed. sorry if it looks like stop it, we already have
one and nobody should need more of that!


signature.asc
Description: PGP signature


Re: Unicode exception raise when replacing underscore with space

2015-01-13 Thread Daniel Kozak via Digitalmars-d-learn

On Tuesday, 13 January 2015 at 20:30:16 UTC, Nordlöw wrote:
On Tuesday, 13 January 2015 at 13:01:56 UTC, Daniel Kozák via 
Digitalmars-d-learn wrote:

What do I need to do/add to avoid auto-decoding here?


std.array.replace(x, `_`, ` `);


Thanks! What about adding See alsos in the docs that relate 
these two with respect to auto-decoding?


I am not sure, it doesn`t exactly do the same. And to be fair 
std.array.replace use internaly std.algorithm.find which use in 
some scenario auto-decoding. So to be sure no autodecoding 
occured you must used something like that:


string x = some_text;
auto res = std.array.replace(cast(byte[])x, [byte('_')], 
[byte(' ')]);

writeln(cast(string)res);


Re: Unicode exception raise when replacing underscore with space

2015-01-13 Thread Nordlöw
On Tuesday, 13 January 2015 at 13:01:56 UTC, Daniel Kozák via 
Digitalmars-d-learn wrote:

What do I need to do/add to avoid auto-decoding here?


std.array.replace(x, `_`, ` `);


Thanks! What about adding See alsos in the docs that relate these 
two with respect to auto-decoding?


Re: Map Lambda with Side-Effects

2015-01-13 Thread Nordlöw

On Tuesday, 13 January 2015 at 07:35:53 UTC, Nordlöw wrote:

Somewhat related to

https://github.com/D-Programming-Language/phobos/pull/2024

I wonder about the soundness of `map` in


```D
import std.algorithm, std.range, std.stdio;
void main(string[] args)
{
  long[] arr;
  const n = 3;
  iota(n).map!(a = arr ~= a);
  writeln(arr);
  writeln(iota(n).map!(a = arr ~= a));
  writeln(arr);
}
```

that prints

```D
[]
[[0], [0, 1], [0, 1, 2]]
[0, 1, 2]
```

Shouldn't a warning at least be issued for return-ignoring calls
to map with mutating lambdas? Has there been any discussions on
making map require pure functions now that we have each? I guess
a new function, say `mapPure`, may be neccessary as adding such 
a

restriction to the lambda will break too much code right?


To clarify:

I f() is stronly pure function then DMD since 2.066 will warn 
about


   f();

, that is, upon return-discarding calls to strongly pure function.

I believe

iota(n).map!(a = arr ~= a);

is a very similar mistake done and if possible should be warned 
about.


Is it possible to
- detect that a lambda is has-side-effects and that
- the map hasn't been used?

If this can't (yet) be detected in compiled-time what about 
issuing an exception in the destructor of Map to detect this?


Destroy!


Re: reinterpret array

2015-01-13 Thread bearophile via Digitalmars-d-learn

anonymous:


a |= 1  16;


In D there's also the 2 ^^ x syntax available.

Bye,
bearophile


Re: reinterpret array

2015-01-13 Thread anonymous via Digitalmars-d-learn
On Tuesday, 13 January 2015 at 20:52:15 UTC, Dominikus Dittes 
Scherkl wrote:

Of course you can calculate it, but the
syntax looks quite different if you want to do
a.bit[22] = false:

a = ~(116);

Or if you want to test a bit:

if(a.bit[16])

instead of

if(a  (116))

much more convenient for arrays:

ulong[100] a;

a.bit[3000] = true;

doing this directly with shifts is lousy (and error prone)

But ok. I see, it's not really awesome :-/


I didn't mean to put a stop to your idea just because we have 
bitwise operators. You're totally right: They're somewhat 
cumbersome and easy to get wrong.


We also have std.bitmanip.BitArray which is what you're after, I 
think:


import std.bitmanip: BitArray;
BitArray ba;
ba.length = 3001;
ba[3000] = true;


Re: reinterpret array

2015-01-13 Thread Artur Skawina via Digitalmars-d-learn
On 01/13/15 21:52, Dominikus Dittes Scherkl via Digitalmars-d-learn wrote:
 On Tuesday, 13 January 2015 at 20:11:45 UTC, anonymous wrote:
 On Tuesday, 13 January 2015 at 20:00:57 UTC, Dominikus Dittes Scherkl wrote:
 So if I have a function that allowes to do this:

 uint a;
 a.bit[16] = true;
 writeln(a); // 65536

 Is it also already available?

 a |= 1  16;
 
 Of course you can calculate it, but the
 syntax looks quite different if you want to do
 a.bit[22] = false:
 
 a = ~(116);
 
 Or if you want to test a bit:
 
 if(a.bit[16])
 
 instead of
 
 if(a  (116))
 
 much more convenient for arrays:
 
 ulong[100] a;
 
 a.bit[3000] = true;
 
 doing this directly with shifts is lousy (and error prone)
 
 But ok. I see, it's not really awesome :-/

It's neat, but the real problems with it are:
1) obfuscation - it hides those trivial bit ops behind layers of
functions and operator overloads, which everyone reading the
code must then figure out;
2) safety - `a.bit` could potentially outlive `a`; D does not
handle object lifetimes, so there's no 100% safe way to prevent
such bugs.

Hence you probably don't actually want to use this.


   struct Bits(E, size_t UB=1) {
  E* e;

  bool opIndexAssign(bool v, size_t idx) {
 auto o = idx/(E.sizeof*8);
 idx %= E.sizeof*8;
 if (o=UB)
assert (0);
 if (v)
e[o] |=   1Lidx;
 else
e[o] = ~(1Lidx);
 return v;
  }
  bool opIndex(size_t idx) {
 auto o = idx/(E.sizeof*8);
 idx %= E.sizeof*8;
 if (o=UB)
assert (0);
 return !!(e[o]  1Lidx);
  }
   }

   auto bit(E)(ref E e) @property {
  static if (is(E:A[L], A, size_t L))
 return Bits!(typeof(e[0]), L)(e.ptr);
  else
 return Bits!E(e);
   }


artur