Re: Is it possible to avoid call to destructor for structs?

2017-09-25 Thread Adrian Matoga via Digitalmars-d-learn

On Sunday, 24 September 2017 at 19:52:52 UTC, bitwise wrote:

On Sunday, 24 September 2017 at 17:11:26 UTC, Haridas wrote:
In the following code, Bar is an element of struct Foo. Is 
there a way to avoid a call to ~Bar when ~Foo is getting 
executed?




Don't construct it to begin with.

struct Bar {
import std.stdio : writeln;
int a = 123;
void boink() { writeln(a); }
~this(){ writeln("bar dtor"); }
}

struct Foo
{
ubyte[Bar.sizeof] barBuffer;
Bar* _bar = null;

ref Bar bar()
{
import std.conv : emplace;

if(!_bar) {
_bar = cast(Bar*)barBuffer.ptr;
emplace(_bar);
}

return *_bar;
}
}


You shouldn't store the pointer to barBuffer inside Foo. The 
language allows moving the structure around with a simple memcpy, 
so _bar is likely to point into garbage soon after it's assigned. 
Why don't you just return *cast(Bar*)barBuffer.ptr in bar()? You 
could still emplace a Bar inside barBuffer in Foo's constructor, 
if needed.






Re: RAII

2017-02-23 Thread Adrian Matoga via Digitalmars-d-learn
On Thursday, 23 February 2017 at 09:52:26 UTC, Arun 
Chandrasekaran wrote:

I'm trying to write an RAII wrapper on Linux.

I understand struct in D doesn't have default constructor (for 
.init reasons).

I don't want to use `scope`.

Is there an elegant way to achieve this in D?



static opCall() is the way to emulate an argumentless struct 
constructor. You still need to call it explicitly, though:


```
import std.stdio : writefln;
struct Foo {
int a;
static Foo opCall() {
Foo foo;
foo.a = 42;
return foo;
}
~this() {
writefln("destroyed with a=%d", a);
}
@disable this(this);
@disable void opAssign(Foo);
}

void main()
{
auto foo1 = Foo(); // ok
Foo foo2;  // == Foo.init
}
```




Re: Why can't static arrays be sorted?

2016-10-06 Thread Adrian Matoga via Digitalmars-d-learn

On Thursday, 6 October 2016 at 09:17:08 UTC, pineapple wrote:
On Wednesday, 5 October 2016 at 19:30:01 UTC, Jonathan M Davis 
wrote:
Would just like to point out that this is design weirdness on 
Phobos' part - the library I've been writing does not have 
this problem.


It doesn't even make conceptual sense for a static array to be 
a range, because you can't remove elements from it.


- Jonathan M Davis


Just because the static array itself isn't a range doesn't mean 
that it should be necessary to do unintuitive gymnastics with 
it just to pass it to functions like `sort`.


`sort` takes a range. [] gets a range from anything.
It's a convention, not gymnastics.



Re: Why can't static arrays be sorted?

2016-10-04 Thread Adrian Matoga via Digitalmars-d-learn

On Tuesday, 4 October 2016 at 20:05:15 UTC, TheGag96 wrote:
I was writing some code today and ran into this oddity that I'd 
never come across before:


import std.algorithm : sort;
int[10] arr = [0, 3, 4, 6, 2, 1, 1, 4, 6, 9];
thing.sort();

This doesn't compile. Obviously the .sort property works, but 
what about static arrays makes them unable to be sorted by 
std.algorithm.sort? Thanks.



Try:
arr[].sort();


Re: Parse File at compile time, but not embedded

2016-06-10 Thread Adrian Matoga via Digitalmars-d-learn

On Tuesday, 7 June 2016 at 22:09:58 UTC, Alex Parrill wrote:
Not necessarily, You chased that rabbit quite far! The data 
your reading could contain sensitive information only used at 
compile time and not meant to embed. For example, the file 
could contain login and password to an SQL database that  you 
then connect, at compile time and retrieve that information 
the disregard the password(it is not needed at run time).


