Re: How Stop Worker Thread if Owner Thread is Finished?

2020-10-27 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 27 October 2020 at 11:36:42 UTC, Marcone wrote:
I want to use isDaemon to automatic stop worker thread if 
ownner thread is finished


Terminating threads without properly unwinding the stack is 
generally a very bad idea. Most importantly the destructors of 
stucts on the stack won't run which can cause problems like locks 
not being released.


This isn't specific to D either. For example Raymond Chen writes 
about the TerminateThread function in Windows here:

https://devblogs.microsoft.com/oldnewthing/20150814-00/?p=91811

You should signal the thread somehow that it's time to stop 
working


Re: How is this an "Access Violation"

2020-10-27 Thread Rene Zwanenburg via Digitalmars-d-learn
On Tuesday, 27 October 2020 at 02:05:37 UTC, Ruby The Roobster 
wrote:

   void construct(string type,atom base,atom bonded)
{
base = new 
atom(base.name.idup,base.mass,base.electro_negativity,base.valence_electrons,base.electrons,base.protons,base.neutrons,base.pos);

(...)
assert(this.base.valence >= 1 && 
this.bonded.valence >=1 && this.base.electro_negativity >= 0 && 
this.bonded.electro_negativity >= 0,"For a single bond, both 
atoms need to have at least one free electron and have to have 
electro negativity.");


Going by the assert this is a member function of a class or 
struct with base and bonded members. I think you meant to assign 
the newly created atoms to those fields instead of overwriting 
your arguments.


Re: [windows] Can't delete a closed file?

2019-05-09 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 9 May 2019 at 12:33:37 UTC, Cym13 wrote:

On Thursday, 9 May 2019 at 11:31:20 UTC, Cym13 wrote:

...


To dismiss any doubt about AV or other processes coming into 
play I took the binary and ran it with wine on linux with the 
exact same end result.

For reference my windows system is a 64b windows 10.


You could try to use the find handle function in Process Explorer 
to figure out what process has the file open:


https://docs.microsoft.com/en-us/sysinternals/downloads/process-explorer


Re: Memory reference that does not stop garbage collection.

2019-02-08 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 8 February 2019 at 15:42:13 UTC, Jonathan Levi wrote:

I should be able to use `core.memory.GC.removeRange` right?


That would leave dangling references in the array. You may be 
interested in this, but I have not used it myself:


https://repo.or.cz/w/iv.d.git/blob/HEAD:/weakref.d


Re: cas and interfaces

2018-12-27 Thread Rene Zwanenburg via Digitalmars-d-learn
On Tuesday, 25 December 2018 at 22:07:07 UTC, Johannes Loher 
wrote:
Thanks a lot for the info, that clarifies things a bit. But it 
still leaves the question, why it works correctly when 
inheriting from an abstract class instead of implementing an 
interface... Any idea about why that?


Unlike interfaces, base class references don't need adjustment. 
You can see this in action by printing addresses:


https://run.dlang.io/is/m6icVr

import std.stdio;

interface I {}
class Base : I {}
class Derived : Base { }

void main()
{
auto derived = new Derived;
Base base = derived;
I i = derived;

writeln(cast(void*)derived);
writeln(cast(void*)base);
writeln(cast(void*)i);
}


7FC1F96EE000
7FC1F96EE000
7FC1F96EE010


Re: How does calling function pointers work?

2018-11-12 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 12 November 2018 at 16:29:24 UTC, helxi wrote:
On Monday, 12 November 2018 at 16:25:13 UTC, Rene Zwanenburg 
wrote:
Idk where you got that syntax from, but there's no syntactic 
difference between calling normal functions and function 
pointers:


import std.stdio;
import std.concurrency;
import core.thread;

void worker(int firstNumber) {
foreach (i; 0 .. 4) {
Thread.sleep(500.msecs);
writeln(firstNumber + i);
}
}

void main() {
foreach (i; 1 .. 3) {
spawn(, i * 10);
}
}


Looks like worker needs an int and spawn(, i * 10) seems 
to feed it's second arg to worker(?)


That's right. spawn() is a function in the standard library that 
takes a function pointer, and all the arguments to pass to that 
function. It's a bit unusual in that regard: normally when using 
function pointers the arguments are provided by the code that 
receives the function pointer. Internally, spawn will call the 
function pointer just like I did in my example, but on another 
thread.


Here's an example where a function pointer is passed around with 
the arguments provided by the callee:

https://run.dlang.io/is/ArCN5t



Re: How does calling function pointers work?

2018-11-12 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 12 November 2018 at 16:08:28 UTC, helxi wrote:
As far as I understand, calling a function pointer with an 
argument in D looks like:


call(, argTofn0, argTofn1, argTofn3);


Idk where you got that syntax from, but there's no syntactic 
difference between calling normal functions and function pointers:


https://run.dlang.io/is/I6u0rg



Re: Test if variable has void value

2018-08-22 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 22 August 2018 at 13:50:07 UTC, Andrey wrote:

Hello,
How to test if variable has void value?


string text = void;
if(text == void)
{
   writeln("Is void");
}


Tried this:

if(is(text == void))

but doesn't work.


You can't. When using a void initializer the actual value is 
garbage until initialized properly, and that garbage can look 
like anything including a valid instance.


So if the flow of your program can't guarantee that the value has 
been initialized at a certain point, you'll have to track it 
yourself some way. Nullable may be of help:


https://dlang.org/phobos/std_typecons.html#Nullable



Re: Coreect way to create delegate for struct method.

2018-08-22 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 21 August 2018 at 21:29:38 UTC, Andrey wrote:

Hello,
This is a code:

   (...)
   test.handler = 


That's an internal pointer, and internal pointers are not allowed 
in structs precisely because of the issues you're running into: 
the pointer will be invalid after a move.


You may be able to get it kind of working, but I'd recommend 
looking for another solution to your problem. This is one of 
those things that will come back to bite you later.


Memory corruption with COM object

2018-07-06 Thread Rene Zwanenburg via Digitalmars-d-learn
I've been staring at this problem the past few hours without 
making any progress. But I feel like I'm overlooking something 
obvious..


Using Adam's comhelpers, I've made a JSON plugin for LogParser. 
However after running for a bit it'll crash with signs of memory 
corruption.


My guess was the GC was collecting things still in use, and 
disabling the GC does indeed 'fix' the problem. Looking through 
comhelpers, the code doesn't add a GC root for a created object 
before handing it off to the C side. I've added root adding and 
removing, expecting that to fix the problem. However it didn't 
help.


The DLL uses the helper functions like dll_process_attach in 
DllMain, so druntime is initialized.


What would be a good way to figure out why the GC decides to 
collect objects I'm still holding on to?


Re: Configuring DerelictGL3

2018-06-06 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 6 June 2018 at 23:26:23 UTC, Entity325 wrote:
I can't imagine things like "glEnable/DisableClientState" are 
deprecated.


They are. All the missing symbols are indeed deprecated.

attempting to load the deprecated functions according to the 
documentation page did a whole lot of nothing


Could you post the exact code you used? I'm not using the old 
functions, but that should work.


Re: Aggressive conditional inlining with ldc only, not dmd

2018-03-26 Thread Rene Zwanenburg via Digitalmars-d-learn

On Sunday, 25 March 2018 at 22:09:43 UTC, Nordlöw wrote:

eventhough I compile with -release -inline -nobounds flags.


Just to make sure: are you passing -O as well?


Re: How to make AA key a pointer

2018-02-19 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 19 February 2018 at 14:57:47 UTC, Clinton wrote:

On Monday, 19 February 2018 at 14:55:01 UTC, Clinton wrote:

Hi all, I need advice from better developers on this concern.

I'm using an AA to reference another array for quicker access:

[...]


Sorry, on second look my explanation isn't very clear. I want 
to know if:


bool[string] myAA;

myAA[contact.id] = true; // Does this copy contact.id or is 
this a pointer to contact.id?


It's a pointer. In D, string is an alias to immutable(char)[] 
(Slice of immutable characters). A slice is a combination of 
pointer and length.


Re: Debugging on Windows

2018-02-09 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 8 February 2018 at 21:09:33 UTC, JN wrote:

Hi,

is there any way to debug binaries on Windows? I'd at least 
like to know which line of code made it crash. If it's D code, 
I get a call trace usually, but if it's a call to a C library, 
I get a crash and that's it. I am using VSCode and I'd prefer 
to debug in it if possible, but using other IDEs is a 
possibility for me if that will help.


You can debug D programs from VS Code using the C++ plugin:

https://marketplace.visualstudio.com/items?itemName=ms-vscode.cpptools

It requires some configuring, but from what I remember it was all 
very straightforward.


Re: SegFault with HibernateD

2018-01-12 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 12 January 2018 at 07:33:37 UTC, Mike Parker wrote:

On Friday, 12 January 2018 at 05:24:52 UTC, Venkat wrote:
I get a SegFault with the main method below which uses 
HibernateD . The second main method which uses ddbc just works 
fine. What is wrong with the first main method ? I have 
attached the error at the bottom although I don't think it 
says much.




This is the error.



object.Exception@source/dub/generators/build.d(530): Program


It says enough to know that the exception is being thrown from 
dub and not your program. You program is never executed because 
dub throws the exception before it gets that far. You should 
report this at the dub repository: 
https://github.com/dlang/dub/issues


It looks to me like the program is being run through dub, and dub 
is just reporting the program's exit code.


Hard to guess what the issue is, I'd attach a debugger to see 
where it crashes.


Re: High-resolution thread sleep

2017-12-15 Thread Rene Zwanenburg via Digitalmars-d-learn
On Friday, 15 December 2017 at 01:49:56 UTC, Steven Schveighoffer 
wrote:


So... you plan on rendering more than 1000 frames per second?

I think in any case, even if the API allows it, you are 
probably not getting much better resolution on your non-windows 
systems.


Have you tried it anyway and see how it works? I think it might 
actually work just fine.


-Steve


The higher precision would be needed b/c updating and rendering 
takes time, so the sleep time would be timePerFrame - 
timeSpendOnRendering.


Problem is you'll need vsync anyway to avoid tearing. 
Applications that use their own timing to limit the framerate 
without using vsync are easy to recognise: they have a tear 
slowly moving around on the screen. It's visually even more 
annoying than regular tearing.


Re: High-resolution thread sleep

2017-12-14 Thread Rene Zwanenburg via Digitalmars-d-learn
On Thursday, 14 December 2017 at 23:45:18 UTC, Ivan Trombley 
wrote:

Something along the lines of this:

while (render)
{
  immutable auto startTime = MonoTime.currTime;

  // Render the frame...

  immutable auto remain = m_frameDuration - (startTime - 
MonoTime.currTime);

  if (remain > Duration.zero)
Thread.sleep(remain);
}


In that case, the best thing you can do is use vsync as the 
waiting mechanism ;)


Re: High-resolution thread sleep

2017-12-14 Thread Rene Zwanenburg via Digitalmars-d-learn
On Thursday, 14 December 2017 at 21:11:34 UTC, Ivan Trombley 
wrote:
I need to be able to put a thread to sleep for some amount of 
time. I was looking at using Thread.sleep but it appears that 
on Windows, it's limited to millisecond resolution. Is there a 
way to do this in a cross-platform way that is higher 
resolution?


Sleeping for very short periods is usually a bad idea for various 
reasons. What do you need it for?


If you really need this, go for a loop with a high resolution 
timer.


Re: Email validation

2017-11-28 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 28 November 2017 at 18:47:06 UTC, Vino wrote:

Hi All,


You can do this easily using the std.net.isemail module:

https://dlang.org/phobos/std_net_isemail.html



Re: opAssign for most struct assignment calls not executed

2017-11-23 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 23 November 2017 at 15:26:03 UTC, Timoses wrote:

A aaa = a;


That's initialization, not assignment, which is subtly different. 
It will call the postblit on aaa instead of opAssign. A postblit 
can be defined this way:


this(this)
{

}

There is no way to access the original a from the postblit. All 
fields have already been copied, you can use it to duplicate 
reference types, increment reference counts, and other things 
like that.


Re: DateTime trying to do it at compile time.

2017-10-26 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 26 October 2017 at 17:55:05 UTC, Mr. Jonse wrote:
when calling Clock.currTime() in a this() in a class. I have no 
idea why it is trying to do it at compile time and failing. I 
thought if ctfe couldn't compile it would do it at run time 
anyways? Seems like a bug.


I suspect you're trying to instantiate your class in a static 
context, which causes it to be constructed at compile time. For 
example:



class A
{
  this() {
// Do sth. with datetime
  }
}

class B
{
  // This will construct A at compile time. This also
  // means a single A instance is shared between all
  // B instances. This is different from most langs!
  A a = new A;
}

// This will also construct at compile time.
A moduleScopedA = new A;


The solution is to new A in your class or module constructor.


Re: How to modify process environment variables

2017-10-17 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 17 October 2017 at 05:57:50 UTC, Ky-Anh Huynh wrote:

On Tuesday, 17 October 2017 at 04:56:23 UTC, ketmar wrote:


you can use libc's `putenv()` in D too, it is ok. just import 
`core.sys.posix.stdlib`,  it is there. D is not antagonistic 
to C, and doesn't try to replace the whole libc with it's own 
libraries. so if you see something that libc has and you'd 
like to use -- just do it! ;-)


