Re: struct destructor

2021-05-15 Thread Dennis via Digitalmars-d-learn

On Saturday, 15 May 2021 at 17:55:17 UTC, Alain De Vos wrote:
Feature request, a function old which does the opposite of new, 
allowing deterministic,real-time behavior and memory 
conservation.


You can use 
[object.destroy](https://dlang.org/phobos/object.html#.destroy) 
to destruct, and 
[GC.free](https://dlang.org/phobos/core_memory.html#.GC.free) to 
free memory allocated with `new`.


Re: Scope of import

2021-05-15 Thread Dennis via Digitalmars-d-learn

On Saturday, 15 May 2021 at 11:38:22 UTC, Adam D. Ruppe wrote:
* rdmd runs the program too, dmd -i just compiles. You run the 
program separately.


You can do `dmd -i -run main.d`


Re: bindbc.sfml , sfVideoMode , Error: undefined identifier

2021-05-08 Thread Dennis via Digitalmars-d-learn

On Saturday, 8 May 2021 at 09:05:18 UTC, Alain De Vos wrote:

I must doing something wrong ?


Did you define the `SFML_Graphics` version like in the README of 
bindbc-sfml?




Re: Measure cpu time

2021-05-07 Thread Dennis via Digitalmars-d-learn

On Friday, 7 May 2021 at 08:52:13 UTC, Dennis wrote:
If you want to use it on Windows as well, this is a code 
snippet I wrote for that:


For completeness, the imports it uses:
```D
version(Windows) {
import core.sys.windows.windows;
	import core.sys.windows.psapi: PROCESS_MEMORY_COUNTERS, 
GetProcessMemoryInfo;

} else version(Posix) {
	import core.sys.posix.sys.resource: rusage, getrusage, 
RUSAGE_SELF, timeval;

} else {
static assert(0, "unsupported platform");
}
```


Re: Measure cpu time

2021-05-07 Thread Dennis via Digitalmars-d-learn

On Friday, 7 May 2021 at 08:25:43 UTC, Andre Pany wrote:
Is there some equivalent function in Phobos to get the cpu time 
on linux?


I don't think so, but you can use `core.sys.posix.sys.resource: 
rusage`.


If you want to use it on Windows as well, this is a code snippet 
I wrote for that:

```D
/// Describes how much cpu time a process has been getting
struct CpuUsage {
	/// Time that the process has executed in kernel mode in 
microseconds

ulong kernelTimeUs;

	/// Time that the process has executed in user mode in 
microseconds

ulong userTimeUs;
}

bool getCpuUsage(out CpuUsage r) {
version(Windows) {
void* currentProcess = GetCurrentProcess();
FILETIME creationTime; // time that process was created
FILETIME exitTime; // undefined if process has not exited
FILETIME kernelTime; // ru_stime
FILETIME userTime; // ru_utime
		if (GetProcessTimes(currentProcess, , , 
, ) == 0) {

return false; // GetLastError();
}
ulong toMicroseconds(FILETIME ft)  {
			return (ft.dwLowDateTime | cast(ulong) ft.dwHighDateTime << 
32) / 10;

}
r.kernelTimeUs = toMicroseconds(kernelTime);
r.userTimeUs = toMicroseconds(userTime);
} else version(Posix) {
rusage rusageStruct;
if (getrusage(RUSAGE_SELF, ) == -1) {
return false; //errno
}
auto toMicroseconds(timeval t) {
return cast(ulong) t.tv_sec * 1_000_000 + t.tv_usec;
}
r.kernelTimeUs = toMicroseconds(rusageStruct.ru_stime);
r.userTimeUs = toMicroseconds(rusageStruct.ru_utime);
}
return true;
}
```
On Windows you need to link to "Psapi.lib", e.g. with 
`pragma(lib, "Psapi.lib")` or `libs "Psapi.lib"` in dub.sdl.


Re: How to check for combinations of versions

2021-05-05 Thread Dennis via Digitalmars-d-learn

On Wednesday, 5 May 2021 at 15:03:16 UTC, Blatnik wrote:
Is there any way to check for multiple conditions in a 
`version` statement?


No, and that's by design to discourage complex version logic.
The recommended approach is:

```D
version (Version_A) version = Cool_Feature_Supported;
version (Version_B) version = Cool_Feature_Supported;

void do_something_cool() {
  version(Cool_Feature_Supported) {
...
  } else {
...
  }
}

```



Re: ioctl to set mixer volume

2021-04-16 Thread Dennis via Digitalmars-d-learn

On Friday, 16 April 2021 at 17:50:13 UTC, Alain De Vos wrote:
The following very simple low level C-function simply sets the 
mixer volume. How to convert this simple function to dlang ?

```
void mixer_setlevel_stereo(int mixfd,int dev,int left,int right)
{
left+=256*right;
#int_ioctl(int fd, unsigned long request, ...);
ioctl(mixfd,
((unsigned long) (((0x8000UL|0x4000UL)) | 
(((sizeof(int)) & ((1 << 13) - 1)) << 16) | ((('M')) << 8) | 
((dev,

);
}
```


You could change `sizeof(int)` to `int.sizeof` and `(unsigned 
long)` to `cast(uint)` in this case, but it seems you expanded 
the IOWR macro resulting in the ugly mess of bitwise operations.


I did a search for your function name and found what I think is 
the original C code:


```C
void mixer_setlevel_stereo(int mixfd,int dev,int left,int right)
{
  left+=256*right;
  ioctl(mixfd,MIXER_WRITE(dev),);
}
```

Looking at my `/usr/include/linux/soundcard.h:`

```
#define MIXER_WRITE(dev)_SIOWR('M', dev, int)
```

And _SIOWR looks identical to IOWR, so I think this is a correct 
translation:


```D
import core.sys.posix.sys.ioctl: ioctl, _IOWR;

void mixer_setlevel_stereo(int mixfd, int dev, int left, int 
right)

{
left += 256 * right;
ioctl(mixfd, _IOWR!int('M', dev), );
}
```



Re: Endianness - How to test code for portability

2021-03-12 Thread Dennis via Digitalmars-d-learn

On Friday, 12 March 2021 at 05:53:40 UTC, Preetpal wrote:
This is not an important issue to me but I was just curious to 
see if anyone actually tests for portability issues related to 
endianness by compiling their D Lang code for a big endian 
architecture and actually running it on that system.


I have a png decoder, and I often avoid a dependency on 
endianness by using bit-shifts instead of casts. For example, 
this code reads a big-endian integer and returns a native-endian 
integer, regardless of architecture:


```
uint readUintBe(in ubyte[] s) {
return (s[0] << 24) | (s[1] << 16) | (s[2] << 8) | s[3];
}
```

There is a part in the decompression where a ubyte[] is cast to a 
uint[] for performance, and it assumes a little-endian byte 
order. There is a fallback for big-endian architectures, but also 
for CTFE, where reinterpretation through overlapped fields or 
array casts is not allowed. So the code is structured like this:


```
version(BigEndian) {
private enum bigEndian = true;
} else {
private enum bigEndian = false;
}

int parse(in ubyte[] data) {
if (__ctfe || bigEndian) {
// Portable code
} else {
// Little-endian optimized code
}
}
```

Then you can test both at runtime and compile time:
```
unittest {
ubyte[] testData = [...];
assert(parse(testData) == 3);
static assert(parse(testData) == 3);
}
```

So no, I don't have a big-endian computer I can test it on, but I 
do test with CTFE, so I'm pretty sure I'm not relying on a 
specific byte order.


Re: Two functions with different args. Taking address of the one

2021-03-11 Thread Dennis via Digitalmars-d-learn

On Thursday, 11 March 2021 at 12:56:34 UTC, Виталий Фадеев wrote:
What right way to call function directly with selecting one of 
two ?


If they are not nested functions, you can also do:
```
// Separate names
void processKey (ref MouseKeyEvent event) {...}
void processMove(ref MouseMoveEvent event) {...}

// Still create overload set
alias process = processKey;
alias process = processMove;

_processMouseKey  = 
_processMouseMove = 
```



Re: Introspection of exceptions that a function can throw

2021-02-24 Thread Dennis via Digitalmars-d-learn

On Wednesday, 24 February 2021 at 19:38:53 UTC, Mark wrote:
Is there a way to obtain a list, at compile-time, of all the 
exception types that a function might throw (directly or 
through a call to another function)?


No, since this is not known at compile-time.

See: 
https://forum.dlang.org/post/qnarroejixxtqxjiw...@forum.dlang.org


Re: Why am I getting a dividing by zero error message

2021-01-28 Thread Dennis via Digitalmars-d-learn
On Thursday, 28 January 2021 at 18:37:37 UTC, Ruby The Roobster 
wrote:

object.Error@(0): Integer Divide by Zero
Why is this happening? Does anybody know?



data[0] = (new egg(0,0,"a"));


Here you set data[0].y to 0


tempb = data[x].y;


In the first iteration, this equals data[0].y which equals 0


temp = tempa / tempb;


And then you divide by zero here, hence the error






Re: How can I check to see if template type is an array?

2021-01-19 Thread Dennis via Digitalmars-d-learn

On Tuesday, 19 January 2021 at 22:26:52 UTC, Tim wrote:
I need to be able to check in a template whether the type given 
is an array type so that I can do some different logic. How can 
I do this?


`if(is(T == E[], E))` or `isDynamicArray!T` is you `import 
std.traits;`


Re: Open question: what code pattern you use usually for null safety problem

2021-01-14 Thread Dennis via Digitalmars-d-learn

On Thursday, 14 January 2021 at 18:24:44 UTC, ddcovery wrote:
If it's not a bother, I'd like to know how you usually approach 
it


Usually I don't deal with null because my functions get primitive 
types, slices, or structs. `ref` parameters can be used to 
replace pointers that may not be null.

When something is nullable by design, I usually do this:

```
if (!person) {
return; // early return if possible
}
if (auto f0 = person.father) {
if (auto f1 = f0.father) {
   if (f1.name == "Peter") {
   doSomething();
   }
}
}
```

It doesn't matter whether you're working with a class, pointer, 
or struct with opCast, this works. When access patterns get 
complex the nesting may get very deep.
Only if you can't avoid this I would consider using fancy helper 
functions, otherwise just use an if-statement or the && operator.


Re: Is there a way to work with processes in Windows without extern(c)?

2021-01-13 Thread Dennis via Digitalmars-d-learn

On Wednesday, 13 January 2021 at 14:04:52 UTC, dog2002 wrote:
I could use extern(c) and Process Walking (Process32First, 
Process32Next), but maybe there is a way to get the list by 
means of D?


I don't think this is part of the standard library.
Here's a piece of code I wrote a while ago if that's useful:

```
pragma(lib, "Kernel32.lib");

/**
 * Get a list of tuples for each currently running process, 
containing name and id

 * Returns:
 *   array of (name, id) tuples
 */
auto getProcessList() @system {
	import core.sys.windows.tlhelp32: CreateToolhelp32Snapshot, 
TH32CS_SNAPPROCESS,

Process32First, Process32Next, PROCESSENTRY32;
	import core.sys.windows.windows: HANDLE, INVALID_HANDLE_VALUE, 
CloseHandle;


import std.typecons: Tuple, tuple;
import std.string: fromStringz;
import std.conv: to;

HANDLE hProcessSnap;
PROCESSENTRY32 pe32;
hProcessSnap = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
scope(exit) CloseHandle(hProcessSnap);

alias restype = Tuple!(string, "name", int, "id");
restype[] result = [];

if (hProcessSnap != INVALID_HANDLE_VALUE) {
pe32.dwSize = PROCESSENTRY32.sizeof;
for (auto notAtEnd = Process32First(hProcessSnap, );
notAtEnd;
notAtEnd = Process32Next(hProcessSnap, )
) {
			string processName = 
pe32.szExeFile[].ptr.fromStringz.to!string;

result ~= restype(processName, pe32.th32ProcessID);
}
}

return result;
}
```


Re: Using multiple mixin templates to implement operator overloading

2020-12-12 Thread Dennis via Digitalmars-d-learn

On Saturday, 12 December 2020 at 18:14:31 UTC, Paul Backus wrote:
IMO this is one of the stupider design decisions in D, but it's 
unlikely it will ever be fixed. The easiest workaround is to 
use string mixins instead, which work the way you'd expect them 
to.


If issue 19365 got fixed, it could be done with an alias instead.
https://issues.dlang.org/show_bug.cgi?id=19365

Currently string mixins are indeed the best option though.


Re: Ways to parse D code.

2020-11-25 Thread Dennis via Digitalmars-d-learn

On Wednesday, 25 November 2020 at 16:27:41 UTC, Jan Hönig wrote:

What is the "easiest" way to parse D code?
(...)
libdparse seems to do it as well with `parseModule` function.
https://github.com/dlang-community/libdparse/blob/master/src/dparse/parser.d


I recommend libdparse.

dmd has to do it somewhere as well. Although I don't know 
exactly where. I do know ldc uses dmd's frontend for parsing.

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


DMD as a library is still experimental. You can try to use it, 
but libdparse is more stable.


I am also a little confused about who uses what. Does D-Scanner 
use libdparse?


Yes, most tools that parse D code do, including Adam's 
documentation generator: https://github.com/adamdruppe/adrdox


Only LDC, GDC and VisualD use the dmd front-end as far as I know.


Is there a D grammar for pegged?
https://github.com/PhilippeSigaud/Pegged


Not complete and outdated, but it's a start:
https://github.com/PhilippeSigaud/Pegged/tree/master/examples/dgrammar



Re: Source code folder naming convention?

2020-11-04 Thread Dennis via Digitalmars-d-learn
On Wednesday, 4 November 2020 at 11:15:33 UTC, Vladimirs Nordholm 
wrote:
Is there a "best practice" of what the source folder should be 
called?


`dub init` creates a folder named `source`, so I would stick with 
that.




Re: is type checking in D undecidable?

2020-10-22 Thread Dennis via Digitalmars-d-learn

On Thursday, 22 October 2020 at 17:25:44 UTC, Bruce Carneal wrote:
Is type checking in D undecidable?  Per the wiki on dependent 
types it sure looks like it is.


It is indeed undecidable. Imagine you had a decider for it. 
Because CTFE is clearly turing-complete, you can express that in 
a D function `bool typeChecks(string code)` and then do this 
(similar to the halting problem):

```
enum int x = typeChecks(import(__FILE__)) ? "abc" : 100;
```


Re: Best way to confine project to 64 bit builds only?

2020-10-17 Thread Dennis via Digitalmars-d-learn

On Saturday, 17 October 2020 at 14:50:47 UTC, NonNull wrote:
I have inherited an open source C project that assumes that the 
size of a long and the size of a pointer are the same, and I 
have translated it into very similar D just like 
https://dlang.org/blog/2018/06/11/dasbetterc-converting-make-c-to-d/


D has the size of long fixed at 64 bits, so a pointer now has 
to be 64 bits.


If you want to exactly match the original C code's semantics, I 
suggest translating (unsigned) long with c_long or c_ulong. You 
can import them here:

```
import core.stdc.config: c_long, c_ulong;
```

Then you could add this:
```
static assert(c_long.sizeof == size_t.sizeof);
```

This will fail on Windows 64 bit, where C longs are 32-bit and 
pointers 64-bit.


Re: Neater "not version (...)" ?

2020-09-16 Thread Dennis via Digitalmars-d-learn
On Wednesday, 16 September 2020 at 19:04:24 UTC, Vladimirs 
Nordholm wrote:
Ah, I guess it boils down to this then. Doesn't really make it 
"neater", but thank you for the tip!


IMO, just keep it as `version(Windows) {} else { ... }` if you 
HAVE to instead of one of the workarounds people suggest. I do 
wonder what kind of code runs on the "not Windows" operating 
system though, do you mean `version(Posix)` perhaps?


Re: How does one run a linux system command from a D main() fcn ?

2020-08-04 Thread Dennis via Digitalmars-d-learn

On Tuesday, 4 August 2020 at 19:52:47 UTC, Andy Balba wrote:

i.e.  D  equivalent to C++ command system("MyExe")


Apart from std.process, you can also call the C function in D 
after importing core.stdc.stdlib:


https://dlang.org/library/core/stdc/stdlib/system.html



Re: dlib 0.19.1 seems to be failing linking with ldc2

2020-07-31 Thread Dennis via Digitalmars-d-learn

On Friday, 31 July 2020 at 14:17:14 UTC, jeff thompson wrote:
dlib.lib(dlib.audio.io.wav.obj) : error LNK2019: unresolved 
external symbol 
_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv 
referenced in function 
_D3std6format__T10printFloatTfTaZQrFNaNfNkAafSQBsQBr__T10FormatSpecTaZQpEQCtQCs12RoundingModeZQCa
dlib.lib(dlib.filesystem.local.obj) : error LNK2001: unresolved 
external symbol 
_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv

.dub\build\application-debug-windows-x86_64-ldc_2092-316AB5B187D20C1F6AFBA496E604908D\test.exe
 : fatal error LNK1120: 1 unresolved externals



The first thing you want to do is demangle the symbols so you 
know what they really are.

You can use the tool `ddemangle` for that:
```
echo 
'_D3std6format__T10printFloatTfTaZQrFNaNfNkAafSQBsQBr__T10FormatSpecTaZQpEQCtQCs12RoundingModeZQCa' | ddemangle

```

You'll find that this symbol is missing:

pure nothrow @nogc @safe void 
core.internal.switch_.__switch_error!().__switch_error(immutable(char)[], ulong)


And it's used in this function:

pure @safe char[] std.format.printFloat!(float, 
char).printFloat(return char[], float, 
std.format.FormatSpec!(char).FormatSpec, std.format.RoundingMode)


The switch_error function is called when none of the cases of a 
`final switch` apply. There is a final switch in 
std.format.printFloat:

https://github.com/ldc-developers/phobos/blob/c43cafe53746a07dee8fa9e00d3a2256c7f05506/std/format.d#L7096

So why is the compiler not emitting the final switch error 
template function? I am not sure, it could be a bug, or maybe you 
have some funky dub settings. You might be able to work around 
this by defining a final switch in you own code somewhere, or 
explicitly defining the function.


```
pragma(mangle, 
"_D4core8internal7switch___T14__switch_errorZQrFNaNbNiNfAyamZv")

void switchError(string file, ulong line) {
assert(0, file);
}
```

I hope someone else with more familiarity of how template symbols 
are emitted can find the root of this problem and give a proper 
fix.




Re: Templates and SIMD - examining types

2020-07-22 Thread Dennis via Digitalmars-d-learn

On Wednesday, 22 July 2020 at 21:58:16 UTC, Cecil Ward wrote:
I need to then work out what is the size of the internal units 
within the 128-bit value, size in bytes,1 or 2, at compile time.


You can use the .sizeof property on the type.

```
import core.simd;
void main() {
ubyte16 a;
ushort8 b;
pragma(msg, a.sizeof);
pragma(msg, b.sizeof);
pragma(msg, a[0].sizeof);
pragma(msg, b[0].sizeof);
pragma(msg, typeof(a[0]));
pragma(msg, typeof(b[0]));
}
```

16LU
16LU
1LU
2LU
ubyte
ushort


Re: alias restriction??!

2020-07-18 Thread Dennis via Digitalmars-d-learn

On Saturday, 18 July 2020 at 18:46:16 UTC, Carl Sturtivant wrote:
Is there any way to avoid the duplication of the entries in the 
anonymous union, aside from using a mixin template?


I think this would be fixed if 
https://github.com/dlang/dmd/pull/11273 gets merged.


Re: Print only part of a stack trace

2020-07-01 Thread Dennis via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 19:33:08 UTC, JN wrote:
Bit off-topic, but if you can use them, debug contexts offer 
much better OpenGL error-checking experience. 
https://www.khronos.org/opengl/wiki/Debug_Output . Instead of 
checking glGetError() after each call, you can setup a C 
callback that will trigger whenever an error occurs. It also 
offers some vendor-specific performance warnings.


I use those as well, to get a more detailed message about the 
error than the error code alone. While it helps describing _what_ 
went wrong, it doesn't tell me _where_ it went wrong.


I tried doing assert(0) in the callback, but even with 
glEnable(GL_DEBUG_OUTPUT_SYNCHRONOUS), the stack trace looks 
something like this:


app.d: debugCallback [0x559eda75c7e8]
??:? [0x7f4a0bffa7d7]

And then it ends. It seems like it goes up into the OpenGL dll 
and then gets stuck, it does not trace back to the call site of 
the glFunction that failed.


Re: Print only part of a stack trace

2020-07-01 Thread Dennis via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 18:54:55 UTC, Dennis wrote:
It sort of works, but it seems it does not start at the right 
stack frame, the top item is this:


??:? void rt.dmain2._d_run_main2(char[][], ulong, extern (C) 
int function(char[][])*).runAll().__lambda1() [0x55c19a09c1fa]


So dmd skips the first 5 stack frames to account for 
_d_traceContext, _d_createTrace etc, while ldc filters out by 
filename.


https://github.com/ldc-developers/druntime/blob/cc97ccd00d4082221eee1d5afdbd775201d75877/src/core/runtime.d#L855

I can easily work around this, though it's unfortunate that the 
public API of DefaultTraceInfo has this limitation.


Re: Print only part of a stack trace

2020-07-01 Thread Dennis via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 18:44:10 UTC, Stanislav Blinov wrote:
void assertNoOpenGLErrors(string file = __FILE__, int line = 
__LINE__, string func = __PRETTY_FUNCTION__)

{
if (glGetError() != GL_NO_ERROR) {
print(file, ":", line, ":", func, ": blah");
exit();
}
}

:)


I love __FILE__ and __LINE__, but in this case they won't cut it.
In my actual code there's usually one or two more functions 
inbetween, and amending hundreds of signatures with __FILE__ and 
__LINE__ for a little debugging convenience is not worth it.


I'm now trying to call the defaultTraceHandler manually like this:
```
void bar() {
import std.stdio;
import core.runtime: defaultTraceHandler;
auto res = defaultTraceHandler(null);
writeln(res);
}

void foo() {bar();}
void main() {foo();}
```

It sort of works, but it seems it does not start at the right 
stack frame, the top item is this:


??:? void rt.dmain2._d_run_main2(char[][], ulong, extern (C) int 
function(char[][])*).runAll().__lambda1() [0x55c19a09c1fa]


Re: Print only part of a stack trace

2020-07-01 Thread Dennis via Digitalmars-d-learn

On Wednesday, 1 July 2020 at 18:05:09 UTC, Jacob Carlborg wrote:
[1] 
https://dlang.org/phobos/core_runtime.html#.Runtime.traceHandler


Thanks, but I don't want to re-implement the default trace 
handler, I want to use it on a specific location and capture its 
output. I'll be more specific in what I want to achieve.


I have a function that checks a global error constant of a C 
library (OpenGL) like this:

```
void assertNoOpenGLErrors() {
if (glGetError() != GL_NO_ERROR) {
assert(0); // stack trace points to here instead of caller
}
}
```

And I would like to rewrite it to this:
```
void assertNoOpenGLErrors() {
if (glGetError() != GL_NO_ERROR) {
print(getStackTrace().filterTrace());
exit();
}
}
```

So that the stack trace immediately points to the function that 
raised the OpenGL error, instead of it being buried in a large 
trace.


Print only part of a stack trace

2020-07-01 Thread Dennis via Digitalmars-d-learn
On assertion failure, the default error handler prints a stack 
trace that looks like this


[library functions]
[application functions]
[druntime start-up functions]

I'm only interested in application functions, the rest is noise.
I could easily filter unwanted lines out if I had the stack trace 
in string form, but I don't know how to obtain that. Is there a 
simple way to do this, or should I delve into Druntime internals?




Re: How to work Get & Set text in clipboard in Windows ?

2020-06-20 Thread Dennis via Digitalmars-d-learn

On Saturday, 20 June 2020 at 13:32:22 UTC, Vinod K Chandran wrote:
I would like to know how to get & set text in clipboard. I am 
using windows machine.


This is an example of setting the clipboard using the Windows API 
in D:

```
/// Returns: true on success
bool setClipboard(string str) {
import core.stdc.string: memcpy;
import std.string: toStringz;
	import core.sys.windows.windows: GlobalAlloc, GlobalLock, 
GlobalUnlock,

OpenClipboard, EmptyClipboard, SetClipboardData, CloseClipboard,
CF_TEXT, CF_UNICODETEXT, GMEM_MOVEABLE;

auto hMem = GlobalAlloc(GMEM_MOVEABLE, str.length + 1);
if (hMem is null) {
return false;
}
memcpy(GlobalLock(hMem), str.ptr, str.length);
(cast(char*) hMem)[str.length] = '\0'; // zero terminator
GlobalUnlock(hMem);
if (!OpenClipboard(null)) {
return false;
}
EmptyClipboard();
if (!SetClipboardData(CF_TEXT, hMem)) {
return false;
}
CloseClipboard();
return true;
}
```

Here's an example of getting it, from arsd:
https://github.com/adamdruppe/arsd/blob/ae17d5a497de93454f58421cd9d4a5ecd70594c0/terminal.d#L2043

Here is a C example from GLFW:
https://github.com/glfw/glfw/blob/51a465ee2b50234f984efce0e229f7e9afceda9a/src/win32_window.c#L2150


Re: How to parse enum from a string ?

2020-05-27 Thread Dennis via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 17:33:33 UTC, Vinod K Chandran wrote:
I am saving this enum values as string in database. So, when i 
retrieve them from the database, how can i parse the string 
into TestEnum ?


Use `to` from `std.conv`.

```
import std.conv: to;
void main() {
assert("Received".to!TestEnum == TestEnum.Received);
}
```


Re: What's the best way to find out which exceptions may be thrown ?

2020-05-27 Thread Dennis via Digitalmars-d-learn

On Wednesday, 27 May 2020 at 09:56:07 UTC, wjoe wrote:
The problem with catch(Exception) is that it's run time whereas 
I'd like to know compile time which exception may possibly be 
thrown.


Note that this is impossible in general due to the nature of 
classes.
A function could at runtime find the latest trending hashtag on 
twitter, name a class after it that derives from Exception, 
invoke the compiler to generate a shared library that throws an 
exception with that class, load that library, and call the newly 
loaded function that throws the newly created exception class.


Obviously there's no way of knowing this class at compile time.



Re: Can You Expand Arrays into an Argument List?

2020-05-15 Thread Dennis via Digitalmars-d-learn

On Friday, 15 May 2020 at 19:19:59 UTC, H. S. Teoh wrote:

Here's how to do it:

int add(int[] args...) {
... // access `args` here as an array
}


Beware that that language feature, typesafe variadic functions, 
might become deprecated:

https://github.com/dlang/dmd/pull/11124


Re: DScanner warns class is undocumented, how to resolve it ?

2020-05-14 Thread Dennis via Digitalmars-d-learn

On Thursday, 14 May 2020 at 06:08:17 UTC, Vinod K Chandran wrote:
On Thursday, 14 May 2020 at 06:05:00 UTC, Vinod K Chandran 
wrote:

Hi all,
I wrote a class and in VS Code, DScanner says that the class 
is undocumented. How can i document a class ?


Never mind, i found the answer myself. Just like in dot net, i 
added triple forward slash comment and problem solved.


If you plan to publish your code to dub, consider actually 
documenting it or marking it private/package so it won't appear 
as an undocumented symbol.


Re: Is there a way to benchmark/profile portably?

2020-05-07 Thread Dennis via Digitalmars-d-learn

On Thursday, 7 May 2020 at 10:21:07 UTC, Dukc wrote:
Is there some way to measure the performance of a function so 
that the results will be same in different computers (all x86, 
but otherwise different processors)? I'm thinking of making a 
test suite that could find performance regressions 
automatically.


You can make a reference program that you use to get a measure 
for how fast the computer is that you run the benchmark on. Then 
you can use that to scale your actual benchmark results.


When testing regressions there's a fairly obvious choice for this 
reference program: the old version. You can compare those results 
with the new version and report the relative difference.


Re: To get memory from another process.

2020-04-09 Thread Dennis via Digitalmars-d-learn

On Thursday, 9 April 2020 at 19:27:16 UTC, Quantium wrote:
I see this code imports drivers and does it depend on processor 
architecture? Would it work only on 64-bit or 32-bit or some 
special architechtures?


kernel32.dll and psapi.dll should be present on any normal 
Windows 10 installation.


Windows only runs on x86 and ARM processors as far as I know. I 
have never used Windows with an ARM processor, but I assume such 
a Windows installation has the full WinAPI implemented, in which 
case it should work.


As for 32-bit/64-bit on x86:

- 32-bit OMF: might work, but I often get errors because the 
Digital Mars import libraries for Windows dll's are outdated so I 
don't recommend this target

- 32-bit COFF: pretty sure it works
- 64-bit COFF: definitely works, I use this regularly.

In any case, I suggest you just try these out to see yourself.


Re: To get memory from another process.

2020-04-09 Thread Dennis via Digitalmars-d-learn

On Thursday, 9 April 2020 at 17:23:19 UTC, Quantium wrote:
Ok. For training example, we're using Windows 10 Por. We can 
use WinAPI. Are there any D libs to use WinAPI?


I have used the Windows API to read/write into a different 
process before. Here is some example code in case it's useful: (I 
removed some stuff without recompiling so it may have some errors)


```
version(Windows):
pragma(lib, "Kernel32.lib");
pragma(lib, "Psapi.lib");

struct WinProcess
{
import core.sys.windows.winbase: OpenProcess, 
ReadProcessMemory, WriteProcessMemory, CloseHandle;
import core.sys.windows.windows : PROCESS_VM_READ, 
PROCESS_VM_WRITE,

PROCESS_QUERY_INFORMATION, PROCESS_VM_OPERATION, HANDLE;

import std.bitmanip;
import std.exception: enforce;

int processId = -1; /// Id of the process this is attached to
HANDLE processHandle = null; /// Windows handle of the process

this(int processId) {
this.processId = processId;

const access = PROCESS_VM_READ | PROCESS_QUERY_INFORMATION
| PROCESS_VM_WRITE | PROCESS_VM_OPERATION;
this.processHandle = OpenProcess(access, false, 
processId);

enforce(processHandle, "could not open process");
}

import std.traits: isNumeric;

void write(T)(void* address, T value) if (isNumeric!T) {
enforce(processHandle != null, "not attached to a process 
yet");

size_t bytesWritten = 0;
ubyte[T.sizeof] buffer;
auto b = buffer[];
b.write(value, 0);
WriteProcessMemory(processHandle, address, cast(void*) 
buffer, buffer.sizeof, );
enforce(bytesWritten == T.sizeof, "could not write all 
bytes");

}

T read(T)(void* address) if (isNumeric!T) {
enforce(processHandle != null, "not attached to a process 
yet");

size_t bytesRead = 0;
ubyte[T.sizeof] buffer;

ReadProcessMemory(processHandle, address, cast(void*) 
buffer, buffer.sizeof, );


enforce(bytesRead == T.sizeof, "could not read all 
bytes");


auto b = buffer[]; // lvalue
return b.read!T;
}
}
```



Re: Whats wrong with binery heap or i am not understand something?

2020-04-02 Thread Dennis via Digitalmars-d-learn

On Thursday, 2 April 2020 at 13:23:29 UTC, Dennis wrote:
writeln recognizes b and h as ranges, and prints them by 
iterating over each element,


Correction: this only applies to `h`, the array slice `b` will 
not be mutated by writeln.


Re: Whats wrong with binery heap or i am not understand something?

2020-04-02 Thread Dennis via Digitalmars-d-learn

On Thursday, 2 April 2020 at 12:59:06 UTC, AlexM wrote:

Please explain me whats wrong with binery heap?!!!


This has nothing to do with binaryheap and all to do with writeln.
writeln recognizes b and h as ranges, and prints them by 
iterating over each element, which advances the range to the end. 
You can see that the following actually prints what you expect:


```
 writeln(b[]);   // [1, 2, 3, 4, 7, 9, 10, 14, 8, 16]
 writeln(h.dup); // [1, 2, 3, 4, 7, 8, 9, 10, 14, 16]
 writeln(h.length); // 10
 h.insert(21);
 writeln(h.dup); // [1, 2, 3, 4, 7, 8, 9, 10, 14, 16, 21]
 writeln(h.length); // 11
```




Re: How to code Z-Function of string?

2020-03-26 Thread Dennis via Digitalmars-d-learn

On Thursday, 26 March 2020 at 19:34:08 UTC, Quantium wrote:

1. How can I make string ONLY char[] (Not immutable)


You can use .dup to make a mutable copy of an array.

```
char[] a = "abc".dup;
```

2. How can I work with some of chars in the stirng, is, for 
example:

string s="abc";
writeln(s[1]); // Should write 'b' or not???
Is it a legit code or it doesn't work ?


Yes, that works.


Re: return val if

2020-03-22 Thread Dennis via Digitalmars-d-learn

On Sunday, 22 March 2020 at 18:48:32 UTC, Abby wrote:
Is there a way to create a template that would do the same is 
glib


g_return_val_if_fail() 
(https://developer.gnome.org/glib/stable/glib-Warnings-and-Assertions.html#g-return-val-if-fail)


I'm not famililar with glib, but the description:

If expr evaluates to FALSE, the current function should be 
considered to have undefined behaviour (a programmer error).


Sounds a lot like:

```
assert(expr);
```


I was hoping something like this would work

template returnValIfFail(alias expr, alias val)
{
if(expr) return val;
}


It would have to be a string mixin, you can't inject a return 
statement otherwise.
The thing is, why do you want that? It seems shorter to just 
write it out:


if(expr) return val;
debug if(expr) return val;
returnValIfFail!(expr, val);




Re: Best way to learn 2d games with D?

2020-03-17 Thread Dennis via Digitalmars-d-learn

On Tuesday, 17 March 2020 at 22:47:43 UTC, Sebastiaan Koppe wrote:
Dont trust that marketing, there is actually decent scripting 
in gamemaker, which you'll need if you get creative.


Second that. GameMaker is how I got into programming at age 12, 
and look where I ended up ;)


Re: Best way to learn 2d games with D?

2020-03-17 Thread Dennis via Digitalmars-d-learn
On Sunday, 15 March 2020 at 17:58:58 UTC, Steven Schveighoffer 
wrote:
I want to try and learn how to write 2d games. I'd prefer to do 
it with D.


I haven't seen anyone mention Dgame yet:

https://github.com/Dgame/Dgame

It's not maintained anymore since last November [1], but is seems 
pretty mature and it has a tutorial:


http://dgame-dev.de/index.php?controller=learn=tutorial=0.6

[1] Searching for Dgame Maintainer - 
https://forum.dlang.org/post/mkobhebqxcfytkgal...@forum.dlang.org


Re: Integer without restrictions

2020-03-15 Thread Dennis via Digitalmars-d-learn

On Sunday, 15 March 2020 at 19:07:05 UTC, ... wrote:
And if I need to create very large value, how to use GMP 
library (It isn't described in that post)?


You can use C bindings [1], look up examples in C and do the same 
in D, or use a high-level wrapper [2].


[1] https://code.dlang.org/packages/libgmp
[2] https://code.dlang.org/packages/gmp-d


Re: Does anyone have gdb pretty printers for buildin types like associative arrays?

2020-03-15 Thread Dennis via Digitalmars-d-learn

On Sunday, 15 March 2020 at 16:42:52 UTC, Panke wrote:
Should this just work and by box is not correctly configured or 
do I need some pretty printers? If so, has someone already made 
them?


Take a look at:

https://forum.dlang.org/post/ztyhmmxalpiysgjkv...@forum.dlang.org




Re: Cool name for Dub packages?

2020-03-07 Thread Dennis via Digitalmars-d-learn

On Saturday, 7 March 2020 at 10:49:24 UTC, Paolo Invernizzi wrote:

Frankly, I simply hate all that shuffle around names ...


I remember someone noting how unusual it is for D to have a name 
for its standard library, "Phobos".




Re: converting to/from char[]/string

2020-03-05 Thread Dennis via Digitalmars-d-learn

On Thursday, 5 March 2020 at 11:31:43 UTC, mark wrote:
I've now got Martin Porter's own Java version, so I'll have a 
go at porting that to D myself.


I don't think that's necessary, the errors seem easy to fix.

src/porterstemmer.d(197,13): Error: cannot implicitly convert 
expression s.length of type ulong to int
src/porterstemmer.d(222,9): Error: cannot implicitly convert 
expression cast(ulong)this.m_j + s.length of type ulong to int


These errors are probably because the code was only compiled on 
32-bit targets where .length is of type `uint`, but you are 
compiling on 64-bit where .length is of type `ulong`.
A quick fix is to simply cast the result like `cast(int) 
s.length` and `cast(int) (this.m_j + s.length)`, though a proper 
fix would be to change the types of variables to `long`, 
`size_t`, `auto` or `const` (depending on which is most 
appropriate).


src/porterstemmer.d(259,12): Error: function 
porterstemmer.PorterStemmer.ends(char[] s) is not callable 
using argument types (string)
src/porterstemmer.d(259,12):cannot pass argument "sses" 
of type string to parameter char[] s


These errors are because `string` is `immutable(char)[]`, meaning 
the characters may not be modified, while the function accepts a 
`char[]` which is allowed to mutate the characters.
I don't think the functions actually do that, so you can simply 
change `char[]` into `const(char)[]` so a string can be passed to 
those functions.


Re: dscanner and ref parameters

2020-02-23 Thread Dennis via Digitalmars-d-learn

On Sunday, 23 February 2020 at 09:03:56 UTC, mark wrote:
Then this would not only help dscanner, but also make it clear 
to programmers that the argument could be modified.


(This is done in Rust with f( arg), and I certainly find it 
helpful.)


C# also does it, and uses exactly the same keyword as D:

To use a ref parameter, both the method definition and the 
calling method must explicitly use the ref keyword, as shown in 
the following example.


https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/ref

Making it mandatory in D would cause code breakage and hamper 
generic code, but like you suggest, making it optional is an 
interesting idea. It can also enforce that something is actually 
passed by ref to avoid accidental copies, which currently 
requires manual checking. For example in std.format:



// force toString to take parameters by ref
static assert(!__traits(compiles, val.toString(s, 
FormatSpec!Char(;

static assert(!__traits(compiles, val.toString(S(), f)));}


https://github.com/dlang/phobos/blob/fee0697a8328dc22258cf09753f39ad5984015db/std/format.d#L3887




Re: Speeding up compilation of template-heavy code

2020-02-22 Thread Dennis via Digitalmars-d-learn

On Saturday, 22 February 2020 at 11:26:19 UTC, Per Nordlöw wrote:
Is there a dmd flag that shows the code after template 
instantiations has been performed?


The -vcg-ast flag does that.


Re: Conditional Attributes

2020-02-20 Thread Dennis via Digitalmars-d-learn

On Tuesday, 18 February 2020 at 17:11:55 UTC, Marcel wrote:
Say I have a struct where every member function can either be 
static or not depending on a template parameter. Is there a 
simple way to do this?


The best I can think of is:

```
mixin template maybeStatic() {
void foo() {
// implementation
}
}

struct S(bool condition) {
static if (condition) {
static {
mixin maybeStatic;
}
} else {
mixin maybeStatic;
}
}
```

What do you need this for? It seems like an unusual situation to 
me.


Re: State of MIPS

2020-02-19 Thread Dennis via Digitalmars-d-learn

On Wednesday, 19 February 2020 at 07:09:02 UTC, April wrote:
What's the current state of MIPS compiling for bare metal? 
Especially the R4300i processor.


I've had some success with running D code on Nintendo 64 
emulators, which emulate a R4300i processor. I'm compiling with:


ldc2 -march=mips -mcpu=mips3 -output-o -betterC -c sourcefile.d

And then use a custom linker to inject the segments.
Some of the issues I came across:
- global variables should be marked __gshared or immutable to 
avoid thread-local storage.
- LDC sometimes inserts calls to memcpy, memset and memcmp, so I 
provided implementations for those
- double precision floating point code does not work, only single 
precision

- functions returning large structs by value was not supported

Apart from that it worked decently. I'm not sure what kind of 
support your looking for exactly, but I suggest just giving it a 
try and see how far you get.


Re: Some impressions/notes from a new D programmer

2020-02-12 Thread Dennis via Digitalmars-d-learn

Thanks for your perspective. Just a few things are unclear to me:

On Wednesday, 12 February 2020 at 10:39:06 UTC, mark wrote:
I don't find the presentation of the member properties and 
methods very easy to read


Can you elaborate a bit on this?

The lack of set and B-tree types is disappointing (esp. 
considering that the much younger Rust has them). I'm using 
rbtree for sets but that imposes a requirement that my items 
support < (rather than the == or hash I'd expect for a set).


This confuses me. So there is std.container.rbtree, but you don't 
like that the element type needs to have an order defined? How 
can Rust do binary search in a tree that has no order?
If you are looking for a hashset, you can use an associative 
array for that.


However, dub doesn't seem to be competitive with Rust's cargo. 
Getting fast statically built (no dependency) executables is 
really nice.


I've heard good things about cargo, but haven't used it myself 
yet.

Do you have a specific thing dub can improve the most on?



Re: Flatten a range of static arrays

2020-02-07 Thread Dennis via Digitalmars-d-learn
On Friday, 7 February 2020 at 21:40:36 UTC, Steven Schveighoffer 
wrote:
S.popFront is not @safe, and S is not a template. So no 
inferrence.


Oops, minimized a bit too much. Corrected test case:
```
import std;

struct S {
@safe:
 int[3] front = [10, 20, 30];
 bool empty = false;
 void popFront() {empty = true;}
}

void main() @safe {
 S.init.map!((return ref x) => x[]).joiner.writeln;
}
```
It indeed still errors with -dip1000, but without -dip1000 it 
compiles now interestingly.


Re: Flatten a range of static arrays

2020-02-07 Thread Dennis via Digitalmars-d-learn

On Friday, 7 February 2020 at 20:55:14 UTC, nullptr wrote:
Depending on how your range is structured, it might be possible 
to just mark front as returning by ref to make this work.


That's a good one. I can't make front() return by ref, but I can 
make front a member variable of the range struct. Only problem:
@safe function ... cannot call @system function 
std.algorithm.iteration.joiner!(...).joiner


I don't know why. I don't have time to delve into this at the 
moment but if anyone wants to try, here's a minimal testcase:


```
import std;

struct S {
int[3] front = [10, 20, 30];
bool empty = false;
void popFront() {empty = true;}
}

void main() @safe {
S.init.map!((return ref x) => x[]).joiner.writeln;
}
```
flags: -dip1000 -dip25



Re: Flatten a range of static arrays

2020-02-07 Thread Dennis via Digitalmars-d-learn
On Friday, 7 February 2020 at 20:31:47 UTC, Steven Schveighoffer 
wrote:
The only solution I can provide is to wrap the static array 
into a range (maybe something like this exists in Phobos?):


Thanks. I was hoping something like that existed in Phobos, but I 
can't find anything.


Flatten a range of static arrays

2020-02-07 Thread Dennis via Digitalmars-d-learn
If I have an input range with element type `int[3]`, how do I 
easily turn it into a range of `int` so I can map it?
If it were an int[3][] I could simply cast it to an int[] before 
mapping, but I don't want to eagerly turn it into an array.

I thought of doing this:
```
range.map!(x => x[]).joiner.map!(x => x*2);
```

But it gives:
Error: returning x[] escapes a reference to parameter x, perhaps 
annotate with return


I tried doing:
```
map!((return x) => x[]) // same error
map!((return ref x) => x[]) // does not match, map.front is not 
an lvalue

```

I can easily work around it with some more code, but I wonder if 
someone knows an easy solution.


Re: const pointers C vs. D

2020-02-04 Thread Dennis via Digitalmars-d-learn

On Tuesday, 4 February 2020 at 10:06:03 UTC, Johann Lermer wrote:
In C, this would not be valid. So the question for me now is: 
is const char* in D different from C?


Yes, const char* in D reads as const(char*), so it is a char* 
that cannot be modified.

This is similar to the C code:

char *const text = "Hello";

However, because of transitivity, the characters also can't be 
modified (unlike C).
For a mutable pointer to const characters, you indeed do 
const(char)*.


See also:
https://dlang.org/articles/const-faq.html

C++ has a const system that is closer to D's than any other 
language, but it still has huge differences:


- const is not transitive
- no immutables
- const objects can have mutable members
- const can be legally cast away and the data modified
- const T and T are not always distinct types





Re: Cannot take slice of scope static array in @safe code

2020-02-02 Thread Dennis via Digitalmars-d-learn
On Sunday, 2 February 2020 at 18:18:28 UTC, Steven Schveighoffer 
wrote:

scope should have been a type constructor.


I feel the same way, I find const/immutable much easier to reason 
about than scope in its current state.
Do you think scope as a storage class is fundamentally broken, or 
is it still sound, just not very granular?


Re: Cannot take slice of scope static array in @safe code

2020-02-02 Thread Dennis via Digitalmars-d-learn

Thanks for your response.

On Sunday, 2 February 2020 at 15:20:39 UTC, ag0aep6g wrote:
Now it's important to realize that `scope` only applies to the 
top-level of the type.


This is where my confusion was.
I knew scope wasn't transitive, so I thought that `scope 
string[1]` meant the static array could not escape the function, 
but the elements of it (the strings) could, since arr[0] would 
yield a `string` and not a `scope string`. I thought that it 
wouldn't have mattered if the element type had indirections 
(string) or not (int).


Now I realize scope applies to the elements, since indexing a 
static array doesn't actually remove a layer of indirection 
unlike a dynamic array.




Cannot take slice of scope static array in @safe code

2020-02-02 Thread Dennis via Digitalmars-d-learn

Compiling the following with -dip1000 gives an error.

```
void main() @safe {
string[1] a0;
scope int[1] a1;
scope string[1] a2;

scope string[] b0 = a0[]; // Fine
scope int[] b1 = a1[]; // Fine
scope string[] b2 = a2[]; // Error: cannot take address of 
scope local a2

}
```

Can anyone explain why? I don't see how b2 violates the scope 
constraint of a2.
It might be a compiler bug, but since the int[] case works, I 
could also just be missing something about how `scope` works on 
`string[1]`.


Re: list of all defined items in a D file

2020-01-24 Thread Dennis via Digitalmars-d-learn

On Thursday, 23 January 2020 at 17:10:29 UTC, berni44 wrote:
I'd like to get a list of all items (public, package, private) 
that are defined in a D file. Is there a simple way, to get 
them?


You can pass the -X flag to dmd, which makes it generate a .json 
file describing the compiled file.


Re: Win32 Api: How create a Color Dialog?

2020-01-09 Thread Dennis via Digitalmars-d-learn

On Thursday, 9 January 2020 at 13:04:33 UTC, Marcone wrote:

I am creating a GUI using winsamp.d as model.
See the window here: https://i.ibb.co/ZJ4v2KD/Sem-t-tulo.png
I want to ask a user for choose a color when click 
Configuration/Color, and then change backgroud color of GUI. 
But how can I create a Color Dialog? There's dlang example in 
the web and I can not make c++ example work.


Windows has the 'common dialog' module with a ChooseColor 
function you can use.


https://docs.microsoft.com/en-us/previous-versions/windows/desktop/legacy/ms646912(v=vs.85)

(The link is not clickable on the forum because of the closing 
bracket, you have to manually copy-paste it)


An example of how to use it can be found here:

https://github.com/adamdruppe/arsd/blob/fc896e74cb6939ef3d81d592045885fbe1cc6f98/minigui_addons/color_dialog.d#L14

Or try this (I am not on Windows currently so this isn't tested):
```
import core.sys.windows.windows;
pragma(lib, "comdlg32");

uint getColor(uint defaultColor) {
COLORREF[16] acrCustClr; // array of custom colors

CHOOSECOLOR cc;
cc.lStructSize = cc.sizeof;
	cc.hwndOwner = null; // owner window, allowed to be NULL if no 
owner

cc.lpCustColors = cast(LPDWORD) acrCustClr;
cc.rgbResult = defaultColor;
cc.Flags = CC_FULLOPEN | CC_RGBINIT;

if (ChooseColor()) {
return cc.rgbResult;
} else {
return 0; // user clicked cancel
}
}

import std;

void main() {
const color = getColor(0xFFFF); // default color red
const red = color & 0xFF;
const green = (color >> 8) & 0xFF;
const blue = (color >> 16) & 0xFF;
writeln("Selected color is (", red, ",", green, ",", blue, 
")");

}

```


Re: @safe std.file.read

2020-01-06 Thread Dennis via Digitalmars-d-learn

I would say it should return a ubyte[].

On Monday, 6 January 2020 at 10:07:37 UTC, WebFreak001 wrote:

Or should void[] actually be castable to ubyte[] in @safe code?


Definitely not with the current semantics, since a void[] can 
alias pointers in @safe code.

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


Re: How bundles a Dlang application and all its dependencies into a single .exe package?

2019-12-01 Thread Dennis via Digitalmars-d-learn

On Sunday, 1 December 2019 at 20:05:40 UTC, Marcone wrote:
How bundles a Dlang application and all its dependencies into a 
single .exe package?


You can embed files in the .exe using the import statement:
https://p0nce.github.io/d-idioms/#Embed-a-dynamic-library-in-an-executable


Re: static assert(version(x)) ?

2019-11-26 Thread Dennis via Digitalmars-d-learn
On Tuesday, 26 November 2019 at 10:24:00 UTC, Robert M. Münch 
wrote:
How can I write something like this to check if any of a set of 
specific versions is used?


```
version(a) {}
else version(b) {}
else version(c) {}
else {
   static assert(0, "only versions a, b and c are supported");
}
```

```
version(a) version = supported;
version(b) version = supported;
version(c) version = supported;
version(supported) {
// good to go
} else {
static assert(0, "not a supported version");
}
```


static assert(!(version(a) | version(b) | version(c)):


That seems to be the opposite of what you describe.
If you want that, then:
```
version(a) static assert(0, "version a not supported");
version(b) static assert(0, "version b not supported");
version(c) static assert(0, "version c not supported");
```



Re: How to catch a signal

2019-11-09 Thread Dennis via Digitalmars-d-learn

On Saturday, 9 November 2019 at 12:44:20 UTC, W.Boeke wrote:

What should be the right way to accomplish this?


Put an ampersand before the function to get its address:

  signal.signal(SIGWINCH,cast(void function(int)) _winch);


In C you can omit the & when taking a function address, but when 
you do that in D it tries to call the function and cast the 
return value of the function instead.


Re: Duration to Decimal Total

2019-11-06 Thread Dennis via Digitalmars-d-learn
On Wednesday, 6 November 2019 at 19:13:46 UTC, Jonathan Levi 
wrote:
I would think a function that this would be appropriate to 
belong in the module.  Am I missing it?  Or, how would you 
recommend calculating it?


The author of the module has explained before that this is very 
intentional:

https://forum.dlang.org/post/mailman.3711.1453121204.22025.digitalmars-d-le...@puremagic.com



Re: Unable to pass a D function member to a C callback

2019-11-02 Thread Dennis via Digitalmars-d-learn

On Saturday, 2 November 2019 at 20:42:29 UTC, Luh wrote:

Yup that's it !
Many thanks !


One word of warning: ensure the C library does not have the only 
reference to your Game class instance, or the garbage collector 
might deallocate it since it does not scan threads created by C 
libraries.


See:
https://dlang.org/spec/garbage.html#gc_foreign_obj


Re: Unable to pass a D function member to a C callback

2019-11-02 Thread Dennis via Digitalmars-d-learn

On Saturday, 2 November 2019 at 19:42:54 UTC, Luh wrote:

So I think I just can't. :(


Is that `void* c` in the callback a context pointer by any chance?
That's a common thing in C callbacks precisely for purposes like 
this.
You can cast your class to a void* when you register the callback 
and in the callback function cast it back to a class and call 
process on that.


I don't know what C library you're working with so can't give you 
specifics.


Re: Documentation: is it intentional that template constraints are displayed after the signature?

2019-11-01 Thread Dennis via Digitalmars-d-learn
Template constraints are not allowed before the signature in the 
language, so it can be expected the documentation does not swap 
that order.


On Thursday, 31 October 2019 at 13:34:35 UTC, Tobias Pankrath 
wrote:

I was confused at first by the trailing

 if (!is(T == struct) && !is(T == interface) && !is(T == class) 
&& !__traits(isStaticArray, T));


Or are you confused by the newline between the ) and the if?
I do think the indentation is a bit confusing, but I don't know a 
better one.
I always have difficulty myself when trying to cleanly format 
long signatures of template functions.


Re: Why Dlang use parsing expression grammar (PEG) parser not BNF?

2019-11-01 Thread Dennis via Digitalmars-d-learn

On Thursday, 31 October 2019 at 08:40:42 UTC, lili wrote:

Hi:
   I want implementation Lua on D, I find that a PEG parser 
https://github.com/PhilippeSigaud/Pegged

   why do not use BNF parser. Is PEG better than BNF?


The readme has a link to the reference article:

https://bford.info/pub/lang/peg

Which says in the abstract:

The power of generative grammars to express ambiguity is 
crucial to their original purpose of modelling natural 
languages, but this very power makes it unnecessarily difficult 
both to express and to parse machine-oriented languages using 
CFGs. Parsing Expression Grammars (PEGs) provide an 
alternative, recognition-based formal foundation for describing 
machine-oriented syntax, which solves the ambiguity problem by 
not introducing ambiguity in the first place.




Re: About the in expression, Why can't use with array.

2019-10-25 Thread Dennis via Digitalmars-d-learn

On Friday, 25 October 2019 at 19:49:05 UTC, Ali Çehreli wrote:
I'm still not completely sold on the whole idea though because 
it's not a clear win.


Do others see other advantages in other places like templates? 
For example, could templates really be written generically for 
arrays and associative arrays?


I'm personally not concerned about generic code.
- The semantics of `in` aren't very well defined anyways.
- Those who write templates like that (hopefully) know what 
they're doing, they'll figure it out  ;)
- I can't think of situations where you actually want to write 
code that generically works on both arrays and associative arrays 
like that. (Though if anyone knows one, please share, I'm 
interested.)


I'm more concerned about the repeated reports of users being 
surprised that `in` doesn't work like they expect. In Python, the 
expression `3 in [2, 3, 4]` returns a boolean, and in D you can 
do `bool b = 15 in iota(10, 20)` because the operator is 
overloaded in Phobos for iota; But as far as actual language 
support, `in` is only defined for associative arrays:


https://dlang.org/spec/expression.html#InExpression

It returns a pointer which can be used in an if-statement, but 
also to read/modify the value. So should `in` on arrays do the 
same? It would be consistent, but usage of raw pointers is 
discouraged with the advent of scope and ref etc. Also you can't 
implicitly convert a pointer to a boolean.
Should it be a boolean then? That means part of the result of the 
linear search is discarded, making `in` less flexible.
So maybe we should leave it for now, and put a small explanation 
in the error message.


Re: About the in expression, Why can't use with array.

2019-10-25 Thread Dennis via Digitalmars-d-learn

On Friday, 25 October 2019 at 05:17:35 UTC, Ali Çehreli wrote:

- Big O is different


No it isn't. Worst case lookup of an associative array lookup is 
O(n) too. It can easily be 'achieved' by having a key type with:

```
size_t toHash() const scope pure {
return 0;
}
```

The fact that std.container specifies a worst-case time 
complexity for operations on its data structures doesn't mean 
every other type has to comply to those too.
I can overload the 'in' operator on my types to something that 
takes exponential time if I want, just like "+" can also be 
overloaded to a linear time operation on e.g. BigInt.


- One wants to use keys for associative arrays but (likely) 
values for arrays


Then we implement `in` to look for values in arrays, just like 
users would expect.




Re: Error: need this for method of type

2019-10-23 Thread Dennis via Digitalmars-d-learn

On Wednesday, 23 October 2019 at 11:48:29 UTC, Dennis wrote:
You can change `method(1)` into `x.method(1)` and it should 
work.


Wait, but that's only because the local alias and member function 
have the same name 'method'.
I think you just have to keep the method name as a string instead 
of an alias and use ` __traits(getMember, x, member)(3);` the 
moment you want to call it.


Re: Error: need this for method of type

2019-10-23 Thread Dennis via Digitalmars-d-learn
On Wednesday, 23 October 2019 at 11:40:09 UTC, Márcio Martins 
wrote:
This is a bug, right? If not, why, and how can I get around it 
and call `method`?


An alias refers just to a symbol, in this case a member function 
of struct X.
The fact that you polled it on instance 'x' is not something an 
alias keeps track of.

You can change `method(1)` into `x.method(1)` and it should work.




Re: arsd errors on windows

2019-10-17 Thread Dennis via Digitalmars-d-learn

On Thursday, 17 October 2019 at 21:32:34 UTC, WhatMeWorry wrote:

DUB version 1.11.0, built on Oct  6 2018


`dub add` got added at the end of 2018 IIRC, so you need to 
upgrade Dub.


Re: arsd errors on windows

2019-10-17 Thread Dennis via Digitalmars-d-learn

On Thursday, 17 October 2019 at 20:17:53 UTC, Greatsam4sure wrote:

the same error


That was meant for Adam to put in the dub package file of arsd, 
in your project it won't affect the compilation of the 
dependency. (Though you can still try adding it in your local  
download of arsd to quickly get rid of the error)


Re: arsd errors on windows

2019-10-17 Thread Dennis via Digitalmars-d-learn

On Thursday, 17 October 2019 at 12:06:49 UTC, Dennis wrote:
You can put "buildRequirements": "allowWarnings" in your 
dub.json.


Should be
"buildRequirements": ["allowWarnings"]


Re: arsd errors on windows

2019-10-17 Thread Dennis via Digitalmars-d-learn

On Thursday, 17 October 2019 at 11:35:26 UTC, Adam D. Ruppe wrote:
ugh dub insists on this stupid warning as error nonsense and 
the warnings suck so they slip through me sometimes.


You can put "buildRequirements": "allowWarnings" in your dub.json.
(buildRequirements "allowWarnings" in dub.sdl)


Re: arsd errors on windows

2019-10-17 Thread Dennis via Digitalmars-d-learn

On Thursday, 17 October 2019 at 04:05:40 UTC, Greatsam4sure wrote:

what is the way out.


I made a pull request fixing it: 
https://github.com/adamdruppe/arsd/pull/222
In the mean time, you can add the subpackage 
"arsd-official:simpledisplay" as a depdendency instead so cgi.d 
won't be included (assuming you don't need it).


Re: std.algorithm.cmp doesn't seem to support numeric types?

2019-10-16 Thread Dennis via Digitalmars-d-learn
On Wednesday, 16 October 2019 at 20:07:10 UTC, Adam D. Ruppe 
wrote:
Notice that the docs say "a negative value" rather than -1 
specifically. That's because the implementation for integers an 
be as simple as


return a - b; // if b > a, you get a negative value


Except that e.g. -2 - int.max underflows to int.max suggesting 
that int.max < -2.


Re: Mixin and introspection ordering

2019-10-16 Thread Dennis via Digitalmars-d-learn
On Wednesday, 16 October 2019 at 10:09:51 UTC, Sebastiaan Koppe 
wrote:
Do we want to be able to catch things in their 'before' state? 
Or is it a bug?


The 'before' and 'after' are implementation details showing up as 
a result of underspecification.


Module level declarations are supposed to be order invariant. I 
weirdly can't find that directly in the spec, but it is implied 
in the world 'unlike' in this sentence:


"Unlike module level declarations, declarations within function 
scope are processed in order."

https://dlang.org/spec/function.html#nested

Now look at the specification of __traits(compiles):

"Returns a bool true if all of the arguments compile (are 
semantically correct)."

https://dlang.org/spec/traits.html#compiles

That isn't very clear; compile in what context? What is 
"semantically correct" at that point?

For example:
```
static if (__traits(compiles, sqrt(3))) {
import std.math: sqrt;
}
```
The reference implementation does not import sqrt here because in 
the context without the import it doesn't compile, but arguably 
importing sqrt is a valid resolution of the constraints here.


Another problem arises when evaluating the equivalent of "this 
statement is false":

if x doesn't compile, make x compile. Let's have two of them:
```
static if (!__traits(compiles, a)) {
   string a;
}
static if (!__traits(compiles, a)) {
   int a;
}
pragma(msg, typeof(a)); // int or string?
```

Either this is a contradiction, or __traits(compiles) should 
evaluate it in a "compilation state" before everything that 
depends on it. That implies there actually is an order of module 
level declarations.


Ideally, the D language formally specifies constraints for the 
validity of programs and any D compiler contains a correct 
constraint resolution algorithm for it. In practice DMD  has 3 
semantic passes for symbols and kind of recursively calls it on 
symbols on an as-needed basis without much rigor. Walter stated 
in his "Spelunking D compiler internals" talk [1] that the 3 
semantic passes were a mistake and an endless source of bugs. 
Small bugs with it are resolved  occasionally (for example [2]), 
but there are always more (for example [3] and [4]) and we need a 
good specification of semantic analysis before DMD can stop 
leaking its order of semantic analysis on symbols.


[1] https://www.youtube.com/watch?v=l_96Crl998E
[2] https://github.com/dlang/dmd/pull/9069
[3] https://issues.dlang.org/show_bug.cgi?id=9125
[4] https://issues.dlang.org/show_bug.cgi?id=19458


Re: selective tests

2019-10-12 Thread Dennis via Digitalmars-d-learn
On Saturday, 12 October 2019 at 09:52:59 UTC, Jonathan M Davis 
wrote:
You could set up your build so that you had targets which only 
compiled specific directories so that the only unit tests that 
were run were the ones in those directories, but I don't think 
that it's possible to do anything like that with dub. 
Certainly, if it is, it would be a royal pain to set up.


I think you can do it with sub packages:

dub.sdl
```
name "bread-and-butter"
description "the best thing since slided bread"
sourceFiles ""
dependency "bread-and-butter:bread"  version="*"
dependency "bread-and-butter:butter" version="*"

subPackage {
name "bread"
sourceFiles "source/bread/*.d"

}

subPackage {
name "butter"
sourcePaths "source/butter"
dependency "bread-and-butter:bread" version="*"
}
```

Then you can run tests like:

```
dub test bread-and-butter
dub test bread-and-butter:bread
dub test bread-and-butter:butter
```

An annoying thing about sub packages though is that you may have 
to duplicate lots of settings.
(hint hint 
https://forum.dlang.org/thread/fppszpfvbnvioeiak...@forum.dlang.org)


Re: Template mixin + operator overloading question

2019-10-11 Thread Dennis via Digitalmars-d-learn

On Friday, 11 October 2019 at 12:45:59 UTC, Boyan Lazov wrote:

Any ideas what I'm doing wrong?


Nothing, it's a bug.
https://issues.dlang.org/show_bug.cgi?id=19476



Have DUB sub packages inherit settings

2019-10-09 Thread Dennis via Digitalmars-d-learn
I want to split my package into sub packages for faster 
compilation, but I have some custom settings that I don't want to 
copy-paste 10 times since that makes editing them really 
annoying. Is there a way to inherit the settings from the 
main-package, or avoid repetition in another way?


I found this 2 years old post:
https://forum.dlang.org/post/wdkrsfjfbtnmpxcgu...@forum.dlang.org
It is mentioned that when using --combined the flags are 
inherited, but I also want to inherit the settings when not using 
that flag.


The settings in question are:
```
dflags "-dip1000" "-dip25"

buildType "debug" {
buildOptions "debugMode" "debugInfo"
buildOptions "betterC"
buildRequirements "allowWarnings"
}

buildType "release" {
buildOptions "releaseMode" "optimize" "inline"
buildOptions "betterC"
}

buildType "unittest" {
buildOptions "unittests" "debugMode" "debugInfo"
dflags "-checkaction=context"
buildRequirements "allowWarnings"
}
```



Re: How does D distnguish managed pointers from raw pointers?

2019-10-04 Thread Dennis via Digitalmars-d-learn

On Friday, 4 October 2019 at 18:53:30 UTC, H. S. Teoh wrote:
Here's an actual working example that illustrates the pitfall 
of this implicit conversion:


Luckily it's caught by -dip1000


Re: How does D distnguish managed pointers from raw pointers?

2019-10-04 Thread Dennis via Digitalmars-d-learn

On Friday, 4 October 2019 at 19:08:04 UTC, Adam D. Ruppe wrote:
(personally though I like to explicitly slice it all the time 
though, it is more clear and the habit is nice)


Turns out I have this habit as well. I'm looking through some of 
my code and see redundant slicing everywhere.


Re: How does D distnguish managed pointers from raw pointers?

2019-10-04 Thread Dennis via Digitalmars-d-learn

On Friday, 4 October 2019 at 18:43:34 UTC, H. S. Teoh wrote:
Actually, it *does* automatically convert the static array to a 
slice.


You're right, I'm confused. I recall there was a situation where 
you had to explicitly slice a static array, but I can't think of 
it now.


Re: How does D distnguish managed pointers from raw pointers?

2019-10-04 Thread Dennis via Digitalmars-d-learn

On Friday, 4 October 2019 at 18:30:17 UTC, IGotD- wrote:
What if you pass a static array to a function that expects a 
dynamic array. Will D automatically create a dynamic array from 
the static array?


No, you have to append [] to create a slice from the static array.


Re: Looking for a Simple Doubly Linked List Implementation

2019-09-21 Thread Dennis via Digitalmars-d-learn

On Saturday, 21 September 2019 at 08:34:09 UTC, Ron Tarrant wrote:
Thanks, Dennis. Not performant... It doesn't work? I was hoping 
for a complete, working example, but maybe this'll help.


Bad word choice (it appears it's debatable whether 'performant' 
even is a word), I meant it was a simple implementation not 
optimized for speed / memory efficiency.
Making it 'complete' is a bit hard since I can think of tens of 
methods and operator overloads you could use, but if I include 
them all it's no longer minimal and it just becomes 
std.container.dlist.


Does a doubly-linked list always have to be done with structs? 
Can it be classes instead?


My example originally included classes actually. It was mostly 
the same, except that Node!T* was just Node!T. The only problem 
was with const:


```
size_t length() const {
size_t result = 0;
for(auto a = head; a !is null; a = a.next) result++;
return result;
}

```

Since I marked the method as const, `auto a = head` got the type 
const(Node!T) and `a = a.next` no longer compiled. With structs 
you can declare a const(Node!T)* (mutable pointer to const node), 
but I don't know if I can declare a mutable reference to a const 
class, so I switched to structs.


Re: Looking for a Simple Doubly Linked List Implementation

2019-09-20 Thread Dennis via Digitalmars-d-learn

On Friday, 20 September 2019 at 20:26:03 UTC, Ron Tarrant wrote:
If someone could please post a minimal example (if there's 
extra stuff in there, I'll get confused; I'm getting that old, 
dammit) I'd be ever so grateful.


Below is a simple doubly linked list with Garbage Collected 
memory.
It's not performant or complete by any means, just a minimal 
example in D like you wanted.
You probably also want methods for removing nodes or inserting in 
the middle (else why don't you use an array?), I think you can 
think of an implementation for those yourself (or look them up, 
there should be plenty examples online).


If not, just ask again.

```

struct Node(T) {
private T value;
private Node!T* next = null;
private Node!T* previous = null;

this(T value) {
this.value = value;
}
}

struct DoublyLinkedList(T) {
Node!T* head = null;
Node!T* tail = null;

import std.range: isInputRange, ElementType;
this(R)(R initialList) if (isInputRange!R && is(ElementType!R 
: T)) {

foreach(elem; initialList) {
addLast(elem);
}
}

void addFirst(T value) {
auto n = new Node!T(value);
if (head !is null) {
head.previous = n;
} else {
tail = n;
}
n.next = head;
head = n;
}

void addLast(T value) {
if (head is null) {
addFirst(value);
} else {
auto n = new Node!T(value);
tail.next = n;
n.previous = tail;
tail = n;
}
}

size_t length() const {
size_t result = 0;
for(const(Node!T)* a = head; a !is null; a = a.next) 
result++;

return result;
}

T opIndex(size_t pos) const {
const(Node!T)* p = head;
for(; p !is null && pos-- != 0; p = p.next) {}
return p.value;
}
}

unittest {
auto a = DoublyLinkedList!int([10, 20, 30]);
assert(a[2] == 30);
assert(a.length == 3);
a.addFirst(-10);
a.addLast(100);
assert(a[0] == -10);
assert(a.tail.value == 100);
}
```



Re: Questions regarding a port (bindbc-cimgui)

2019-09-16 Thread Dennis via Digitalmars-d-learn

On Sunday, 15 September 2019 at 08:17:20 UTC, sytnax wrote:
So, the question is: should I share this somehow (despite the 
limitations listed below)?


Considering the circumstances you mentioned, I'd say either don't 
publish it or simply make it a public GitHub repository with 
these limitations stated in the readme. Considering there are 
already a derelict binding [1] and a port [2] for imgui out 
there, putting much work into making your code useful for others 
might not be worth it.


If you want to publish it on Dub (the D package manager, 
https://code.dlang.org), I'd encourage you to polish it up and 
test it so it's up to par with other bindbc packages and useful 
for others. However, it's not like Dub currently has a high 
standard (you can find lots of low-effort packages in there) and 
ultimately it's up to you to decide how / whether you share your 
code.



Would it be ok to share it (regarding licenses)?


Assuming you used this: https://github.com/0dyl/d-cimgui
It says "license": "MIT"
Which allows you to modify and redistribute as long as you keep 
the MIT license text in there.
The author of that repository didn't put an MIT license text in 
there, but considering it's a simple header translation I doubt 
you can get sued over it.

(usual IANAL applies)

[1] http://code.dlang.org/packages/derelict-imgui
[2] http://code.dlang.org/packages/dimgui


Re: Throwing from a lambda isn't supported by the compiler

2019-09-09 Thread Dennis via Digitalmars-d-learn

On Monday, 9 September 2019 at 13:22:22 UTC, Johannes Loher wrote:
This is incorrect. It was rejected because the proposal was not 
solid enough.


I put that a bit bluntly, but as far as I see it, the DIP focused 
too much on only adding a way to mark functions as 'no return' 
that people were like "if all you want to do is tell the compiler 
a function does not return, an attribute is sufficient. A new 
type is overkill.".
Add some discussion about the name TBottom and the fact that 
community feedback wasn't addressed and the DIP was deemed dead 
on arrival as Walter put it.



It just needs somebody to come up with a solid proposal.


I might give it a try actually.


Re: Throwing from a lambda isn't supported by the compiler

2019-09-09 Thread Dennis via Digitalmars-d-learn

On Monday, 9 September 2019 at 09:37:25 UTC, a11e99z wrote:
cuz throwing exception ever is not compatible with any return 
type so I dont see reasons do not allow such expressions


A throw statement can actually be seen as an expression returning 
a 'never' / 'bottom' type which is implicitly convertible to any 
return type. This is actually a really good example for the value 
of a bottom type as suggested in DIP1017:

https://github.com/dlang/DIPs/blob/master/DIPs/rejected/DIP1017.md

Such a shame it got rejected in favor of ugly 'no return' 
annotations, if only the DIP pointed out other use cases. Looking 
at the Formal Assessment section:
"He (Walter Bright) still thinks there is value in adding a 
bottom type to the language, but has decided to revisit the issue 
at a later date."


I hope a bottom type resolves this issue with throw statements in 
lambdas instead of another hack such as 'no return'.


Re: Quick question regarding dynamic array deletions

2019-09-01 Thread Dennis via Digitalmars-d-learn

On Sunday, 1 September 2019 at 18:26:20 UTC, WhatMeWorry wrote:
Maybe my question is when would be want to use 3) without also 
adjusting the .ptr ?


It matters when casting to a boolean, since an empty array with a 
non-null pointer is still `true` while an array with null pointer 
casts to `false`. This could be useful when you want to 
distinguish 'no array' and an empty array.


For example:
```
int[] getList(); // might fail

void main() {
  if (auto list = getList) {
writeln(list); // could be an empty list
  } else {
error("could not retrieve list"); // must be 'null' list
  }
}
```




Re: Linker errors to Windows functions

2019-08-20 Thread Dennis via Digitalmars-d-learn
On Tuesday, 20 August 2019 at 17:17:01 UTC, Vladimirs Nordholm 
wrote:
In code I have `import core.sys.windows.winuser;`, but still 
get this error.


Importing only specifies that you expect the symbols to be there, 
it doesn't mean the functions are linked in.


On Windows there are three targets, 32-bit OMF (old dmd default), 
32-bit MSCoff and 64-bit MSCoff (dub defaults to MSCoff since not 
too long ago). While DMD ships with import libraries for all 
targets, I never know which ones get linked in by default and 
which ones don't.


Usually when I get Windows linking errors I either switch the 
target (the OMF import libraries are sometimes lacking, so then I 
compile with --arch=x86_mscoff or --arch=x86_64) or explicitly 
link the import libraries.

Just quickly Google a function like GetSystemMetrics:
https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-getsystemmetrics
On the bottom it says "Library: User32.lib" so I add `pragma(lib, 
"User32.lib");` to my module using it.




Re: Speed of Random Numbers

2019-08-03 Thread Dennis via Digitalmars-d-learn
On Saturday, 3 August 2019 at 16:35:34 UTC, Giovanni Di Maria 
wrote:
Do you know other faster functions or methods to generate 
random numbers?


For me the "goodness of random" is NOT important.


I found some nice random functions in this public-domain C 
single-header library collection, one of which is GameRand:


https://github.com/mattiasgustavsson/libs/blob/022370a79cf2d5f87fb43b420834a069adb5fede/rnd.h#L449

Here's the D version:
```
struct GameRand
{
uint[2] state;
}

uint randomGameRand(ref GameRand gamerand) {
gamerand.state[0] = ( gamerand.state[0] << 16 ) + ( 
gamerand.state[0] >> 16 );

gamerand.state[0] += gamerand.state[1];
gamerand.state[1] += gamerand.state[0];
return gamerand.state[0];
}
```

It's really fast and decent enough for games (hence the name I 
suppose). See:

http://www.flipcode.com/archives/07-15-2002.shtml


Re: Can one customize unit tests?

2019-08-03 Thread Dennis via Digitalmars-d-learn
The out-of-the box unittest runner is pretty bare by design. It 
just runs unittest blocks in serial as functions where assert() 
failures are not undefined behavior. Assert messages are not very 
helpful, though the recently added flag `-checkaction=context` 
helps a lot.


Luckily there is a trait for getting unittests:
https://dlang.org/spec/traits.html#getUnitTests

So it is possible to make your own unittest runner, as people 
have done:

http://code.dlang.org/packages/silly
http://code.dlang.org/packages/unit-threaded
http://code.dlang.org/packages/dunit

On Saturday, 3 August 2019 at 13:31:02 UTC, PV wrote:
Is it possible to somehow customize syntax and running of unit 
tests?


You can add @("attributes") to your unittests.
The default test-runner will not do anything with them currently, 
but your own test runner can.


I'd looked into the documentation, found nothing, but perhaps I 
just missed it. If it is not possible, is it realistic to (very 
easily) hack the D compiler to implement such feature?


Shouldn't be necessary, I think what you want can be done with 
attributes and your own test runner.



Would such feature also work in betterC?


unittest blocks itself are supported in betterC, so you can 
probably make it work.





Re: accuracy of floating point calculations: d vs cpp

2019-07-22 Thread Dennis via Digitalmars-d-learn

On Monday, 22 July 2019 at 12:49:24 UTC, drug wrote:
Before I start investigating I would like to ask if this issue 
(different results of floating points calculation for D and 
C++) is well known?


This likely has little to do with the language, and more with the 
implementation. Basic floating point operations at the same 
precision should give the same results. There can be differences 
in float printing (see [1]) and math functions (sqrt, cos, pow 
etc.) however.


Tips for getting consistent results between C/C++ and D:
- Use the same backend, so compare DMD with DMC, LDC with CLANG 
and GDC with GCC.
- Use the same C runtime library. On Unix glibc will likely be 
the default, on Windows you likely use snn.lib, libcmt.lib or 
msvcrt.dll.

- On the D side, use core.stdc.math instead of std.math
- Use the same optimizations. (Don't use -ffast-math for C)

[1] 
https://forum.dlang.org/post/fndyoiawueefqoeob...@forum.dlang.org


Re: Quotes inside wysiwyg strings, or alternative solution?

2019-07-18 Thread Dennis via Digitalmars-d-learn

On Thursday, 18 July 2019 at 11:38:55 UTC, Paul wrote:
What is the solution in D for wysiwyg strings (or similar) 
spanning multiple lines containing quotes and apostrophes?


Take a look at:
https://dlang.org/spec/lex.html#string_literals

All string literals may span multiple lines.

If you only need " and ' without `, you can use a string literal 
like this: `WysiwygCharacters`


For ' and ` in your string you can use r"WysiwygCharacters".

You can also concatenate different string literals with ~.

If your string contains code, you can try a token string like 
q{if 'a' "" ``}


Finally, you can also have custom delimiters in q-strings but I 
don't recommend them since they're hard to process for text 
editors. (Details are in the spec)



(also, how can I put formatted code in a post?)


Often requested, but you can't.


  1   2   3   >