Accessing a SQL server at compile time seems like a huge abuse 
of CTFE (and I'm pretty sure it's impossible at the moment). 
Why do I need to install and set up a MySQL database in order 
to build your software?


Just mount a filesystem that uses an SQL database as storage 
(query can be encoded in file path) and you have it.

Whether it's a good idea is another story.



Re: Anonymous structure

2016-04-19 Thread Adrian Matoga via Digitalmars-d-learn
On Monday, 18 April 2016 at 15:59:11 UTC, Steven Schveighoffer 
wrote:

I wonder if it makes a difference for layout. So for example:

struct T
{
   struct
   {
  int x;
  ubyte y;
   }
   ubyte z;
}

If there is padding inserted between y and z.


There isn't. T.init.z.offsetof - T.init.y.offsetof == 1.




Re: Joining AliasSeq/TypeTuple s

2016-03-30 Thread Adrian Matoga via Digitalmars-d-learn

On Tuesday, 29 March 2016 at 10:06:43 UTC, Adrian Matoga wrote:

(...)


Another version that doesn't misbehave if first and second are of 
different lengths:


import std.meta : AliasSeq;

template RR(A...) {
template With(B...) {
static if (A.length == 0 || B.length == 0)
			alias With = AliasSeq!(A, B); // or static assert(0) if you 
require equal lengths

else
			alias With = AliasSeq!(A[0], B[0], RR!(A[1 .. $]).With!(B[1 .. 
$]));

}
}

struct S(A...) {} // needed to reliably compare AliasSeq's for 
equality


unittest {
alias first = AliasSeq!(int, string, bool);
alias second = AliasSeq!("abc", "def", "ghi");
alias third = RR!first.With!second;
	static assert(is(S!third == S!(int, "abc", string, "def", bool, 
"ghi")));

alias fourth = RR!(first[0 .. 2]).With!second;
	static assert(is(S!fourth == S!(int, "abc", string, "def", 
"ghi")));

}




Re: Joining AliasSeq/TypeTuple s

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

On Tuesday, 29 March 2016 at 09:33:40 UTC, Voitech wrote:
Hi, i want to join two or more tupples in to one, with mixing 
the indexes like roundRobin but in compile time.


unittest{
import std.meta;
alias first=AliasSeq!(int, string,bool);
alias second=AliasSeq!("abc","def","ghi");
alias third=...

static assert(third==AliasSeq!(int, "abc", string, "def", bool, 
"ghi"));

}


How to obtain this kind of functionality ? Is there maybe some 
builin template for this in phobos ? I couldn't find this.


Thank you
Voitech.


import std.meta : AliasSeq;

template RR(A...)
if (!(A.length & 1))
{
static if (A.length == 0)
alias RR = AliasSeq!();
else {
alias Left = A[0 .. $ / 2];
alias Right = A[$ / 2 .. $];
		alias RR = AliasSeq!(Left[0], Right[0], RR!(Left[1 .. $], 
Right[1 .. $]));

}
}

struct S(A...) {} // needed to reliably compare AliasSeq's for 
equality


unittest {
alias first = AliasSeq!(int, string, bool);
alias second = AliasSeq!("abc", "def", "ghi");
alias third = RR!(first, second);
	static assert(is(S!third == S!(int, "abc", string, "def", bool, 
"ghi")));

}



Re: Template mixins and struct constructors

2016-03-03 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 2 March 2016 at 20:39:57 UTC, Adam D. Ruppe wrote:

On Wednesday, 2 March 2016 at 12:27:04 UTC, Adrian Matoga wrote:

Is it by design or is it a bug?
And, if it is by design, what is the reason for that?


That's by design. It allows you to override names from a 
template mixin like inheritance but no runtime cost.


Read my tip of the week here to see how it works and how you 
can combine ctors from a mixin:


http://arsdnet.net/this-week-in-d/2016-feb-07.html


Ah, I was on vacation at that time so that's why I don't remember 
reading it. :)