I see :) I have always tried to avoid C if possible :D


As an alternative, a search on code.dlang.org turned up this lib:

http://code.dlang.org/packages/dotenv


Re: Making a repo of downloaded dub package

2017-09-05 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 5 September 2017 at 06:23:26 UTC, Dukc wrote:

On Monday, 4 September 2017 at 20:31:35 UTC, Igor wrote:
Search for word "local" here: 
https://code.dlang.org/docs/commandline. Maybe some of those 
can help you. If not you could make a pull request for dub 
that would support such a thing :)


That will make a Dub package out of a Git package, but I'm 
trying to do it vice-versa (And so that it is able to use the 
same histoy as the repository). I think it will require Git 
commands, but what commands exactly? I was unable to figure 
that out myself.


When you go to the package's page on code.dlang, look for the 
github repository link in the top right corner. You can fork from 
there.


Re: Remove all blank lines from a file

2017-08-31 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 31 August 2017 at 14:44:07 UTC, vino wrote:

Hi All,

  Can some provide me a example of how to remove all blank 
lines from a file.


From,
Vino.B


This one doesn't read the entire file into memory:

import std.stdio;
import std.array;
import std.algorithm;
import std.uni;

void main(string[] args)
{
auto inputFile = File(args[1]);
auto outputFile = File(args[2], "wb");

inputFile
.byLine
.filter!(line => !line.all!isWhite)
.copy(outputFile.lockingTextWriter);
}

But if you want to replace the input file, you'd have to write to 
a temp file, remove the original, then move the temp file.


Re: Getting enum from value

2017-08-05 Thread Rene Zwanenburg via Digitalmars-d-learn

On Saturday, 5 August 2017 at 15:33:57 UTC, Matthew Remmel wrote:

Any ideas?


You can use to! in std.conv:


import std.stdio;
import std.conv;

enum Foo
{
A = "A",
B = "B"
}

void main()
{
writeln("A".to!Foo);  
}


Re: Function with static array as parameter

2017-07-12 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 12:57:19 UTC, Rene Zwanenburg wrote:

On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
What is the best way in D to create a function that receives a 
static array of any length?


Templatize the array length:

void foo(size_t length)(int[length] arr)
{

}


That being said, this may lead to template bloat and excessive 
copying. What are you trying to do? Is there a reason you can't 
use a slice?


Re: Function with static array as parameter

2017-07-12 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 12 July 2017 at 12:20:11 UTC, Miguel L wrote:
What is the best way in D to create a function that receives a 
static array of any length?


Templatize the array length:

void foo(size_t length)(int[length] arr)
{

}


Re: D and memory mapped devices

2017-06-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 14 June 2017 at 08:10:57 UTC, Russel Winder wrote:
but the bitfields mixin template appears to do more than add 
all the bit twiddling functions to emulate the bitfields. This 
would appear a priori to not allow for actual memory mapped 
devices using it, or am I missing something?


I've casted void buffers to structs containing bitfields to read 
pre-existing binary files, and that worked just fine. I don't see 
why it would be different for memory mapped devices. What do yo 
mean by 'do more'?


Re: purity question

2017-05-30 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 30 May 2017 at 11:34:52 UTC, ketmar wrote:
If malloc were marked as pure, wouldn't that mean it must 
return the same pointer every time you call it with the same 
size?


of course. but D "pure" is not what other world knows as 
"pure". we love to mess with words.


Well, there's the ability to modify non-const reference 
parameters from a pure function, but that's not applicable to 
malloc. Are there any other special rules?


Re: purity question

2017-05-30 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 29 May 2017 at 01:36:24 UTC, Jonathan M Davis wrote:

A simple example: anything that has a malloc/free pair.


Yeah, if you do it right, you should be fine, but you have to 
do it right, and it's very easy to miss some detail that makes 
it wrong to insist to the compiler that what you're doing is 
pure.


If malloc were marked as pure, wouldn't that mean it must return 
the same pointer every time you call it with the same size?


Re: Why map return [] ?

2017-04-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 14 April 2017 at 15:49:00 UTC, Suliman wrote:
I found problem! ResultRange should be converted to array 
before it can be `map`ed


That shouldn't be necessary. Can you post your complete code?


Re: Can't build simple project. Very strange errors

2017-04-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 14 April 2017 at 15:42:33 UTC, Suliman wrote:

On Friday, 14 April 2017 at 15:40:18 UTC, Rene Zwanenburg wrote:

On Friday, 14 April 2017 at 15:31:21 UTC, Suliman wrote:
On Friday, 14 April 2017 at 15:22:49 UTC, Rene Zwanenburg 
wrote:

On Friday, 14 April 2017 at 09:49:09 UTC, Suliman wrote:

on: dub build --compiler=ldc2


link

OPTLINK (R) for Win32  Release 8.00.17


Optlink isn't able to link object files produced by ldc. 
Could you try an x64_86 build? You'll need the Microsoft 
linker.


I do not have VS on my PC :(


You don't need VS, the Windows SDK should be fine too. It's a 
free download :)


How to check if it's installed and how to use linker from it?


If it's installed you can find it in the programs and features 
list as 'Windows Software Development Kit for Windows X'. The DMD 
installer will look for it during installation, so reinstalling 
DMD after installing the SDK should work. I'm not sure how LDC 
does it, but last time I installed LDC it also just worked.


Re: Can't build simple project. Very strange errors

2017-04-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 14 April 2017 at 15:31:21 UTC, Suliman wrote:

On Friday, 14 April 2017 at 15:22:49 UTC, Rene Zwanenburg wrote:

On Friday, 14 April 2017 at 09:49:09 UTC, Suliman wrote:

on: dub build --compiler=ldc2


link

OPTLINK (R) for Win32  Release 8.00.17


Optlink isn't able to link object files produced by ldc. Could 
you try an x64_86 build? You'll need the Microsoft linker.


I do not have VS on my PC :(


You don't need VS, the Windows SDK should be fine too. It's a 
free download :)


Re: Can't build simple project. Very strange errors

2017-04-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 14 April 2017 at 09:49:09 UTC, Suliman wrote:

on: dub build --compiler=ldc2


link

OPTLINK (R) for Win32  Release 8.00.17


Optlink isn't able to link object files produced by ldc. Could 
you try an x64_86 build? You'll need the Microsoft linker.


Re: DUB mismatch between project structure and dub.json contents

2017-04-10 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 10 April 2017 at 12:56:49 UTC, Nordlöw wrote:
src/knet/traversal.d(20,8): Error: module factixs from file 
src/knet/factixs.d must be imported with 'import factixs;'


What am I doing wrong?


My first guess would be that the module declaration in that file 
is incorrect. Are you sure it's set to knet.factixs? The module 
declaration needs to be present or it will be put in the root 
package.


Re: delegate with optional parameters

2017-04-03 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 3 April 2017 at 05:00:15 UTC, Inquie wrote:
Yes, but they are really not any different. They only look 
different. A field can be a function just like a method because 
they look exactly the same except on is in a vtable and the 
other is in the fields memory. But both point functions.


It should be possible to create a wrapper struct around your 
'overloads' with an opDispatch which selects the right delegate.


Re: Why is [0] @safer than array.ptr?

2017-01-24 Thread Rene Zwanenburg via Digitalmars-d-learn
On Tuesday, 24 January 2017 at 11:38:16 UTC, Jonathan M Davis 
wrote:
Likely because it does bounds checking, so you at least know 
that it's not null. But I don't see why that would really 
improve much considering that the odds are that you're really 
going to be accessing far more than just the first element with 
the pointer. It seems _slightly_ better from a safety 
perspective but only slightly. So, I don't know what the point 
is in suggesting it as an alternative.


- Jonathan M Davis


Pointer arithmetic is forbidden in @safe code so that's not a 
problem. The reason this was introduced was indeed bounds 
checking. For example:


@safe:

int parse(ref char[] input)
{
  // Pop all numeric characters from the front of the input slice 
and convert to int

}

void main()
{
  auto input = "123".dup;
  parse(input);
  // Since all numeric chars have been popped, input is now 
effectively input[$ .. $].

  // This means input.ptr is pointing past the end of the array.
  writeln(input.ptr); // Out of bounds access
}


Re: Strange Bug

2017-01-20 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 20 January 2017 at 08:19:57 UTC, Chris M. wrote:
I have no idea if this is an issue with D, or OpenSSL, or if 
I'm just doing something completely wrong. I'm writing a 
program that will either encrypt or decrypt a string using AES 
in ECB mode (for a school assignment) and it's giving me a very 
strange bug.


[...]

auto encOut = new ubyte[inputStr.length];

// Encrypt and convert to base64
AES_set_encrypt_key(aesKey.ptr, aesKey.sizeof * 8, );
AES_ecb_encrypt(inputStr.ptr, encOut.ptr, , 
AES_ENCRYPT);


Here's the problem. I tried running this without the if-else 
statements (i.e. encrypting and decrypting all in one run of 
the program, code below). If I leave in the base64 encoding and 
decoding, and use decB64 as the input to decrypt, it still 
doesn't work. However, if I decrypt with encOut directly, or 
assign encOut to decB64, it somehow works.


My guess:

The encrypted output will be a bit longer than your input. You're 
not getting an out of bounds exception during encryption since 
OpenSSL only has the pointer to write to, not a buffer length it 
can check. The memory behind your buffer is apparently committed, 
and will be written to by OpenSSL. This is why using the same 
buffer to decrypt works: it continues to read after the end of 
the buffer. (In case it's not clear, writing and reading past the 
end of the buffer is really bad)


I expect OpenSSL to have a helper function to calculate the 
required buffer size for a given input length. Use that to 
allocate the buffer.


Re: Phobos: Determining number of hours or minutes or seconds till now

2017-01-20 Thread Rene Zwanenburg via Digitalmars-d-learn
On Friday, 20 January 2017 at 03:48:14 UTC, rikki cattermole 
wrote:
As per the documentation this is wrong for anything beyond a 
few weeks.

Although I have no idea if that's the case implementation wise.


I think the documentation is talking about the units used, not 
length of the duration. The reason Duration makes this 
distinction is because months and everything larger have a 
variable length. I'm not sure though.


Re: Phobos: Determining number of hours or minutes or seconds till now

2017-01-19 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 19 January 2017 at 14:04:36 UTC, aberba wrote:
Using the standard library, how do a get number of hours or 
seconds or minutes or days or months or years till current time 
from a past timestamp (like "2 mins ago")? Not with manual 
calculations but from Phobos functions.


You can get a duration by subtracting two timestamps. For example:

auto delta = (Clock.currTime - timeStamp).total!"seconds";


Re: Thread will get garbage collected?

2017-01-17 Thread Rene Zwanenburg via Digitalmars-d-learn
On Tuesday, 17 January 2017 at 08:58:33 UTC, Arun Chandrasekaran 
wrote:
Interesting. Why doesn't the thread get GC'd in this case even 
without any reference still active?


There will be a reference to it in druntime itself:
http://dlang.org/phobos/core_thread.html#.Thread.getThis


Re: Changing template parameters

2017-01-16 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 16 January 2017 at 15:56:16 UTC, Jack Stouffer wrote:

Same way you use any template parameters,

 auto i = uniform!("(]")(0, 1000);


Also, if the template parameter consists of a single token you 
can omit the parens:


auto i = uniform!"(]"(0, 1000);


Re: Alias variable from another class

2016-12-15 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 13 December 2016 at 19:13:24 UTC, Begah wrote:

Any ideas?


Closest you can get is wrapping it in a property. If you need to 
do this often you may be able to generate them, check the recent 
"Getters/Setters generator" thread in Announce for some 
inspiration.


Re: Updated D then undefined symbols in vibed

2016-11-24 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 24 November 2016 at 16:17:19 UTC, Jot wrote:
Any more ideas? Obviously something isn't getting linked in in 
the VS project.


This is definitely a stale object file problem. From that error 
message it appears to use the .dub directory to store object 
files of your dependencies. Try nuking it, then run dub to 
recreate it.


Re: Updated D then undefined symbols in vibed