Thanks! It's a nice workaround but it's, well, a workaround. It 
leaks the internals of the template mixin and a potential API 
user would have to remember two additional quirks when using it. 
I guess I'll try a different approach, initializing the mixed in 
members later with a function.




Re: Template mixins and struct constructors

2016-03-02 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 2 March 2016 at 14:36:59 UTC, Daniel Kozak wrote:

OK maybe this one:

template AddField(T) {
T b;
this(Args...)(T b, auto ref Args args)
{
   this.b = b;
   this(args);
}
this(int a) {
this.a = a;
}
}

struct Bar {
int a;
mixin AddField!(string);
}

unittest {
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15);
}


Then it's limited to structs in which only "int a" is to be 
initialized. Not very useful and the templated ctor is not needed 
now.


struct Baz {
mixin AddField!string; // fail, no "int a" in Baz.
ulong d;
double x;
string foo;
}


Re: Template mixins and struct constructors

2016-03-02 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 2 March 2016 at 12:48:47 UTC, Daniel Kozak wrote:

On Wednesday, 2 March 2016 at 12:27:04 UTC, Adrian Matoga wrote:

(...)


You can use string mixins:

template AddField(T) {
enum AddField = T.stringof ~ `  b;
this(Args...)(` ~ T.stringof ~ ` b, auto ref Args args)
{
this.b = b;
this(args);
}`;
}

struct Bar {
mixin(AddField!string);
int a;
this(int a) { this.a = a; }
}

unittest {
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15);  // line 31
}


What if T is private type in some other module or, even worse, a 
Voldemort type?


Template mixins and struct constructors

2016-03-02 Thread Adrian Matoga via Digitalmars-d-learn

I can do this:

struct Foo {
int a;
string b;
this(int a) { this.a = a; }
	this(Args...)(string b, auto ref Args args) { this.b = b; 
this(args); }

}

unittest {
auto foo1 = Foo(5);
auto foo2 = Foo("foo", 15);
}

However, the following code is invalid:

mixin template AddField(T) {
T b;
this(Args...)(T b, auto ref Args args)
{
this.b = b;
this(args);
}
}

struct Bar {
mixin AddField!string;
int a;
this(int a) { this.a = a; }
}

unittest {
auto bar1 = Bar(5);
auto bar2 = Bar("bar", 15);  // line 31
}

sctor.d(31): Error: constructor sctor.Bar.this (int a) is not 
callable using argument types (string, int)


Is it by design or is it a bug?
And, if it is by design, what is the reason for that?



Re: Member Access Based On A Runtime String

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

On Tuesday, 1 March 2016 at 08:53:20 UTC, Adrian Matoga wrote:

static if (is(Q : T)) {


Oops, should be T : Q



Re: Member Access Based On A Runtime String

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

On Tuesday, 1 March 2016 at 05:05:40 UTC, Jack Stouffer wrote:

In Python, I can do this:

my_obj = Obj()
string_from_func = func()
setattr(my_obj, string_from_func, 100)

Say func() returns "member1" or "member2", the setattr would 
then set either one of those to 100.


Is there any equivalent in D?


struct Foo
{
string foo = "dog";
int bar = 42;
int baz = 31337;
}

void set(P, T)(ref P p, string name, auto ref T value)
{
foreach (mem; __traits(allMembers, P)) {
static if (is(typeof(__traits(getMember, p, mem)) Q)) {
static if (is(Q : T)) {
if (mem == name) {
__traits(getMember, p, mem) = value;
return;
}
}
}
}
assert(0, P.stringof ~ " has no member " ~ name);
}

unittest
{
Foo foo;
foo.set("bar", 15);
assert(foo.bar == 15);
foo.set("foo", "cat");
assert(foo.foo == "cat");
}



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

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

On Friday, 29 January 2016 at 23:44:56 UTC, Basile B. wrote:

Haven't you seen my answer about constraint ?

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


What do you think constraints are used for otherwise ^^


Yes, I've seen it, thanks.
Requiring the user to write the constraint might indeed enforce a 
better style, but I want to be able to test it even if the user 
forgets the constraint. Otherwise she'll get cryptic error 
messages from some other code assuming that CallsFoo!NoFoo is a 
valid type.




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

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

On Saturday, 30 January 2016 at 00:16:21 UTC, Ali Çehreli wrote:

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

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


Ali


Thanks a lot! Now I can continue my work. :)



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

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