2016-11-24 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 24 November 2016 at 09:52:32 UTC, Jot wrote:
Seems like someone decided to screw up a lot of people by 
removing a lot of stuff ;/ I guess I should learn my lesson 
about assuming a "stable" dmd release won't completely kill my 
project.


There are still some old object files or libs hanging around. 
MSBuild doesn't know you've updated DMD and reuses them.


Dub shouldn't have this problem. If you've generated the solution 
from a dub file, try a rebuild with Dub first. I suspect MSbuild 
will work after that.


Re: Why don't Function Lambdas Cast to Delegate?

2016-11-21 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 21 November 2016 at 16:24:38 UTC, Q. Schroll wrote:
Why don't lambdas cast to a delegate if they are of type R 
function(Args)? I don't see any reason to that; a lambda should 
be a delegate type by default, and a function only as a special 
guarantee/optimization. It just makes them cumbersome to use 
with toDelegate.
Probably there is a good reason why R function(Args) does not 
implicitly cast to R delegate(Args); I can imagine something 
internally (memory layout etc.) causes that. I'd just like to 
know.


A delegate has the hidden context pointer as parameter in 
addition to the 'visible' parameters. That causes functions and 
delegates with the same declared params to look different on the 
ABI level.


Re: [vibe.d] showing images

2016-10-26 Thread Rene Zwanenburg via Digitalmars-d-learn
On Wednesday, 26 October 2016 at 12:42:09 UTC, Nicholas Wilson 
wrote:

doctype html
html
body
-foreach(s; images)
// it doesn't seem to like #{s} or !{s}
img(src=s)

--
shared static this()
{
auto router = new URLRouter;
router.registerWebInterface(new CamController);

auto settings = new HTTPServerSettings;
settings.port = 8081;
settings.bindAddresses = ["::1", "127.0.0.1"];
listenHTTP(settings, router);


}
class Controller
{
void index(HTTPServerRequest req, HTTPServerResponse res)
{
auto images = 
dirEntries("public/images",SpanMode.breadth)

.map!(f=> f.name).array;
writeln(images); // ["public/images/testprog.jpg"]
res.render!("index.dt",images);
}
 }

What am I missing? I just get a 404 for the image.


You need to make the images accessible over HTTP. Note the use of 
staticFileServer in the following example:


http://vibed.org/docs#http-routing


Re: File.write write extra CR character if a string has CRLF on windows

2016-10-06 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 6 October 2016 at 15:00:00 UTC, Pham wrote:

string s is multi-lines (CRLF as line break)
The write function will write extra CR character for each CRLF 
pair -> why (bug?)


import std.file;
import std.stdio;

string s = ...;

auto fHandle = File("f:\\text.txt", "w"); // open for writing
fHandle.write(s);
fHandle.close();


Take a look at this thread:

http://forum.dlang.org/post/ehdnboaufaadgiaah...@forum.dlang.org


Re: Member not accessible in delegate body

2016-09-23 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 23 September 2016 at 07:54:15 UTC, John C wrote:
How is it possible that "onTextChanged" isn't accessible but 
the private method "changeSize" *is*?


Smells like an oversight. I guess the compiler doesn't see the 
delegate as a member of a Control subclass, so it can't access 
protected members. Private works because private in D means 
module private.


Please file an issue. As a workaround you can try to take the 
address of the method in the closure (untested):


void delegate() foo()
{
  auto func = 

  return () => func(); // I think this will work
}


Re: Vibe.d compilation error: backend/cgelem.c 5018 dmd failed with exit code 1.

2016-09-23 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 23 September 2016 at 08:39:44 UTC, llaine wrote:
Okay I tried yesterday, after 4hours of process, I never went 
through the end of minification.


At the beginning I enter YES should I enter NO instead?


Hmm that's strange. I don't get any yes or no questions. What is 
the exact message you get?


I've been looking into using dustmite with dub a bit, and running

dub dustmite "../DustmiteResult" 
--compiler-regex=".*backend/cgelem\.c 501.*" --build=release


in your project directory should just work..


Re: Vibe.d compilation error: backend/cgelem.c 5018 dmd failed with exit code 1.

2016-09-21 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 21 September 2016 at 20:22:42 UTC, llaine wrote:

The project is pretty big, DustMite would handle this?


Yes, but it may take some time. For large projects, running it on 
a server is advisable. 3K LOC should be doable on a desktop 
machine.


Dub has built-in support for running Dustmite. I'm not very 
familiar with it, but it looks like you'll want to use 'dub 
dustmite' with the --compiler-regex switch with a regex matching 
the ICE assert message.


Re: Copy a struct and its context

2016-09-11 Thread Rene Zwanenburg via Digitalmars-d-learn

On Sunday, 11 September 2016 at 05:44:13 UTC, Yuxuan Shui wrote:
I recently noticed nested struct capture its context by 
reference (which, BTW, is not mentioned at all here: 
https://dlang.org/spec/struct.html#nested). And bliting a 
struct obviously doesn't do a deep copy of its context.


So my question is, is there a way to deep copy the context of a 
struct?


I've tried a few things, but I don't think you can. The root 
issue is that the context pointer is void*, so you can't do 
meaningful reflection on it.


Re: Storing a reference

2016-09-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 1 September 2016 at 20:38:13 UTC, Yuxuan Shui wrote:
I think my approach is probably better, because I believe 
(correct me if I'm wrong): 1) it will never refer to a null 
object.


That's true, but you can ensure the same thing for the wrapper:

struct Ref()
{
  @disable this();
  this(T* value)
  {
assert(value !is null);
this.value = value;
  }
  // rest same as before
}

2) after DIP1000 is implemented we will be able to make sure 
there will be no dangling reference.


I'm not very familiar with the details of DIP1000, so I can't 
comment on that.


Re: Storing a reference

2016-09-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 1 September 2016 at 19:37:25 UTC, Yuxuan Shui wrote:

I just figured out how to store a reference:

@safe:
auto x(ref int a) {
struct A {
ref int xa() { return a; }
}
return A();
}
void main() {
import std.stdio;
int b = 10;
auto a = x(b);
a.xa = 20;
writeln(b); //Prints 20
}

I have no idea if this is a right thing to do. Can someone tell 
me if this is idiomatic D, and whether there're any catches to 
this method or not?


Thanks.


This will allocate a closure. A struct definition inside a 
function has a hidden context / closure pointer, unless it's a 
static struct.


There is nothing like a ref variable in D. If you want to refer 
to something someplace else, use a pointer. You can create a 
pointer wrapper which acts like a reference (untested):



auto toRef(ref T value)
{
  return Ref!T();
}

struct Ref(T)
{
  private T* value;
  @property ref T _value() { return *value; }
  alias _value this;
}

Note that D's pointer syntax is a bit friendlier than C++'s: the 
dot operator works fine on pointers. A good reason to use the Ref 
wrapper is to forward arithmetic operations to the wrapped value.


Re: Checking all elements are unique.

2016-08-31 Thread Rene Zwanenburg via Digitalmars-d-learn
On Wednesday, 31 August 2016 at 08:38:11 UTC, Andrea Fontana 
wrote:

Something like this: https://dpaste.dzfl.pl/9fa55b2a7927 ?

Andrea


Or use findAdjacent:

auto idsAreUnique = ids.array.sort.findAdjacent.empty;

http://dlang.org/phobos/std_algorithm_searching.html#.findAdjacent


Re: DerelictGL3.reload with specified path question.

2016-08-17 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 17 August 2016 at 22:59:31 UTC, WhatMeWorry wrote:
I want to store all my shared/dynamic libraries within a 
special directory relative to where the application directory 
is. All of the derelictXX.loads(path) compiles except 
DerelictGL3.reload(lib);  which doesn't seem to be implemented.


Don't ever ship OpenGL.dll with your application: it's provided 
by the graphics driver. The only exception to this rule that I 
can think of is if you want to use a software implementation for 
some reason.


Re: randomIO, std.file, core.stdc.stdio

2016-07-27 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 27 July 2016 at 02:20:57 UTC, Charles Hixson wrote:
O, dear.  It was sounding like such an excellent approach until 
this
last paragraph, but growing the file is going to be one of the 
common

operations.  (Certainly at first.) (...)
So I'm probably better off sticking to using a seek based i/o 
system.


Not necessarily. The usual approach is to over-allocate your file 
so you don't need to grow it that often. This is the exact same 
strategy used by D's dynamic arrays and grow-able array-backed 
lists in other languages - the difference between list length and 
capacity.


There is no built-in support for this in std.mmfile afaik. But 
it's not hard to do yourself.


Re: Dynamic arrays, emplace and GC

2016-07-05 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 5 July 2016 at 13:48:46 UTC, Claude wrote:
Ah ok. I tried using void[size] static array and it seems to 
work without having to use GC.addRange().


Correct. void[] means the type of the data is unknown, so the GC 
has to assume it can contain pointers.


This also means that _everything_ in any void buffer has to be 
treated as a potential pointer. In other words, if you allocate a 
void buffer and fill it with ints, and one of those ints happens 
to have a value equal to the address of a GC-allocated object, 
the GC will assume the int is a pointer to that object and not 
free it.


Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-05 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 5 July 2016 at 12:34:20 UTC, Johannes Loher wrote:

I tried this, but it does not work correctly with slices.


The length of a slice is a runtime value, which is why it can't 
be used to set static array size. What were you trying to 
achieve? Avoid copying the input arrays, or accepting any slice?


In case of the first, you can put ref in front of the Args:
auto combineArrays(Args...)(ref Args args)

The second case will be a bit harder to solve nicely..


Re: Initializing static array with contents of (static and dynamic) arrays

2016-07-04 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 4 July 2016 at 19:22:52 UTC, Johannes Loher wrote:
This looks really nice, but I have several occurences of this, 
with different arrays (and lengths), so i would need to create 
several of those structs. But it looks really clean :)


You can use a template to remove the boilerplate. Here's a quick 
example:


https://dpaste.dzfl.pl/43b379992648


Re: Commit size and Page fault's very large for simple program

2016-07-04 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 4 July 2016 at 11:42:40 UTC, Rene Zwanenburg wrote:

...


I forgot to mention:

If you're on Windows compilation defaults to 32 bit, false 
pointers can be a problem with D's current GC in 32 bit 
applications. This isn't an issue for the sample application 
though, since you're not putting random numbers in the allocated 
arrays.


64 bit doesn't suffer from this. There's also a GSoC project 
underway, aimed at improving the GC. I'm not sure what the exact 
goals are, but IIRC work on making the GC precise is being done, 
which would eliminate the false pointer issue.


Re: Commit size and Page fault's very large for simple program

2016-07-04 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 4 July 2016 at 01:57:19 UTC, Hiemlick Hiemlicker wrote:

version(Windows)

void main()
{
import std.random;

while(getchar() != EOF)
{
auto x = new int[std.random.uniform(100, 1000)];

writeln("");
bThread.Now();

}
}

more or less, ends up with a huge amount of page faults and a 
several hundred MB commit size(hold enter down a bit). I'm 
trying to understand this. Is that normal behavior for normal 
programs(haven't tried it with a similar C++ example though).


The PF's are most likely due to default initialization, so you 
may not see those in a C++ equivalent (or, actually, the exact 
equivalent would be to initialize the array as well, in that case 
you'd get PF's too). If you've determined default initialization 
is causing performance problems in a hot piece of code, D 
provides facilities to disable it.


I realize the GC has to do some work and all that but the 
program only has a working set of a few MB yet a commit of 10 
times that.


Is commit size essentially "touched" memory but really doesn't 
mean much to overall free ram?(can other programs use it at 
some point)?


Strictly speaking there's no relation between commit size and 
RAM, from your application's POV there's only the virtual address 
space. Committed memory can be paged to disk if the OS determines 
your application isn't actively using certain pages.





We know the program is not using more than 10MB


It's an array of ints, so you'll have to multiply that by four ;)

of extra memory(since x is local)... so I'd only expect the 
footprint to be a max of around 15-20MB. not 150MB+(depends on 
how fast and long you hit enter).


Keeping memory usage to an absolute minimum would mean the GC has 
to do a collection on every allocation. As a very coarse rule of 
thumb, expect a GC heap (not just the D GC) to be about 1.5 to 2 
times as large as strictly necessary. This is to reduce the 
amount of collections. Since your example is doing nothing but 
hammering the GC I'm not surprised the heap is a bit larger than 
that.


Re: Range non-emptyness assertions and opIndex

2016-07-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 1 July 2016 at 10:35:04 UTC, Nordlöw wrote:
I think this is a important issue since asserts are not 
optimized away in release mode and D is very much about 
performance.


Asserts are removed in release mode, enforce isn't. Here's an 
example:


=
void main(string[] args)
{
assert(args.length >= 1);
}
=

dmd testfile.d

This calls the assert function as expected:
=
_Dmain:
  : 55 pushrbp
  0001: 48 8B EC   mov rbp,rsp
  0004: 48 83 39 01cmp qword ptr 
[rcx],1
  0008: 73 0E  jae 
0018

  000A: B9 03 00 00 00 mov ecx,3
  000F: 48 83 EC 20sub rsp,20h
  0013: E8 00 00 00 00 call
_D5test28__assertFiZv

  0018: 31 C0  xor eax,eax
  001A: 5D pop rbp
  001B: C3 ret
=

Now compiling in release mode:
dmd -release testfile.d

No assert in sight:
=
_Dmain:
  : 55 pushrbp
  0001: 48 8B EC   mov rbp,rsp
  0004: 31 C0  xor eax,eax
  0006: 5D pop rbp
  0007: C3 ret
=


Re: How to use a char[] buffer in D

2016-06-23 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 23 June 2016 at 05:59:10 UTC, Andrew Chapman wrote:

Perfect, thank you! :-) Works like a charm.

On Wednesday, 22 June 2016 at 22:41:24 UTC, H. S. Teoh wrote:
On Wed, Jun 22, 2016 at 09:57:04PM +, Andrew Chapman via 
Digitalmars-d-learn wrote:



Maybe try:

if (buffer[] in myHash) { ... }

?  Does that make a difference?


T


If the keys are fixed-length, you may want to consider using 
immutable(char[4]) as key. That way there is no GC allocation for 
the strings at all, the only allocations are done by the AA.


Re: Templated class defaults and inheritence

2016-06-19 Thread Rene Zwanenburg via Digitalmars-d-learn

On Saturday, 18 June 2016 at 17:48:47 UTC, Joerg Joergonson wrote:

class foo(T) if (is(T : subfoo)) X;


FYI this can also be done in the template parameter list:

class foo(T : subfoo){}


Re: Out of order execution

2016-06-16 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 16 June 2016 at 01:57:19 UTC, Joerg Joergonson wrote:

Is there an efficient lazy way to make this happen?


No, I don't see how that would work.

Suppose I can't run the loop twice for performance 
reasons(there is other stuff in it) and I don't want to store 
the state and call info then sort them out afterwards.


Storing the state is your best bet. Based on your recent post 
about OpenGL I assume this is for the same project?


If so, you can reuse the storage buffer between frames. Generally 
speaking it's the allocations that are slow, copying some state 
to a buffer shouldn't be expensive. Use separate buffers for the 
Do1 and Do2 calls so you don't have to sort.


Re: GTKD - Application crashes - or not? [Coedit]

2016-06-15 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 15 June 2016 at 10:31:18 UTC, TheDGuy wrote:
Thanks a lot for your answer, getcwd() returns the path where 
coedit is located on my harddrive:

C:\Program Files (x86)\Coedit_32\coedit.2update6.win32

How can i change that?


I'm not familiar with Coedit, but the run options seem to contain 
a field for setting it:

https://github.com/BBasile/Coedit/wiki#run-options

You may be able to use the symbolic strings there:
https://github.com/BBasile/Coedit/wiki#symbolic-strings


Re: GTKD - Application crashes - or not? [Coedit]

2016-06-15 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 15 June 2016 at 09:48:19 UTC, TheDGuy wrote:
But if i execute the app my hand (in the windows command window 
or my double click) it works as expected (so no error)? Why is 
that?


My first guess would be that Coedit does not use the directory 
where the executable is located as working directory. You can 
check what getcwd returns:

https://dlang.org/phobos/std_file.html#.getcwd


Re: What's up with GDC?

2016-06-14 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 13 June 2016 at 20:21:28 UTC, Joerg Joergonson wrote:
Are you running some other program that might be sending a lot 
of broadcast messages?




Not that I know of. I haven't tried running it outside VS 
though so it might be doing something weird. I'll investigate 
further when I get a chance and get further down the road.


It's often useful to attach a sampling profiler when the process 
is eating CPU. It should tell you what's going on at a glance.


I believe VS has a sampling profiler built in, but it most likely 
won't demangle D symbols, so the function names will be a bit 
hard to read.


Re: Range and poolTask

2016-06-06 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 6 June 2016 at 10:26:11 UTC, moechofe wrote:
The functions passed to map or amap take the type of the 
element of the range as argument, but not a range itself.