Code:


struct HasFoo { void foo() {} }

struct NoFoo {}

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

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

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


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

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

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



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

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

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

Code:


struct HasFoo { void foo() {} }

struct NoFoo {}

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

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

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


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

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

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



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

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

-Steve


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

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

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

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



Re: how to allocate class without gc?

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

On Tuesday, 26 January 2016 at 01:09:50 UTC, Igor wrote:
Is there any examples that shows how to properly allocate an 
object of a class type with the new allocators and then release 
it when desired?


There's an example of class object allocation in the 
std.experimental.allocator docs:


// Dynamically allocate a class object
static class Customer
{
uint id = uint.max;
this() {}
this(uint id) { this.id = id; }
// ...
}
Customer cust = theAllocator.make!Customer;
assert(cust.id == uint.max); // default initialized
cust = theAllocator.make!Customer(42);
assert(cust.id == 42);

To release the object (call the destructor and free the memory), 
call dispose():

theAllocator.dispose(cust);

You'll need to replace "theAllocator" with the allocator you want.


Re: Socket - handling large numbers of incoming connections

2015-12-21 Thread Adrian Matoga via Digitalmars-d-learn

On Monday, 21 December 2015 at 21:32:55 UTC, Jakob Jenkov wrote:

My server uses "poll" for that.


Okay, how does that work? How do I use "poll" in D?

Link?
Code example?


The same as in C [1].
Just change
#include 
to
import core.sys.posix.poll;

[1] http://linux.die.net/man/2/poll



Re: How to return user name from vibed session?

2015-12-10 Thread Adrian Matoga via Digitalmars-d-learn

On Thursday, 10 December 2015 at 11:36:20 UTC, Suliman wrote:
Vibed have method get for user session 
http://vibed.org/api/vibe.http.session/SessionStore


I set user name for session like this:
req.session.set("username", "admin");

But I can't understand how to get user name from it:

abstract std.variant.VariantN!(20) get(
  string id,
  string name,
  lazy std.variant.VariantN!(20) defaultVal
);

What does every string here mean? Could anybody to show example 
of usage?


I think what you need is Session.get, not SessionStore.get:

http://vibed.org/api/vibe.http.session/Session.get



Re: How to use std.experimental.logger?

2015-10-01 Thread Adrian Matoga via Digitalmars-d-learn

On Thursday, 1 October 2015 at 08:21:35 UTC, Panke wrote:
I tried it on Windows today using the latest DMD installer, all 
default logger and settings.


I get: safe function [...].logImplf cannot call system function 
'std.format.formattedWrite!(MsgRange, char, 
Result!()).formattedWrite'


How do I make formatted logging work?


Would be easier to diagnose your problem if you pasted your code 
and uncut complaint from the compiler.


Anyway, the following works, so it may give you a hint:

$ cat log.d
import std.experimental.logger;

void main()
{
logf("just log %s and %d", "this", 1337);
}
$ dmd log.d
$ ./log
2015-10-01T11:23:57.291:log.d:main:5 just log this and 1337



Re: Problem with map, reduce, ..

2015-06-24 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 24 June 2015 at 08:30:29 UTC, Adrian Matoga wrote:
input.byLine() yields char[]'s as range elements, while props 
is (correctly) indexed by strings, i.e. immutable(char)[].


Ooops, more precisely it's because of the second argument of 
add() being string, but the solution above still applies.




Re: Problem with map, reduce, ..

2015-06-24 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 24 June 2015 at 08:18:52 UTC, Stefan wrote:
I tried to refactor some existing code to use more of the 
functional patterns/style (map, filter, reduce, ..).
The task is to read in some sort of a simple property file and 
present the result as an associative array.

My attempt is:

import std.stdio;
import std.algorithm.iteration : filter, map, reduce;
import std.algorithm.mutation : split;
import std.string : indexOf, strip;
import std.stdio : File, writeln;
import std.algorithm : startsWith;

string[string] add( ref string[string] result, in string line) {
int assignmentIndex = indexOf( line, = );
if ( assignmentIndex  0 ) {
string key = line[ 0 .. assignmentIndex ];
string value = line[ assignmentIndex + 1 .. line.length 
];

result[ key ] = value;
   }
   return result;
}


void main() {
   auto input = File( test.ini, r );
   auto lines = input.byLine()
  .filter!( line = !startsWith( line, # )  
!startsWith( line, !)  line.length  0 )

  .map!( line = strip( line ) );
   string[string] props;
   auto result = reduce!(add)( props, lines );
}

result should now contain the associative array.

However, it fails with an error in the reduce line:

c:\develop\dmd2.067.1\windows\bin\..\..\src\phobos\std\algorithm\iteration.d(2536): 
Error: static assert  Incompatible function/seed/element: 
prop.add/string[string]/char[]
c:\develop\dmd2.067.1\windows\bin\..\..\src\phobos\std\algorithm\iteration.d(2521):
instantiated from here: reduceImpl!(false, MapResult!(__lambda2, 
FilterResult!(__lambda1, ByLine!(char, char))), string[string])
c:\develop\dmd2.067.1\windows\bin\..\..\src\phobos\std\algorithm\iteration.d(2505):
instantiated from here: reducePreImpl!(MapResult!(__lambda2, 
FilterResult!(__lambda1, ByLine!(char, char))), string[string])
source\prop.d(30):instantiated from here: 
reduce!(string[string], MapResult!(__lambda2, 
FilterResult!(__lambda1, ByLine!(char, char


I have no idea how to resolve this.


input.byLine() yields char[]'s as range elements, while props is 
(correctly) indexed by strings, i.e. immutable(char)[]. Use .idup 
to create an immutable copy of the property name, e.g.:


   auto lines = input.byLine()
  .filter!( line = !startsWith( line, # )  !startsWith( 
line, !)  line.length  0 )

  .map!( line = strip( line.idup ) );



Re: Problem with map, reduce, ..

2015-06-24 Thread Adrian Matoga via Digitalmars-d-learn

On Wednesday, 24 June 2015 at 08:58:10 UTC, Stefan wrote:

On Wednesday, 24 June 2015 at 08:33:29 UTC, Adrian Matoga wrote:
On Wednesday, 24 June 2015 at 08:30:29 UTC, Adrian Matoga 
wrote:
input.byLine() yields char[]'s as range elements, while props 
is (correctly) indexed by strings, i.e. immutable(char)[].


Ooops, more precisely it's because of the second argument of 
add() being string, but the solution above still applies.


Thanks! That does it!

Any idea how to make the 'ugly' reduce step more 'pleasant'? 
I.e. make it a part of the filter, map, .. chain?


What about:

   auto result = File(test.ini, r)
  .byLine()
  .filter!( line = !startsWith( line, # )  !startsWith( 
line, !)  line.length  0 )

  .map!( line = line.idup.split('='))
  .filter!( fields = fields.length  1)
  .map!( fields = tuple(fields[0].strip(), fields[1].strip() 
))

  .assocArray();




Re: Does D has built-in stack structure?

2015-06-22 Thread Adrian Matoga via Digitalmars-d-learn

On Monday, 22 June 2015 at 06:09:48 UTC, Assembly wrote:
Does D has built-in stack structure (if so, which module?) or 
should I implement it myself?


AFAIK there's no built-in, but std.array.Appender could be easily 
wrapped in an interface that makes thinking of it as stack easier:


struct Stack(T)
{
import std.array: Appender, appender;
Appender!(T[]) _app;
@property ref inout(T) top() inout { return _app.data[$ - 1]; };
@property bool empty() const { return _app.data.length == 0; }
void pop() { _app.shrinkTo(_app.data.length - 1); }
void push(T t) { _app.put(t); }
}