Right. I don't think I understand what the semantics of your 
example would be though.. Could you elaborate a bit?


Re: Range and poolTask

2016-06-06 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 6 June 2016 at 09:32:30 UTC, moechofe wrote:

I wonder if it is possible to write something like this:
---
// taskPool.distribute -- take a range and distribute entries 
to different threads.

dirEntries().distribute(function(R1,R2)(R1 from,R2 to){
from
.filter!xxx
.map!yyy
.tee!zzz(to);
})
.each!www;
---
This would be great.


This might be useful:

http://dlang.org/phobos/std_parallelism.html#.TaskPool

Or, more specifically,

http://dlang.org/phobos/std_parallelism.html#.TaskPool.amap
http://dlang.org/phobos/std_parallelism.html#.TaskPool.map


Re: Creating a "fixed-range int" with opDispatch and/or alias this?

2016-06-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 1 June 2016 at 19:59:51 UTC, Mark Isaacson wrote:
FWIW, the fixed range int part of this question is just an 
example, I'm mostly just interested in whether this idea is 
possible without a lot of bloat/duplication.


I suspect not.. Here's how std.typecons.Proxy is doing it:

https://github.com/dlang/phobos/blob/master/std/typecons.d#L5109


Re: Using referenceCounters

2016-06-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 1 June 2016 at 18:14:33 UTC, Begah wrote:
I started using reference counters for my assets in my 
application :

 - Images
 - Models
 - 


For my resource manager I started out with something similar to 
what you're describing, but I eventually changed the design which 
turned out to be an immense improvement so I'll just describe 
that ^^


- Differentiate between the type implementing a resource, and 
handles to a resource.
- Split up the resource manager, which stores the 'real' resource 
for a given handle, and the cache where you look up resources by 
name.


A stripped down version of the resource manager looks something 
like this:




template ResourceManager(ResourceType)
{
  struct HandleImpl
  {
~this()
{
  // Destroy the resource, make sure you mark the 
corresponding slot in the array as free

}

size_t slot;
  }

  alias Handle = RefCounted!HandleImpl;

  private ResourceType[] resources;

  // When creating a resource add it to the manager and pass 
around the opaque handle instead.

  Handle add(ResourceType resource)
  {
// Find an empty slot in the resources array, put the 
resource there, and return a handle pointing to that slot.

  }

  // This should be used sparingly. Most code shouldn't care 
about resource implementation. The parts that do can get at it 
via this function, but shouldn't hold on to the reference longer 
than necessary.

  ResourceType getActualResource(Handle handle) { ... }

  // This allows you to hot-swap resources while keeping the 
resource implementation logically const. Hot-swapping is 
extremely valuable, I've always found myself wanting to support 
it sooner or later. I've tried to do it in different ways, but it 
always ended up in a mess. Using handles on the other hand turned 
out to be clean and easy.

  void update(Handle handle, ResourceType newResource) { ... }
}



Note that it doesn't allow you to search for resource by name or 
anything, this is just a simple mapping between handles and the 
resource implementation. It doesn't store instances of the 
RefCounted handles itself, so there are no issues with resources 
not being cleaned up.


Now when you have this in place you can build a caching mechanism 
on top of it:




template ResourceCache(ResourceType, alias loadByName)
{
  alias Manager = ResourceManager!ResourceType;

  Manager.Handle[string] cache;

  Manager.Handle get(string name)
  {
// Check if the resource is already in the cache, if not load 
it using the loadByName function and store it.

  }

  void purge()
  {
// the keys property allocates a new array with the AA keys, 
which is important since we're modifying the AA.

foreach(key; cache.keys)
{
  // This is the part you were actually interested in. It's 
important to take a pointer to the handle here, and not reference 
it directly. I had some issues with that in the past, I'm not 
sure if that's still the case.

  auto ptr = key in cache;
  if(ptr.refCountedStore.refCount == 1) // If this is the 
last reference

  {
destroy(*ptr); // I'm not sure if this is still 
necessary, there was some issue with AAs in the past. It may be 
fixed today. Destroying the handle doesn't hurt either way so I 
left it in.

cache.remove(key);
  }
}
  }
}



So cached resources don't get cleaned automatically if you don't 
call purge, but that's usually the right thing to do anyways. For 
example when you're changing scenes (I assume this is for some 
kind of game?) you can simply destroy the current scene, load 
another, then purge the cache, without having to reload resources 
used by both scene 1 and 2.


Another upside is that this doesn't require every resource to be 
named / backed by file. Resources can be dynamically generated at 
runtime without special casing anywhere.


Re: Base64 of String without casting

2016-06-01 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 1 June 2016 at 09:31:51 UTC, tcak wrote:
I understand that Base64 uses Ranges, and since String is seen 
and used as unicode by Ranges (please tell me if I am wrong).


I am guessing, for this reason, auto btoa = 
std.base64.Base64.encode("Blah"); doesn't work. You need to be 
casting the string to ubyte[] to make it work which doesn't 
look and feel nice at all.


Can/shall we add another alias into the module for encode 
method, so it accepts a string, and casts it to ubyte[] by 
itself?


This should do the trick:

https://dlang.org/phobos/std_string.html#.representation


Re: Preferred method of creating objects, structs, and arrays with deterministic memory management

2016-06-01 Thread Rene Zwanenburg via Digitalmars-d-learn
I was wondering: what's the preferred method for deterministic 
memory management?


You may be interested in RefCounted. It only works for structs, 
not classes, but it's still useful.


 - Classes/Structs have constructors and destructors. I am 
unconfident with my knowledge as to how this works with malloc 
and free.


malloc() and free() operate on a lower level, they only care 
about raw memory. When you malloc() some space, you can construct 
an object there using emplace(), and it can be destructed by 
using detroy().


- Many features and types use the GC such as exceptions, the 
new keyword, and all arrays except statics.


It's important to differentiate static arrays, and slices with 
static storage. For example:


class C
{
  static int[] someSlice; // This is a slice with static storage. 
The memory it is referring to may be GC allocated, but it doesn't 
have to (this is true for all slices btw).


  int[4] someStaticArray; // This is a static array, i.e. an 
array with a fixed length. In D static arrays are value types, so 
it's allocated in its enclosing scope and copied when you pass it 
around.

}

 - std.container.array can be used for deterministic arrays, 
but has the issue of dangling pointers. There is probably a 
good solution to this, but I don't know it.


I don't know of any dangling pointer issues with Array. It's 
possible to create cycles resulting in a leak, but that's only 
likely to happen if you heavily rely on refcounting everything.


 - There seems to be no way to completely turn off the GC. That 
is, never have the runtime allocate the memory used by the GC.


Like Rikki said, if you really want to the GC can be replaced 
with an asserting stub. This isn't as hard as it sounds, just add 
something like the file he linked to to your project. Since all 
declarations are extern(C) there is no name mangling, and the 
linker will prefer your own definitions over the ones in 
druntime. I don't recommend you do this though unless you really 
know what you're doing.


This are the pieces I've gathered, but I don't really know 
what's true or how to use this knowledge. Some ideas I've 
gleaned may also be outdated. Does anyone know the "correct" 
way one would go about a non-GC program, and if a program can 
be ran without ever instantiating a GC? Has there been any 
progress on reducing the std library's usage of the GC?


You can annotate your functions as @nogc. The compiler will 
disallow any potential GC use, including calling other functions 
that are not @nogc.


P0nce is doing real time audio stuff, iirc he's using a thread 
with a @nogc entry point for the strictly real-time parts, and 
regular GC-using code in another thread for everything else.


Re: Benchmark Dlang vs Node vs Ruby

2016-05-27 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 27 May 2016 at 15:18:38 UTC, llaine wrote:

- And how can I minimize allocations?


My previous post still allocates though, through that call to 
array at the end. I'm not sure how to completely remove all 
allocations (I'm not that familiar with vibe.d), but I strongly 
suspect it's possible. Someone else may know how.


That said, it's a an optimization which should not be necessary 
in the general case. Only if you're doing something where there's 
tight maximum latency requirements (or when doing benchmarks ^^)


Re: Benchmark Dlang vs Node vs Ruby

2016-05-27 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 27 May 2016 at 15:04:31 UTC, llaine wrote:
My level of D is really slow, so can you help me to improve 
this? :)


Here's an alternative getCompanies. Untested so it may contain 
some mistakes.


Company[] getCompanies() {
  auto conn = client.lockConnection();
  immutable result = conn.execStatement("SELECT id, name from 
companies LIMIT 1", ValueFormat.TEXT);

  delete conn;

  import std.algorithm : map;
  import std.array : array;

  return result
.rangify
.map!(row => Company(row["id"].as!PGtext, 
row["name"].as!PGtext))

.array;
}


Re: Benchmark Dlang vs Node vs Ruby

2016-05-27 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 27 May 2016 at 13:45:23 UTC, llaine wrote:

Hi guys,

In my journey of learning about D I tried to benchmark D with 
Vibe.d vs node with express and Ruby with Sinatra.


And the results are pretty surprising.
I have to admit that I though D was more faster than that. How 
is this even possible ?


I am doing something wrong ?


Here are the numbers with the project :

https://github.com/llaine/benchmarks/blob/master/README.md


Could this line be the problem?
https://github.com/llaine/benchmarks/blob/master/vibed/source/app.d#L30

You keep appending the db result to a class member, so the 
response size grows with every call.


Additionally minimizing allocations should give a nice speed 
boost.


Re: Introspect alias name of an aliased type

2016-05-23 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 23 May 2016 at 10:45:49 UTC, ParticlePeter wrote:

Is there a way to get the alias uint32_t instead ?


Nope. For the compiler uint32_t and uint are the same thing, this 
is by design. Typedef can be used to create a separate type with 
the same semantics as the type it's based upon:


https://dlang.org/phobos/std_typecons.html#.Typedef


Re: How to share an appender!string?

2016-05-19 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 19 May 2016 at 10:58:42 UTC, Rene Zwanenburg wrote:
Calling task() only creates a Task, you also have to start it 
somehow. The documentation contains an example:


https://dlang.org/phobos/std_parallelism.html#.task


I should add that a single shared array will cause contention if 
the number of calls to addLine is large compared to the amount of 
work done.


If performance is a problem, another way is to use a thread local 
array and merge the arrays to a single global one on thread 
termination. Something like this:


// thread local. Can be appended to without locking
string[] lines;

__gshared Mutex mutex;

shared static this()
{
  mutex = new Mutex();
}

__gshared string allLines;
static ~this()
{
  synchronized(mutex)
  {
allLines ~= lines;
  }
}

This will not preserve order of course, and you'll have to make 
sure all your worker threads are terminated before using 
allLines. Both can be fixed if required but will make the code 
more complicated.


The upside is that this will avoid contention on the mutex. 
You'll still have to be careful with the GC though, just about 
every GC operation takes a global lock so it doesn't play nice 
with high perf multi-threaded code.


Re: How to share an appender!string?

2016-05-19 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 19 May 2016 at 10:41:14 UTC, Thorsten Sommer wrote:
On Thursday, 19 May 2016 at 10:13:21 UTC, rikki cattermole 
wrote:



At this point I'd recommend you to just ignore Appender.
Write your own.


Dear rikki,

Thanks for the proposal :) Here is the new attempt #4 as simple 
test case: https://dpaste.dzfl.pl/f6a9663320e5


It compiles & runs, but the array of strings gets not shared 
across threads :( I am sure that I missed something about the 
shared() concept...


Hmm...


Best regards,
Thorsten


Calling task() only creates a Task, you also have to start it 
somehow. The documentation contains an example:


https://dlang.org/phobos/std_parallelism.html#.task


Re: Does DUB create .dll files?

2016-05-17 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 17 May 2016 at 05:30:33 UTC, WhatMeWorry wrote:
Am I supposed to get ALURE32.DLL from somewhere outside of DUB, 
or did I miss a step or command when I built 
derelict-alure-master?


thanks.


You'll need to get the dll somewhere else and set up DUB to copy 
it to your output directory. The derelict packages don't include 
prebuilt binaries for the libraries they're binding to.


Here's how dlangui does it for example:

https://github.com/buggins/dlangui/blob/master/dub.json#L60


Re: DMD flag -gs and -gx

2016-05-13 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 13 May 2016 at 10:19:04 UTC, Nordlöw wrote:

  -gsalways emit stack frame


IIRC, not emitting a stack frame is an optimization which 
confuses debuggers. So I think this can be used to make optimized 
builds a bit easier to debug.



  -gxadd stack stomp code


After a function returns the stack normally still contains the 
local variables of that function, but they can be overwritten at 
any time (which is why it's unsafe to escape references to stack 
variables from a function). Using this switch will cause the 
compiler to overwrite the stack with bogus values before 
returning, which will help with early detection of bugs like the 
above. It can also be useful in security contexts where a 
function operates on sensitive data.


Re: Accepting function or delegate as function argument

2016-05-04 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 4 May 2016 at 14:54:39 UTC, chmike wrote:
Two constructors, one accepting a function and the other one 
accepting a delegate would do the job for the API. Is there a 
simple method to convert a function pointer into a delegate 
pointer that is also efficient ?


http://dlang.org/phobos/std_functional.html#.toDelegate

You can also make your constructor a template, constrain it on 
isCallable if you wish, and then use toDelegate. If the argument 
is already a delegate toDelegate will avoid doing extra work.


Static introspection in a class hierarchy

2016-05-02 Thread Rene Zwanenburg via Digitalmars-d-learn
I'm in the process of making my code compile with DMD 2.071. 
There's a construction I've been using which now results in a 
deprecation message, and I'm not sure how to properly fix it.


It's a bit like design by introspection within a class hierarchy. 
For example:


abstract class Base
{
  private void initialize(){}
}

class Derived : Base
{
  private void initialize(){}
}

Then an external function walks the inheritance chain of a 
statically known derived type and call the init functions. 
Something like this:


void callInitialize(T)(T instance)
{
  static if(BaseClassesTuple!T.length > 1)
  {
callInitialize!(BaseClassesTuple!T[0])(instance);
  }

  static if(only(__traits(derivedMembers, 
T)).canFind("initialize"))

  {
auto initializePtr = &__traits(getMember, instance, 
"initialize")

initializePtr();
  }
}

That __traits(getMember, ... trick was used to access private 
initialize() functions but now results in a deprecation warning:
Deprecation: Derived.initialize is not visible from module 
moduleWhereCallInitializeIsDefined


Declaring both initialize functions as public final doesn't work 
at all:
Error: function Derived.initialize cannot override final function 
Base.initialize


I thought shadowing like this was allowed? Apparently not..

Anyway, what would be the right way to do something like this? I 
don't want to use virtual functions; the need to call 
Base.initialize() in Derived.initialize is leaking implementation 
details and error prone, and I can't afford the overhead. 
(Initialize is a bad example regarding overhead, but I use the 
same mechanism to register callbacks if present. Using static 
introspection makes the difference between thousands of static 
calls that do actual work and millions of useless virtual calls, 
every second)


Re: Linker error for d.o: relocation R_X86_64_32 against `__dmd_personality_v0'

2016-04-22 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 21 April 2016 at 16:29:14 UTC, rcorre wrote:
- What happens when you compile a binary without phobos and 
druntime, and with a custom entry point? I've never done that 
myself and don't remember how to do that off the top of my 
head, but the info should be somewhere on dlang.org.


I'll look into it.


Declaring a C-like main and the -defaultlib switch do the trick:

 cmain.d
extern(C) void main() nothrow {}
---

dmd cmain.d -defaultlib=""


If even that fails to link I honestly wouldn't know where to look 
next..


Re: Linker error for d.o: relocation R_X86_64_32 against `__dmd_personality_v0'

2016-04-21 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 21 April 2016 at 11:54:27 UTC, rcorre wrote:


Thanks for the tip. Here's the linking code it shows:


cc d.o -o d -m64 -L/usr/lib -L/usr/lib32 -Xlinker 
--export-dynamic -Xlinker -Bstatic -lphobos2 -Xlinker -Bdynamic 
-lpthread -lm -lrt -ldl
/usr/bin/ld: d.o: relocation R_X86_64_32 against 
`__dmd_personality_v0' can not be used when making a shared 
object; recompile with -fPIC


I tried `cc d.o -o d -m64 -fPIC and still get the error.


Right, the -fPIC should be used while compiling the source code, 
but that's a gcc option. I think DMD is supposed to always 
generates position independent code.


Here are a few things you can try to narrow the problem down. I'm 
not too familiar with this stuff though, so I'm just shooting in 
the dark here and not all of it may make sense ^^


- What happens when you mark main() as nothrow? That personality 
symbol has to do with exception handling.
- Is it possible the linker is picking up 32 bit libraries? That 
-L/usr/lib32 switch is a bit suspicious.

- What happens when you compile for 32 bit?
- What happens when you compile a binary without phobos and 
druntime, and with a custom entry point? I've never done that 
myself and don't remember how to do that off the top of my head, 
but the info should be somewhere on dlang.org.
- What happens when you compile some D code as a static lib, and 
link it with a main written in C?


Oh, and I take it you've already tried to simply reinstall DMD? 
If you uninstall DMD, look if there are still sc.ini's and 
libphobos.a's floating around.


Re: Linker error for d.o: relocation R_X86_64_32 against `__dmd_personality_v0'

2016-04-21 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 21 April 2016 at 01:20:27 UTC, rcorre wrote:

s/compile/link
I _can_ compile a D library, but as soon as I try to link 
anything compiled with DMD it falls over.


What is dmd's verbose output? (add -v switch)

Some of the things it outputs are the location of the config file 
it uses, you can inspect that file to see if it has been borked 
somehow.


Near the bottom you can find the used link command, that could 
also reveal the problem.


Re: Shallow copy object when type is know

2016-04-21 Thread Rene Zwanenburg via Digitalmars-d-learn

On Wednesday, 20 April 2016 at 19:58:15 UTC, Tofu Ninja wrote:
To implement a copy/paste/duplicate functionality in a game 
editor. I have an entity-component system, to duplicate an 
entity, all it's components need to be duplicated. I have many 
many components, I don't want to rely on manually writing copy 
methods for each, it is too error prone. There are only a very 
few that need special copies, almost all can get by with a 
simple shallow copy. I would like a generic way to do that 
shallow copy.


How are you handling loading and saving of your components? Can't 
you use the same mechanism, without going through the storage 
format?


Anyway, to answer your question, perhaps something like this: 
(untested, it probably needs some minor modifications to compile)


T shallowCopy(T)(T source)
{
assert(source.classinfo == T.typeinfo);
auto rv = new T;
shallowCopy(source, rv);
return rv;
}

void shallowCopy(T)(T source, T target)
{
foreach(i; 0 .. T.tupleof.length)
{
target.tupleof[i] = source.tupleof[i];
}

import std.traits : BaseClassesTuple;
alias baseClasses = BaseClassesTuple!T;

static if(baseClasses.length > 0)
{
shallowCopy!(baseClasses[0])(source, target);
}
}




How does D not have shallow copy? Seems like a very basic 
functionality...


Generally speaking copying class instances is a very bad idea. 
That's one of the things structs are for.


Re: @nogc inconsistent for array comparison depending on mutability of elements

2016-04-08 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 8 April 2016 at 09:56:41 UTC, Nick Treleaven wrote:
If the comparison with b shouldn't be allowed, I suggest we add 
opEquals to std.range.only. This removes a need to import 
std.algorithm.equal and reduces bracket nesting:


assert(b == only(1, 2));


equal[1] can compare ranges of different types. It's a bit less 
clear than the original code though.


b.equal(only(1, 2));

[1] http://dlang.org/phobos/std_algorithm_comparison.html#.equal


Re: Issue with 2.071: Regression or valid error?

2016-04-08 Thread Rene Zwanenburg via Digitalmars-d-learn

On Friday, 8 April 2016 at 08:26:11 UTC, Daniel Kozak wrote:

On Friday, 8 April 2016 at 06:08:38 UTC, 9il wrote:
On Thursday, 7 April 2016 at 15:55:16 UTC, Steven 
Schveighoffer wrote:
Wow, totally agree with you. Compiler shouldn't make you jump 
through this hoop:


void foo(Cat cat)
{
   Animal a = cat;
   a.create();
}

Please file a bug report, not sure why this happened.

-Steve


Why this is a bug? private methods are not virtual, are they? 
--Ilya


No they are not virtual, so this is not a bug.


I disagree, virtuality has nothing to do with this. After all, 
moving Cat to the same module as Animal, or making create() 
public final will make the code compile.


Private symbols can (only) be accessed from the module where they 
are defined, so anything in the animal module should be able to 
call create() on a Cat just fine.


Re: VibeCustomMain not working

2016-04-07 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 7 April 2016 at 13:40:17 UTC, Rene Zwanenburg wrote:
That's possible of course, but I'd expect something so 
fundamental breaking to be noticed sooner.


Just to make sure, could you run dub with --force to rule out 
that it's picking up some stale object files from somewhere?


And if that doesn't work, post the output of dub --force 
--verbose and we should be able to figure out where it goes wrong.


Re: VibeCustomMain not working

2016-04-07 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 7 April 2016 at 13:25:29 UTC, Jerry wrote:
I generated a visuald project and tried that. Now suddenly it 
is working as expected. So I guess it's a bug in dub.


That's possible of course, but I'd expect something so 
fundamental breaking to be noticed sooner.


Just to make sure, could you run dub with --force to rule out 
that it's picking up some stale object files from somewhere?


Re: Convert wchar* to wstring?

2016-04-05 Thread Rene Zwanenburg via Digitalmars-d-learn

On Tuesday, 5 April 2016 at 01:21:55 UTC, Thalamus wrote:
I'm sorry for this total newbie question, but for some reason 
this is eluding me. I must be overlooking something obvious, 
but I haven't been able to figure this out and haven't found 
anything helpful.


In case you haven't done so already, you'll also have to use 
CharSet = CharSet.Unicode in the DllImport attribute.


Re: Read only delegate

2016-04-04 Thread Rene Zwanenburg via Digitalmars-d-learn

On Monday, 4 April 2016 at 08:10:10 UTC, Edwin van Leeuwen wrote:
Is there a way to make sure a delegate only reads state, 
without changing it? I tried annotating the delegate as const, 
but that does not seem to work.

```


Yeah this is a nasty old issue. The underlying problem is that a 
delegate's function and context pointers are completely untyped.


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


Re: foreach UFCS

2016-03-31 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 31 March 2016 at 13:39:25 UTC, ixid wrote:

What is going on with UFCS and foreach?

foreach(i;0..5).writeln;

This prints five line breaks.

foreach(i;0..5).i.writeln;

This will not compile.

foreach(i;0..5).writeln(i);

This writes out 1 to 4 on separate lines. Is this supposed to 
work? I thought a.b would be rewritten to b(a) with UFCS but 
writeln(foreach(i;0..5)) is nonsensical and does not compile 
and should be the same as foreach(i;0..5).writeln;


The compiler interprets it as a foreach without curly braces. 
With curlies it would look like:

foreach(i; 0..5)
{
  .writeln();
}

In this context the dot means the writeln lookup should happen 
from the module level scope.


Re: Continuous integral range predicate

2016-03-31 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 31 March 2016 at 11:33:36 UTC, Nordlöw wrote:
Is there a function in Phobos to check if a range of integral 
elements is adjacent, that is


x[i+1] == x[i] + 1

where x[i] is the i:th element of the range.


(untested)

std.algorithm.findAdjacent!((a, b) => a != b+1)(range).empty;


Re: Usage of custom class with JSONValue

2016-03-24 Thread Rene Zwanenburg via Digitalmars-d-learn
On Thursday, 24 March 2016 at 08:24:46 UTC, Edwin van Leeuwen 
wrote:
Alternatively there are multiple serialization libraries that 
will allow you to turn any user defined type from and to 
JSONValues.


https://code.dlang.org/packages/painlessjson
https://code.dlang.org/packages/jsonizer

Cheers, Edwin


I don't know the above libraries so I can't comment on their 
quality, but I've used vibe.d's json module extensively and it's 
pretty solid. Vibe has also recently been split up into multiple 
subpackages, so you only have to depend on vibe-d:data and don't 
have to pull in the rest.


Re: parsing HTML for a web robot (crawler) like application

2016-03-23 Thread Rene Zwanenburg via Digitalmars-d-learn
On Wednesday, 23 March 2016 at 09:02:37 UTC, Martin Tschierschke 
wrote:

Hello!
I want to set up a web robot to detect changes on certain web 
pages or sites.
Any hint to similar projects or libraries at dub or git to look 
at,

before starting to develop my own RegExp for parsing?

Best regards
mt.


Adam's dom.d will get you pretty far. I believe it can also 
handle documents that aren't completely well-formed.


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


Re: immutable array in constructor

2016-03-18 Thread Rene Zwanenburg via Digitalmars-d-learn

On Thursday, 17 March 2016 at 10:11:43 UTC, Jeff Thompson wrote:
This is a simplified example from a larger class I have where I 
need an immutable constructor. This is because I need to 
construct an object an pass it to other functions which take an 
immutable object. So, how to keep an immutable constructor?


In that case, new immutable C() should work I believe. Also, if 
you mark the constructor as pure, new C() should be implicitly 
convertible to an immutable C.


  1   2   >