Re: The effect of ref

2019-11-21 Thread ketmar via Digitalmars-d-learn

Adam D. Ruppe wrote:


On Friday, 22 November 2019 at 03:42:26 UTC, dokutoku wrote:
Is there a difference in the execution speed and stability when 
executing the program by rewriting the parameter of the function 
argument like this?


the generated code the processor sees is generally identical, but the 
`ref` version is potentially better because then X cannot possibly be 
`null` which can help you write better code and might help the optimizer 
too.


still, using explicit pointers may be good for readability.

int a;
foo(a); // does it chage `a`?
boo(); // oh, yeah, now i see that it will prolly change `a`

unsafe coding style, but for me pointers for `ref` are more readable.


Re: -O flag ; automatic cast in a bitshift

2018-09-20 Thread ketmar via Digitalmars-d-learn

Guillaume Lathoud wrote:

this is UB. by the specs, values are promoted to int, and shifting int by 
50 is UB. so both results are nonsense.


Re: float/double to string (pure nothrow @nogc)

2018-08-08 Thread ketmar via Digitalmars-d-learn

vit wrote:


thanks, that code can be modified to pure nothrow @nogc @safe.
Is that lib ok? Is little complicated...


converting float to string is a *very* complicated task. that lib is quite 
small for what it is doing ('cause it hacks around some... interesting 
cases). the *real* thing will be a LOT bigger.


Re: float/double to string (pure nothrow @nogc)

2018-08-08 Thread ketmar via Digitalmars-d-learn

vit wrote:

Hello, is in phobos some function which convert float/double to string 
and is pure @nogc and nothrow?


i don't think that you can make it `pure`, but you certainly can make it 
`nothrow`, `@nogc` and ctfe-able. it's dangerous to go alone! take this[0].



[0] http://repo.or.cz/iv.d.git/blob_plain/HEAD:/ctfefloat.d


Re: @safe - why does this compile?

2018-07-16 Thread ketmar via Digitalmars-d-learn

Johan Engelen wrote:


On Friday, 13 July 2018 at 14:51:17 UTC, ketmar wrote:


yeah. in simple words: safe code is *predictable*, but not 
"segfault-less". segfaults (null dereferences) in safe code are allowed, 
'cause they have completely predictable behavior (instant program 
termination).


@safe doesn't free you from doing your null checks, it protects you from 
so-called "undefined behavior" (aka "unpredictable execution results"). 
so when we are talking about "memory safety", it doesn't mean that your 
code cannot segfault, it means that your code won't corrupt random 
memory due to misbehaving.


This is not true when using LDC (and I'd expect the same for GDC).
With LDC, dereferencing `null` is undefined behavior regardless of 
whether you are in an @safe context or not.


- Johan


p.s.: it worth noting that *program* *state* is undefined after null 
dereference, though. i.e. program cannot continue execution, and must be 
aborted. in this sense, null dereferencing is defined behavior: it aborts 
the app unconditionally. and if you will catch segfault with some OS 
mechanics, you still cannot reliably do *anything* except immediately 
aborting (strictly speaking, this is true for any `Error` condition, even 
for asserts).


so compiler *can* assume that null dereferencing is something code 
generally won't do, but it cannot do any optimisations assuming that code 
will not dereference nulls at all (dmd -O, afair, was guilty of some such 
optimisations too).


so, code can dereference null, and it will be immediately aborted, without 
any chance to perform cleanup (as program state is undefined after this 
operation). in this sense, null dereferencing is "defined behavior".


Re: @safe - why does this compile?

2018-07-16 Thread ketmar via Digitalmars-d-learn

Johan Engelen wrote:


On Friday, 13 July 2018 at 14:51:17 UTC, ketmar wrote:


yeah. in simple words: safe code is *predictable*, but not 
"segfault-less". segfaults (null dereferences) in safe code are allowed, 
'cause they have completely predictable behavior (instant program 
termination).


@safe doesn't free you from doing your null checks, it protects you from 
so-called "undefined behavior" (aka "unpredictable execution results"). 
so when we are talking about "memory safety", it doesn't mean that your 
code cannot segfault, it means that your code won't corrupt random 
memory due to misbehaving.


This is not true when using LDC (and I'd expect the same for GDC).
With LDC, dereferencing `null` is undefined behavior regardless of 
whether you are in an @safe context or not.


- Johan


then those compilers are broken, and should be fixed.


Re: @safe - why does this compile?

2018-07-13 Thread ketmar via Digitalmars-d-learn

Steven Schveighoffer wrote:


To emphasize the point, this is @safe as well:

X2 x2; // = null
x2.run();

D does not consider a segmentation fault due to null dereferencing to be 
unsafe -- no memory corruption happens.


yeah. in simple words: safe code is *predictable*, but not "segfault-less". 
segfaults (null dereferences) in safe code are allowed, 'cause they have 
completely predictable behavior (instant program termination).


@safe doesn't free you from doing your null checks, it protects you from 
so-called "undefined behavior" (aka "unpredictable execution results"). so 
when we are talking about "memory safety", it doesn't mean that your code 
cannot segfault, it means that your code won't corrupt random memory due to 
misbehaving.


Re: @safe - why does this compile?

2018-07-13 Thread ketmar via Digitalmars-d-learn

Piotr Mitana wrote:


This code:

 import std.stdio;

 class X1 {}
 class X2 : X1
 {
void run() @safe
 {
 writeln("DONE");
 }
 }

 void main() @safe
 {
 X1 x1 = new X1;
 X2 x2 = cast(X2) x1;
 x2.run();
 }

is obviously wrong gets killed by OS's signal. Why is it @safe? I thought 
@safe should prevent such errors as well.


there is nothing wrong here. dereferencing null reference is completely 
safe (in terms of result predictability).


Re: Debugging silent exit of threads in Phobos calls

2018-06-01 Thread ketmar via Digitalmars-d-learn

Steven Schveighoffer wrote:

Can you put in some more debug messages and see what the exact types of A 
and T are? Just put it right before the assert.


you prolly asked Russel here, as i don't have his sources to experiment 
with. ;-)


Re: Debugging silent exit of threads in Phobos calls

2018-06-01 Thread ketmar via Digitalmars-d-learn

Russel Winder wrote:


On Fri, 2018-06-01 at 17:53 +0300, ketmar via Digitalmars-d-learn
wrote:



[…]

it looks like "// type T is not constructible from A" phobos
assertion triggered. that is, std.variant cannot wrap the struct, and 
all hell

breaks loose.


An instance of FrontendAppeared is created in frontend_manager module
and sent to the actor defined in control_window module which has:

import frontend_manager: FrontendAppeared

It seems the symbol FrontendAppeared in control_window is matching the
FrontendAppeared type of the message sent, and yet the assertion fails.


it may be something with struct copying. variant wants to copy a struct 
into itself, and somehow failed. either there is no room, or something 
prevented it to do that. it is hard to say more without full source code.


Re: Debugging silent exit of threads in Phobos calls

2018-06-01 Thread ketmar via Digitalmars-d-learn

Russel Winder wrote:


On Fri, 2018-06-01 at 16:37 +0300, ketmar via Digitalmars-d-learn
wrote:



[…]

yeah. if it receives something it doesn't expect (and there is no
`Variant` clause to catch it), it throws. and exceptions from threads are
silently dropped on the floor -- along with the dead threads. so it is 
better

to always wrap your threads in `try/catch`, and at least log an
exception.


It seems that in the case he presence of the Variant doesn't matter.

The message sent is of type frontend_manager.FrontendAppeared and one
of the receive types is frontend_manager.FrontendAppreared yet this
fails to match but it is not treated as a Variant. 


The stack trace is:


it looks like "// type T is not constructible from A" phobos assertion 
triggered. that is, std.variant cannot wrap the struct, and all hell breaks 
loose.


Re: Debugging silent exit of threads in Phobos calls

2018-06-01 Thread ketmar via Digitalmars-d-learn

Steven Schveighoffer wrote:


On 6/1/18 7:12 AM, Russel Winder wrote:

So I had a play and gdb seems to be useless for trying to find out why
calls to std.concurrency.receive exit silently.
Obviously std.concurrency.receive should never terminate a thread, and
it should never terminate a thread silently, but given that it clearly
does (using dmd 2.080 from d-apt on Debian Sid) how is one to find out
useful information as to why it is exiting silently.


I remember something like a receive thread that throws terminates 
silently. Do a try/catch to see if it's that.


-Steve


yeah. if it receives something it doesn't expect (and there is no `Variant` 
clause to catch it), it throws. and exceptions from threads are silently 
dropped on the floor -- along with the dead threads. so it is better to 
always wrap your threads in `try/catch`, and at least log an exception.


Re: Compile-time variables

2018-04-05 Thread ketmar via Digitalmars-d-learn

Kayomn wrote:


I'll give a better example of what it is I'm trying to do.

These are node types. Their contents are not important in this 
explanation, only that they operate as a tree structure.


class Node;

class RootNode : Node;

class SpriteNode : Node;

The result of getNodeID on a specific type is always the same. A value 
representing it that is applied during compilation. The value does not 
matter to the programmer, only that it is unique and gets applied.


--
uint nodeId1 = getNodeID!(Node)(); // 0.

uint nodeId2 = getNodeID!(SpriteNode)(); // 1.

uint comparison = getNodeID!(Node)(); // 0.

// True.
if (getNodeID!(Node)() == getNodeID!(Node)()) {

}

// False.
if (getNodeID!(SpriteNode)() == getNodeID!(Node)()) {

}
--


it is already done for you, free of charge.

class Node {}
class RootNode : Node {}
class SpriteNode : Node {}

void main () {
auto nodeId1 = typeid(Node);
auto nodeId2 = typeid(SpriteNode);
auto comparison = typeid(Node);

Node n = new SpriteNode();

assert(typeid(Node) is typeid(Node)); // obviously
assert(typeid(SpriteNode) !is typeid(Node)); // sure
assert(typeid(Node) is nodeId1);
assert(typeid(n) is nodeId2);
}


Re: Initializing a class member that is an object

2018-03-30 Thread ketmar via Digitalmars-d-learn

Laurent Tréguier wrote:


On Friday, 30 March 2018 at 11:04:59 UTC, ketmar wrote:
p.s.: still, it may be nice to warn user about that. 'cause such runtime 
initializations are really belong to static ctor. dunno, i'm ok both 
with warning and without it.


I simply think a word about it in the docs would be nice, since this is 
tricky if you come from another language that doesn't do this. Otherwise 
I'm fine with it (and it's not exactly hard to fix either)


please, make an ER in bugzilla then. 'cause it will be lost here, and with 
ER we have a chance to eventually do that.


Re: Initializing a class member that is an object

2018-03-30 Thread ketmar via Digitalmars-d-learn
p.s.: still, it may be nice to warn user about that. 'cause such runtime 
initializations are really belong to static ctor. dunno, i'm ok both with 
warning and without it.


Re: Initializing a class member that is an object

2018-03-30 Thread ketmar via Digitalmars-d-learn

Laurent Tréguier wrote:


Is this behavior really intentional ?
yes. default values should be the same for all objects. it is predictable, 
and allows to initialize objects to the known state simply by blitting 
`.init`.


that is, default values aren't a syntax sugar for defining implicit ctor 
actions, they are executed once. this is by design.


Re: #import mapi.h

2018-03-21 Thread ketmar via Digitalmars-d-learn

Martin Tschierschke wrote:


or tutorial


ok, tutorial:

1. learn C.
2. learn D.
3. DO IT!

;-)


Re: signbit question

2018-03-15 Thread ketmar via Digitalmars-d-learn

Miguel L wrote:


as the calculations on f guarantee it cannot be 0 at all.


than `f` will become zero very soon. something that "cannot happen" is the 
most probable thing to happen.


otherwise, LGTM.


Re: how to make private class member private

2018-03-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


Whatever happened to the 'discussion' component of these 'discussions'?


dunno. try to ask yourself, why repeating the same point again and again 
when you were given the answer and the rationale doesn't make a good 
discussion.


Re: how to make private class member private

2018-03-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


On Tuesday, 13 March 2018 at 06:25:39 UTC, ketmar wrote:

psychoticRabbit wrote:


So the 3 most used languages got it wrong??


yes.


do you know any other language, where a private class memeber, is not 
private to the class?


(btw. that's a question, not a statement).


that is, we should stick to defective design only 'cause there is no "other 
D" that made it right? ;-)


also, your question is not valid. you were told several times that you're 
evaluating the whole thing wrong, but you're insisting on your view being 
right. and you're keep asking, omiting the *critical* piece of the picture: 
modules. you were told that in D, encapsulation unit is *module*, not 
class/struct. it is not a "misdesign", it is the proper modular design. it 
doesn't matter what others are doing in this case.


p.s.: yes, i know such language. Delphi/FreePascal.


Re: how to make private class member private

2018-03-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


So the 3 most used languages got it wrong??


yes.


Re: how to make private class member private

2018-03-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


On Tuesday, 13 March 2018 at 05:52:55 UTC, ketmar wrote:

psychoticRabbit wrote:


There are two problems I see:

1) it is not how C++ done it.
2) it is not how C++ done it.

and you're completely right: it is not how C++ done it.


umm...didn't you forget something:

1) it is not how C# done it.
2) it is not how C# done it.

1) it is not how Java done it.
2) it is not how Java done it.


ah, yes, sorry: i completely forgot that C++ was invented after c# and 
java. mea maxima culpa!


Re: how to make private class member private

2018-03-12 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


There are two problems I see:

1) it is not how C++ done it.
2) it is not how C++ done it.

and you're completely right: it is not how C++ done it.


Re: how to make private class member private

2018-03-12 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


On Tuesday, 13 March 2018 at 01:39:13 UTC, Jonathan M Davis wrote:


private is private to the module, not the class. There is no way in D to 
restrict the rest of the module from accessing the members of a class. 
This simplification makes it so that stuff like C++'s friend are 
unnecessary. If your class in a separate module from main, then main 
won't be able to access its private members.


- Jonathan M Davis


Mmm.. I don't think I like it.

I feel you should be able to make a member of a class, private, 
regardless of where the class is located. This seems to break the concept 
of class encapsulation.


No. I don't like it at all.


just stop thinking in C/C++ "#include" terms. there, you have no other ways 
to restrict data access, so they were forced to make it broken, and then 
introduce "friends" just to workaround the fact that there are no modules 
in C++.


instead, start thinking with modules in mind. module is THE unit of 
incapsulation. there is nothing wrong in isolating class or two in a 
module. then, to make imports manageable, either create a package of that, 
or just a dummy module that does `public import xxx;` for everything.


Re: docs/definition: !object

2018-03-07 Thread ketmar via Digitalmars-d-learn

Nick Sabalausky (Abscissa) wrote:

(Or does  return the address of the *reference* to the object 
rather than the address of the object?...You can see just how often I do 
OO in D ;) )


exactly. if you want to convert object to a pointer safely, do this:

MyObject o;
void* p = *cast(void**)

this magic construct guarantees that you won't hit `opCast()` in 
`MyObject` (yes, somebody *can* write weird `opCast` for `void*`! ;-).


doing just `` gives you the address of a variable (on a stack, or in a 
tls), which is, obviously, never `null`. ;-)


Re: docs/definition: !object

2018-03-07 Thread ketmar via Digitalmars-d-learn

Nick Sabalausky (Abscissa) wrote:

I'm having trouble finding the documentation for what exactly the unary 
"not" operator does when applied to a class/interface object. Does this 
documentation exist somewhere?


I know at least part of it involves "is null", but I seem to remember 
hearing there was more to it than just that.


https://dlang.org/spec/operatoroverloading.html#boolean_operators

"Class references are converted to bool by checking to see if the class reference is 
null or not."


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

Matt Gamble wrote:

Ok, this has been submitted as a bug. 
https://issues.dlang.org/show_bug.cgi?id=18573


thank you.


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

Matt Gamble wrote:


On Wednesday, 7 March 2018 at 21:02:30 UTC, ag0aep6g wrote:

On 03/07/2018 09:09 PM, ag0aep6g wrote:


double f() { return 1; }
void main()
{
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
    double b = 2;
     assert(b == 2); /* fails; should pass */
}



With `real` instead of `double` x86_64 is also affected.


Wow. Good to know I'm not crazy. I was afk for a bit, sorry. I guess I'm 
glad I found it and posted. The conversation has gone beyond my realm of 
understanding. Has anyone tested on 2.079 like Ali wanted. I have not had 
a chance to install. I was going to wait to post the bug till that was 
tried.


sure, it is still there in git HEAD. it is not the bug that can be fixed 
"accidentally". %-)


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

ag0aep6g wrote:


On 03/07/2018 09:09 PM, ag0aep6g wrote:


double f() { return 1; }
void main()
{
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
     cast(void) f();
    double b = 2;
     assert(b == 2); /* fails; should pass */
}



With `real` instead of `double` x86_64 is also affected.


yeah. that is 'cause SSE cannot do math with 80-bit floats, and compiler 
falls back to FPU in this case.


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

H. S. Teoh wrote:

On Wed, Mar 07, 2018 at 10:21:42PM +0200, ketmar via Digitalmars-d-learn 
wrote:

[...]

it looks like ignoring `double` result causes FPU stack imbalance
('cause compiler doesn't insert "FPU pop" instruction), and that
affects the computations.
on 64 bit it doesn't matter, 'cause no FPU is used there.
the fix prolly should be easy: just emit "FPU pop" if function result
is ignored. codegen should have this info at hand, i believe.


Nice catch!  Is there a bug filed for this yet?  If not, it should be.


btw, this is specific to `cast(void)`. if you'll remove the cast, or do 
something like `cast(void)(pred(i)+42);`, the bug won't be there. so it 
looks like it is not a codegen bug after all, but glue layer. the codegen 
is correctly dropping the result without `cast(void)` (`fstp   %st(0)` is 
inserted in `main`), but cannot do that if return type information is stripped.


so it looks that glue layer should not strip return type info.


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

H. S. Teoh wrote:

On Wed, Mar 07, 2018 at 10:21:42PM +0200, ketmar via Digitalmars-d-learn 
wrote:

[...]

it looks like ignoring `double` result causes FPU stack imbalance
('cause compiler doesn't insert "FPU pop" instruction), and that
affects the computations.
on 64 bit it doesn't matter, 'cause no FPU is used there.
the fix prolly should be easy: just emit "FPU pop" if function result
is ignored. codegen should have this info at hand, i believe.


Nice catch!  Is there a bug filed for this yet?  If not, it should be.


it seems that no bug is filled yet. feel free to do so. ;-) or maybe OP 
should better do it, dunno. definitely not me. ;-)


Re: issue with each specifically for x86

2018-03-07 Thread ketmar via Digitalmars-d-learn

Steven Schveighoffer wrote:

it seems that the only difference between `void` and `double` lambda is one 
asm instruction: `fldl   (%edi)`. it is presend in `double` labmda, and 
absent in `void` lambda.


it looks like ignoring `double` result causes FPU stack imbalance ('cause 
compiler doesn't insert "FPU pop" instruction), and that affects the computations.


on 64 bit it doesn't matter, 'cause no FPU is used there.

the fix prolly should be easy: just emit "FPU pop" if function result is 
ignored. codegen should have this info at hand, i believe.


Re: Aliasing member's members

2018-02-26 Thread ketmar via Digitalmars-d-learn

Kayomn wrote:


On Monday, 26 February 2018 at 21:04:51 UTC, TheFlyingFiddle wrote:

On Monday, 26 February 2018 at 20:50:35 UTC, Kayomn wrote:

[...]


Don't think you can alias member variables directly.

You could do this though:

struct Player {
Entity entity;

ref auto pos() inout { return entity.position; }
}

Which will give you most of what you want. Although if you want to take 
the address of pos you have to use


auto addr = ();


Damn, was hoping to keep my structs as plain old data-structures. Thanks 
for the info, guess I won't be doing this then.


write `pos` as free function then, and use UFCS. there is no real 
difference. ;-)


Re: Forward references

2018-02-25 Thread ketmar via Digitalmars-d-learn

works for me with 2.076.


Re: Destructor called twice.

2018-02-25 Thread ketmar via Digitalmars-d-learn

add postblit debug prints, and you will see.


Re: Function overloading between modules

2018-02-22 Thread ketmar via Digitalmars-d-learn

JN wrote:


same idea?


absolutely the same. non-qualified imports (be it template, or function) 
won't take part in overload resoultion.


Re: Function overloading between modules

2018-02-22 Thread ketmar via Digitalmars-d-learn

JN wrote:


Is this expected behaviour?

bar.d
---
void foo(string s)
{
}


app.d
---

import std.stdio;
import bar;

void foo(int x)
{
}

void main()
{
   foo("hi");
};


===
Error: function app.foo (int x) is not callable using argument types 
(string)


yes. this is done so unqualified won't silently "steal" your functions. 
this can cause some unexpected (and hard to find) bugs.


if you want it to work, you can either do qualified import

import bar : foo;

or manuall bring overloads from `bar` with

alias foo = bar.foo;


Re: Tuts/Aritcles: Incrementasl C++-to-D conversion?

2018-02-22 Thread ketmar via Digitalmars-d-learn

Nick Sabalausky (Abscissa) wrote:

Are there any tutorials or articles out there for "getting started with 
converting a C++ codebase to D one module at a time?" Or at the very 
least: tips, tricks, lessions learned, from those who have come before.


from my experience (various codebases up to middle size, mostly C, some 
C++): fsck the "one module at a time" idea! even in D modules are 
interwined, and in C and C++ they're even more so. besides, converting 
tests is tedious, it is much funnier to have something working.


so, i'm usually converting alot of code, up to the whole codebase. it is 
not fun when compler spits 100500 errors, but when it finally stops... oh, 
joy!


trick: use 'sed' (or your favorite regexp search-and-replace tool) alot. 
basically, before HDD crash i almost had a set of scripts that does 80-90 
percents of work translating C to D with sed. ;-) then use editor with 
"jump to error line" support, and simply compile your code, fixing errors 
one by one.


tip: try to not rewrite code in any way until it works. i know how tempting 
it to replace "just this tiny thing, it is so ugly, and in D we have a nice 
idiom!" NEVAR. this is by far the most important thing to remember (at 
least for me), so i'll repeat it again: no code modifications until it works!


personal memories: C code often using things like `a == [idx]`, where 
idx can go just past the last array element. it got me when i was doing 
enet conversion. nasty trick.


otherwise, sweat and blood, and patience.


Re: Destructing Struct

2018-02-21 Thread ketmar via Digitalmars-d-learn

Jiyan wrote:


Hi :),

What i thought was that when i create a struct dynamically i can just 
deconstruct it with __dtor lets say:


struct U {...}
struct S {... private U _member;}

S* p;
p = cast(S*)malloc(S.sizeof);

// just run that if it compiles, for simplicity
// we dont use __traits(compiles, ...)
p.__dtor;

The thing here is that this doesn't work because of when S has an element 
that that is private and has a __dtor itself, the __dtor from U doesnt 
get called before the call of __dtor from S - or after.


Is there any way with traits or sth to do that?

Are delete, destroy or any other functions the standard library working 
here?
I would prefer a solution that can be build by myself - so without the 
standard library for example with traits.


Thanks :)


`p.destroy` will call the dtors for you. you'd better not use `__`-frefixed 
symbols yourself, as they aren't actually a part of a language, they're just

implementation details.


Re: C++ std::string_view equivalent in D?

2018-02-21 Thread ketmar via Digitalmars-d-learn

0x wrote:


On Wednesday, 21 February 2018 at 09:21:58 UTC, 0x wrote:
What is the equivalent of C++17 std::string_view (an object that can 
refer to a constant contiguous sequence of char-like objects with the 
first element of the sequence at position zero) in D?


PS: I'm getting back to D after years (since DMD 1 days). A lot changes 
since v1.0.


Wow! Thanks guys.
Those are handy, but I specifically want to do something like:

```
string_view sv = "some string";
```
So I can query it's size, make it point to sth else, use it in callbacks 
etc. Of course I'm aware of scoping etc...


I'm NOT doing any dynamic allocations, I just want a situation where a 
string allocation string would be a little bit expensive.


and that is exactly what slices are for! ;-)

you are probably better to use `const(char)[]`, tho. like this:

// don't store `s`, as it's contents may change after exiting of 
`myfunc`
// (this is what `const` implies here)
void myfunc (const(char)[] s) { ... }

...
string s = "test string";
myfunc(s); // yep, this works
s = s[2..4]; // this doesn't allocate
myfunc(s);
myfunc(s[3..6]); // or this, it doesn't allocate
myfunc("abc"); // or this, doesn't allocate

you got the idea.


Re: How to make AA key a pointer

2018-02-19 Thread ketmar via Digitalmars-d-learn

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?


there is absolutely no reason to copy `string` ever, as it is `immutable`. 
and compiler knows that. anyway, why don't you just check it by writing the 
code first?


import std.stdio;
void main () {
int[string] a;
string s = "test";
writefln("%08x", s.ptr);
a[s] = 666;
s = "test1";
writefln("%08x", s.ptr);
a[s] = 42;
foreach (string k; a.byKey) writefln("%08x", k.ptr);
}


Re: ubyte[4] to int

2018-02-15 Thread ketmar via Digitalmars-d-learn

Nicholas Wilson wrote:


On Thursday, 15 February 2018 at 16:51:05 UTC, Kyle wrote:
Hi. Is there a convenient way to convert a ubyte[4] into a signed int? 
I'm having trouble handling the static arrays returned by 
std.bitmanip.nativeToLittleEndian. Is there some magic sauce to make the 
static arrays into input ranges or something? As a side note, I'm used 
to using D on Linux and DMD's error messages on Windows are comparably 
terrible. Thanks!


you mean you want to convert the bitpattern represented by the uint[4] to 
an int?


You want a reinterpret style case

ubyte[4] foo = ...;
int baz = *cast(int*)


better to use `[0]`, this way it will work with slices too.


Re: import strangeness with std.stdio.write

2018-02-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:

Also, if I do this below, how does the compiler choose the correct write 
function?


import std.stdio;
import std.file;

void main()
{
 write("hello");
 writeln("hello again");
}


it's easy: just take a look at `std.file.write()`. first, it require two 
arguments. this is enough to rule `stf.file.write()` out in your case.


Re: import strangeness with std.stdio.write

2018-02-13 Thread ketmar via Digitalmars-d-learn

psychoticRabbit wrote:


So, strange problem below.

The commented-out line will not compile (if I un-comment it), unless I 
either move std.stdio into main, or, move std.file out of main.


Whereas writeln works just fine as is.

-
module test;

import std.stdio;

void main()
{
 import std.file;

 //write("hello");
 writeln("hello again");
}
---


`std.file` has function named `write()` too. and local import completely 
shadows global imports (i.e. it removes global imports from overload set 
for the given scope), hence `std.stdio.write()` is not available there.


this is done by purpose, so your code won't accidentally use wrong 
function. you can bring `std.stdio` functions back by adding local `import 
std.stdio;`, for example.


Re: inout question

2018-02-12 Thread ketmar via Digitalmars-d-learn

lobo wrote:

sure, i meant that you have to modify the second parameter accordingly. ;-) 
anyway, it's good that you fixed it.


Re: inout question

2018-02-11 Thread ketmar via Digitalmars-d-learn

Norm wrote:


Hi,

I'm new to D so can someone explain to me what is happening here?


void func(const char* s, char** e) {
 import core.stdc.stdlib;
 auto result = strtod(s, e);
}

Error: function core.stdc.stdlib.strtod (scope inout(char)* nptr, scope 
inout(char)** endptr) is not callable using argument types (const(char*), 
char**)


there is a difference between `const char* s`, and `const(char)* s`.
the former means that both `s` and `*s` cannot change, the latter means 
that `s` can be changed, but `*s` cannot. i.e. the first form means that 
you cannot do pointer arithmetic with `s`, while with second form you can 
(only *contents* are const, not the pointer itself).


that is, `strtod` wants const *contents*, but not pointer. `const(char)* s`.


Re: -transition=safe and DIP1000

2018-01-21 Thread ketmar via Digitalmars-d-learn

Mike Franklin wrote:


And what does "NB" mean?

"nota bene". used as "pay attention to the following".


Re: why ushort alias casted to int?

2017-12-22 Thread ketmar via Digitalmars-d-learn

crimaniak wrote:

Both operands are the same type, so as I understand casting to longest 
type is not needed at all, and longest type here is ushort in any case. 
What am I doing wrong?


it is hidden in specs: all types shorter than int are promoted to int 
before doing any math.


Re: Scope failure is not preventing application crush in case of uncaught exceptions

2017-12-16 Thread ketmar via Digitalmars-d-learn

kerdemdemir wrote:


On Saturday, 16 December 2017 at 20:56:26 UTC, ketmar wrote:

kerdemdemir wrote:


As far as I know scope(failure) should be collecting all failure cases.


nope. `failure` scope won't stop exception propagation, it is just 
called before exception leaves your function, to give you a last chance 
to do some immediate cleanup.


Than do I still need to catch'em all? For me it doesn't matter the which 
exception it is. It is more important for me to not pollute my code with 
so many exception related lines. What is the most compact way for me to 
catch'em all?


see collectException[0], for example. something like (WARNING! DON'T DO 
THIS! it's not wise to silence everything! try to be selective with 
`collectException!RequiredExceptionType` instead!)


collectException(() {
your code here
}());

or just move your code to some function, and do

collectException(myfunction);


[0] http://dpldocs.info/experimental-docs/std.exception.collectException.2.html


Re: Scope failure is not preventing application crush in case of uncaught exceptions

2017-12-16 Thread ketmar via Digitalmars-d-learn

kerdemdemir wrote:


As far as I know scope(failure) should be collecting all failure cases.


nope. `failure` scope won't stop exception propagation, it is just called 
before exception leaves your function, to give you a last chance to do some 
immediate cleanup.


Re: lower case only first letter of word

2017-12-05 Thread ketmar via Digitalmars-d-learn

Marc wrote:

Does D have a native function to capitalize only the first letter of the 
word? (I'm asking that so I might avoid reinvent the wheel, which I did 
sometimes in D)


http://dpldocs.info/experimental-docs/std.string.capitalize.html
http://dpldocs.info/experimental-docs/std.uni.asCapitalized.html

searching rox!

p.s.: but beware, it will lowercase all the letters except the first one, 
so it may not be exactly the thing you aksed for.


Re: git workflow for D

2017-12-03 Thread ketmar via Digitalmars-d-learn

Basile B. wrote:


On Sunday, 3 December 2017 at 22:22:47 UTC, Arun Chandrasekaran wrote:
Git CLI is arcane and esoteric. I've lost my commits before (yeah, my 
mistake).


Who hasn't ;)

me.

Happened to me last time because i tried a command supposed to remove 
untracked files in submodules...but used "reset" in a wrong way... ouch.
"git reflog". nothing commited is *ever* lost until you do "git gc". git 
sometimes does GC on its own, so you can turn it off with:


git config --global gc.auto 0

don't forget to manually GC your repo then with "git gc", or it may grow 
quite huge.


Re: How to modify process environment variables

2017-10-16 Thread ketmar via Digitalmars-d-learn

Ky-Anh Huynh wrote:


Hi,

Is it possible to change the current process's environment variables?

I have looked at `std/process.d` source code, and there is only a private 
method `createEnv` used when new (sub)process is created.


In C `putEnv` the answer is positive: 
http://man7.org/linux/man-pages/man3/putenv.3.html (FIXME)


I come to this question as I want to set some custom variables for my 
unittests. My program reads some tokens from system environments, and 
it's convenient if I can simulate different cases for testings.


Thanks for your reading and support.


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! ;-)


Re: Temporary objects as function parameters or when-is-this-shit-going-to-end?

2017-10-15 Thread ketmar via Digitalmars-d-learn

Michael V. Franklin wrote:

In fact, you might want to propose matching bounty from the community on 
this specific bug to encourage funding.  For example, make an 
announcement on the forum that anyone who places a bounty on the bug in 
question will receive a matching contribution from you.  Maybe that might 
raise the bounty high enough to get someone qualified to fix the bug.  Or 
maybe not; it's just an idea that occurred to me.


judging from my several decades of expirience, bounties almost never works. 
there are alot of reasons for that, but the fact still stands: it is 
*almost* impossible to make something happen with boundy. it may work by 
accident ;-), but i myself wouldn't count on that. either bounty is too 
small ("hey, my time worth much more! i'd better spend it playing 
videogames!"), or it is too big ("hey, this is a Really Huge Problem, if 
somebody wants to pay than much! that means that i'll inevitably spend more 
time on that, and... the bounty is too small. oops." ;-).


but one can hire a contractor to fix some specific problem. this is much 
easier, and almost usually works as people expected: there are clearly 
specified goals, a payment, a timeline and such. both parties know what 
exactly they want, and can control the whole process.


Re: Temporary objects as function parameters or when-is-this-shit-going-to-end?

2017-10-13 Thread ketmar via Digitalmars-d-learn

Jack Applegame wrote:

Compiler creates struct on the stack and silently (without postblitting 
and destruction old object) moves it to another address. Is it normal?

yes.

WAT??? Compiler creates struct on the stack copies it without 
postblitting and destructs both objects.

and this is the real bug.


Re: Does writing from NNTP work?

2017-10-04 Thread ketmar via Digitalmars-d-learn

Tristan B. Kildaire wrote:


Does this work?


btw. there is "D" newsgroup which you can use for testing your NNTP client.

web interface: http://forum.dlang.org/group/D
NNTP name: "D"


Re: Does writing from NNTP work?

2017-10-04 Thread ketmar via Digitalmars-d-learn

Tristan B. Kildaire wrote:


Does this work?


if you can see this reply, it works.


Re: Why isn't there more if( ctfe) in std.math ?

2017-09-23 Thread ketmar via Digitalmars-d-learn

user1234 wrote:

"if (__ctfe) {}" is a test happening at runtime. Both the if and the else 
branches got compiled


nope. compiler knows about this special pseudovariable, and will not 
generate code neither for condition, nor for ctfe branch.


Re: traits for function having actual source declaration?

2017-09-01 Thread ketmar via Digitalmars-d-learn

bitwise wrote:


On Friday, 1 September 2017 at 14:38:38 UTC, bitwise wrote:
When I'm using __traits(allMembers), I get a all the invisible functions 
added by the compiler as well "__ctor", "__xdtor", "__cpctor", etc..


Is there a way to filter them out?


dlang's "Lexical" page says:

"Identifiers starting with __ (two underscores) are reserved."

So I suppose I could just filter out functions with leading underscores, 
but still seems unreliable, as people may not listen.


they *should* listen. anyone who doesn't just aksing for troubles, and i 
see no reason to guard 'em further.


Re: DIPs - question about mores, etiquette and DIP1009 in particular

2017-08-30 Thread ketmar via Digitalmars-d-learn

Cecil Ward wrote:


On Wednesday, 30 August 2017 at 17:19:52 UTC, ketmar wrote:

it is explicitly stated in DIP that existing syntax will not be 
deprecated/removed. i guess that reading the DIP before expressing your 
opinion is the prerequisite...


Good to know. A relief.

I am full of pain drugs and missed the no-deprecation thing when I 
inadequately skimmed the proposal. RTFM as always applies. :-)


it happens sometimes. nwm. ;-)


Re: DIPs - question about mores, etiquette and DIP1009 in particular

2017-08-30 Thread ketmar via Digitalmars-d-learn

Cecil Ward wrote:

Is there a way I can simply register my vote eg about DIP 1009? My vote 
is 'no thanks'. Like the existing system, don't care about the alleged 
verbosity / room thing, and please whatever do not deprecate the existing 
syntax because I use it all over the place and the blocks can have 
complex code in them using statements and multiple statements.


it is explicitly stated in DIP that existing syntax will not be 
deprecated/removed. i guess that reading the DIP before expressing your 
opinion is the prerequisite...


Re: Bug in D?!

2017-08-11 Thread ketmar via Digitalmars-d-learn

Mr. Pib wrote:

Wow, that is pretty screwed up! I thought D was against implicit 
conversions that might cause problems?  I'm passing an int and I should 
be able to append an int without having to worry about the value of the 
int. Instead D chose to do something very strange, awkward, and error 
prone.


this is legacy we got from trying to be C-compatible (along with int/uint 
autoconversion, and some other things). i believe that initially it was 
done to allow something like `char c = 32;`, and now it is too late to 
change it, 'cause such change will break existing code (and we're trying to 
not break the code without a *very* strong reason, even if keeping old code 
working means keeping some old quirks).


Re: Bug in D?!

2017-08-10 Thread ketmar via Digitalmars-d-learn

Mr. Pib wrote:


string Q(alias T, alias D)()
{
pragma(msg, T);
pragma(msg, D);
enum x = T~" = "~D~";";
pragma(msg, x);
}


mixin(Q!(`x`, 100)());

outputs, at compile time,

x
100
x = d;

there is no lowercase d. I did initially define Q as

string Q(alias T, D)(D d)

and one might think it is remnants left over from I cleaned the project 
so it shouldn't be happening. Seems like a bug.


(I realized that I'd probably only ever pass compile time values)

Of course, using D.stringof gives the value.

The problem is the case of D.


nope. the problem is the *value* of D. `char(100)` == 'd'.

string s = "<"~100~">";

yes, this works. weither this bug or not is questionable, but this is how D 
works regerding to implicit type conversions: small ints (in the range of 
[0..char.max]) will be implicitly converted to `char` if necessary.


Re: How to build GUI-based applications in D ?

2017-08-01 Thread ketmar via Digitalmars-d-learn

ashit wrote:


what is the simplest library to create gui applications in D?
i want to create gui applications but couldnt configure the tools so far.
i tried to install DFL several times, but it shows some errors while 
installing (that bold red lables showing : depreacated, depreacated, ... )


i dont need to build something advanced or so, only that common and 
simple elements like: buttons, labels, textboxs, ...


i really like D's syntax (C, C++, C#), but i have nothing to do with 
command line.
the good thing about C# (& WPF) is: double click on installer, start 
design your app.


Adam Ruppe has minigui in his arsd[0] repo. and minigui_xml to make 
interface creation easier. it is not really well-documented yet, tho, so 
you will prolly have to figure some things on your own.


[0] https://github.com/adamdruppe/arsd


Re: Questions about dmd source

2017-07-30 Thread ketmar via Digitalmars-d-learn

Francis Nixon wrote:


I have two completely unrelated questions about the dmd source code.

1. What does the mtype.Type.dotExp method do? The documentation comment 
says that it "Accesses the members of the object e". I'm not sure exactly 
why I would want to do that? Is it for handling types specified using an 
identifier/template chain (aka foo.bar!(uint).c)?
types has some built-in properties, like `.length`, `.sizeof`, `.init` and 
so on. this method is used to access those properties.



2. I've noticed there are some rather long methods in the dmd source, 
involving more than one goto; parse.d is particularly bad. Is there a 
reason for this/is it being fixed?
it just was done this way. dmd parser was "evolved", so what you see is a 
result of evolution (it is not stopeed yet ;-), and evolution doesn't 
produce ideal results. there is no need to specifically "fix" working 
things, it doesn't do any good.


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread ketmar via Digitalmars-d-learn

Clinton wrote:


On Monday, 24 July 2017 at 14:51:04 UTC, rikki cattermole wrote:

Stuff the GC.
You don't need it to care about collecting (or destroying for that 
matter).


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);
```

Normally I would suggest to create your own buffer, but because of the 
DB library probably doesn't support that, no point trying to force it.


[0] http://dlang.org/phobos/core_memory.html#.GC.free


BTW, how would I do this with associative arrays?


you can't. you can `.clear` 'em, though, but this won't immediately free 
the internal storage.


Re: Cleaning/Releasing large arrays from memory

2017-07-24 Thread ketmar via Digitalmars-d-learn

rikki cattermole wrote:


Tell it to free[0] the array directly.

```D
T[] array;

GC.free(array.ptr);


or just `delete arr;`. it is marked as "deprecated" in changelog, but who 
cares? it works.


Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-12 Thread ketmar via Digitalmars-d-learn

ikod wrote:


On Wednesday, 12 July 2017 at 08:24:12 UTC, NoBigDeal256 wrote:

On Monday, 10 July 2017 at 20:55:19 UTC, ketmar wrote:

NoBigDeal256 wrote:

Do you happen to have a link to the bug report for this specific issue 
that I could look at? I looked at the known bugs list and couldn't 
find anything related to this.


nope. it is a kind of "known bug nobody bothered to report". ;-)


Okay, so I decided to ditch curl and switch over to dlang-requests, 
which doesn't depend on curl, and I'm running into this same issue 
again... I don't think this is a curl issue.


looks like circular dependency between thingA and thingB lead to problems 
on exit. this code fails on osx too.


yet at least with curl there was definitely a bug with "slightly too early 
curl shutdown".


Re: Static array with parameter based size?

2017-07-11 Thread ketmar via Digitalmars-d-learn

Miguel L wrote:


I need to create a non-dynamic array like this

void f(int x)
{
int[x] my_array;
...

this does not compile as x value needs to be known at compile time. The 
closest to this I can get is:


void f(int x)
{
int[] my_array;
my_array.length=x;

but I don't really need a dynamic array as length is not going to change 
inside f.


What is the best way to do this?

Thanks in advance


for simple cases you can use `alloca()`. it is fairly low-level, but does 
it's job.


but if your array is really big, or contains types with dtors, you'd better 
stick with `new` (or setting length). you can also put `scope(exit) delete 
my_array;` after declaration, so array will be destroyed on function exit. 
`delete` is... slightly deprecated ;-) (i.e. not recommented for wide use), 
but works, and will call dtors for you.


Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-10 Thread ketmar via Digitalmars-d-learn

NoBigDeal256 wrote:

Do you happen 
to have a link to the bug report for this specific issue that I could 
look at? I looked at the known bugs list and couldn't find anything 
related to this.


nope. it is a kind of "known bug nobody bothered to report". ;-)


Re: Having a strange issue with std.net.curl.HTTP as a struct dependency

2017-07-10 Thread ketmar via Digitalmars-d-learn

NoBigDeal256 wrote:

I'm currently learning D and started working on one of my first projects 
which is an API wrapper. I'm currently having an issue with my program 
getting a InvalidMemoryOperationError upon exiting the process on Windows 
7. On my Debian VM I get a segmentation fault.


known bug in curl finalization on program exit. should be fixed in the next 
release. for now you have to live with it, or build your own phobos.


Re: Why doesn't this work...Struct std.regex.Captures

2017-07-09 Thread ketmar via Digitalmars-d-learn

WhatMeForget wrote:

c.hit is undefined when `c.empty` is `true`.


Re: std.json cannot read an array floats back from file

2017-07-03 Thread ketmar via Digitalmars-d-learn

Yuri wrote:


On Monday, 3 July 2017 at 14:04:47 UTC, ketmar wrote:

Yuri wrote:


On Sunday, 2 July 2017 at 21:15:41 UTC, ketmar wrote:

[...]


I share your sentiment in relation to std.json, ketmar.

On a side note, what would be a better way to serialize/deserialize 
objects in D if std.json does not cut it? It does not have to be JSON 
serialization although would be preferred.


it depends of the types of your objects. simple json-like (de)serializer 
for objects with fixed layout can be done in very small amount of 
code[0]. that's what i am using (and it can *read* json into structs 
too, i'm actually using it to parse some jsons -- idgames API replies, 
for example).


[0] http://repo.or.cz/iv.d.git/blob_plain/HEAD:/txtser.d


Thanks, ketmar, I'll have a look into the code, the objects I am dealing 
with are not particularly complex, that might work well enough.


it doesn't matter if objects are complex or not; the only thing that 
matters is that you must really have *objects* that can be described by 
structs, not "freeform" json. i.e. txtser cannot deserialize json into 
dom-like tree structure, only deserialize structs/arrays/aas.


but structs can contain other structs, and AA values can be structs too, 
and so on.


i.e.: if you don't need arbitrary access to arbitrary json fields, but only 
have to deserialize something with known layout, txtser probably can do the 
job for you.


Re: std.json cannot read an array floats back from file

2017-07-03 Thread ketmar via Digitalmars-d-learn

Yuri wrote:


On Sunday, 2 July 2017 at 21:15:41 UTC, ketmar wrote:
so, write your own wrapper that will convert INTEGER/UINTEGER/FLOAT to 
`double`. i think this is the best solution (if there can be "best 
solution" with std.json at all).


I share your sentiment in relation to std.json, ketmar.

On a side note, what would be a better way to serialize/deserialize 
objects in D if std.json does not cut it? It does not have to be JSON 
serialization although would be preferred.


it depends of the types of your objects. simple json-like (de)serializer 
for objects with fixed layout can be done in very small amount of code[0]. 
that's what i am using (and it can *read* json into structs too, i'm 
actually using it to parse some jsons -- idgames API replies, for example).


[0] http://repo.or.cz/iv.d.git/blob_plain/HEAD:/txtser.d


Re: std.json cannot read an array floats back from file

2017-07-02 Thread ketmar via Digitalmars-d-learn

Yuri wrote:


Hi there,

consider the following simple use case:

   import std.json;
   float[] floats = [1,2,3];
   JSONValue j = "{}".parseJSON;
   j.object["floats"] = floats;
   std.file.write("test.json", j.toString);
   JSONValue jj = readText("test.json").parseJSON;
   jj.object["floats"].array[1].floating.writeln;

It is expected to print '2' in the console, however an exception is 
thrown:


std.json.JSONException@/build/ldc-I3nwWj/ldc-0.17.1/runtime/phobos/std/json.d(235): 
JSONValue is not a floating type


while the below works fine:

   import std.json;
   float[] floats = [1,2,3];
   JSONValue j = "{}".parseJSON;
   j.object["floats"] = floats;
   j.object["floats"].array[1].floating.writeln;

any pointers to what could be going wrong?


'cause what you got back is `JSON_TYPE.INTEGER`. dunno why it is there at 
all, as JSON has no "integers" per se, but it read as integer, and 
`.floating` failed type checking.


so, write your own wrapper that will convert INTEGER/UINTEGER/FLOAT to 
`double`. i think this is the best solution (if there can be "best 
solution" with std.json at all).


Re: What's the fastest way to check if a slice points to static data

2017-06-24 Thread ketmar via Digitalmars-d-learn

Petar Kirov [ZombineDev] wrote:

Oh, I should have mentioned that I don't expect anything but ugly 
platform-specific hacks possibly involving the object file format ;)
Just enough of them to claim that the solution is somewhat cross-platform 
:D


i guess you can loot at how TSL scanning is done in druntime (at least on 
GNU/Linux). it does some parsing of internal structures of loaded ELF. i 
guess you can parse section part of the loaded ELF too, to find out r/o 
sections and their address ranges.


Re: What's the fastest way to check if a slice points to static data

2017-06-24 Thread ketmar via Digitalmars-d-learn

Petar Kirov [ZombineDev] wrote:


***
But in any case, the null-terminated string was just an example 
application.
I'm interested in a fast way to determine the "storage class" of the 
memory

a slice or a pointer point to. I'm expecting some magic along the lines of
checking the range of addresses that the rodata section resides in memory.
Similar to how some allocators or the GC know if they own a range of 
memory.

Any ideas on that?
***


the only query you can do is GC query (see `core.memory.CG` namespace, 
`addrOf()` API, for example). it will tell you if something was allocated with D 
GC or not.


yet it is not guaranteed to be fast (althru it is usually "fast enough").

i think this is all what you can get without resorting to ugly 
platform-specific hacks (that will inevitably break ;-).


Re: What's the fastest way to check if a slice points to static data

2017-06-24 Thread ketmar via Digitalmars-d-learn

ketmar wrote:

p.s.: btw, druntime tries to avoid that edge case by not checking for 
trailing out-of-bounds zero if string ends exactly on dword boundary. it 
will miss some strings this way, but otherwise it is perfectly safe.


oops. not druntime, phobos, in `std.string.toStringz()`.


Re: What's the fastest way to check if a slice points to static data

2017-06-24 Thread ketmar via Digitalmars-d-learn
p.s.: btw, druntime tries to avoid that edge case by not checking for 
trailing out-of-bounds zero if string ends exactly on dword boundary. it 
will miss some strings this way, but otherwise it is perfectly safe.


Re: What's the fastest way to check if a slice points to static data

2017-06-24 Thread ketmar via Digitalmars-d-learn

Petar Kirov [ZombineDev] wrote:

Please note that not all static immutable strings have to be null 
terminated.
It is possible to generate a string at ctfe which may appear the same as 
string literal, but does not have the \0 at the end.


But in that case, the check `s.ptr[s.length] == 0` in fastStringZ
would do the trick, right?


with the edge case when something like the code i posted below managed to 
make `a` perfectly aligned with r/o area, and you got segfault by accising 
out-of-bounds byte.



BTW, are you sure? AFAIU, it doesn't matter if the CTFE engine returns a
non-null-terminated string expression, since the backend or the glue layer
would write it to the object file as if it was a null-terminated string.


immutable ubyte[2] a = [65,66];
enum string s = cast(string)a;
immutable ubyte[2] b = [67,68]; // just to show you that there is no 
zero

void main () {
  assert(s[$-1] == 0);
}



Re: More optional parens concerns

2017-06-24 Thread ketmar via Digitalmars-d-learn

Russel Winder wrote:


On Sat, 2017-06-24 at 11:58 +0300, ketmar via Digitalmars-d-learn
wrote:

Russel Winder wrote:


I note that:
x.map!(…).array.sort
is not valid, you have to have the parentheses on sort:
x.map!(…).array.sort()
Why?

built-in property .sort kicks in and ruins the day. luckily, it will
be completely removed in the upcoming major release.


Ah, thanks. We like stuff being removed as well as added.


sort and .reverse builtins was deprecated for a long time, and scheduled 
to be removed anyway. finally, this happens! (the patch is in git already)


Re: More optional parens concerns

2017-06-24 Thread ketmar via Digitalmars-d-learn

Russel Winder wrote:


I note that:

x.map!(…).array.sort

is not valid, you have to have the parentheses on sort:

x.map!(…).array.sort()

Why?


built-in property .sort kicks in and ruins the day. luckily, it will be 
completely removed in the upcoming major release.


Re: Help me escape optional parens hell

2017-06-24 Thread ketmar via Digitalmars-d-learn

ketmar wrote:


Meta wrote:


So I have no clue what I'm doing wrong. This is driving me insane.


h. known $#^#$@^@%.

	enum SymName = ().stringof[2..$]; // this, instead of 
symbol.stringof


dirty hack, let's hope that DMD devs won't change `.toString()` output 
(i.e. first two chars will always be "& ").


besides this, i know no other way to stop compiler from calling the 
function there.


i hope devs won't break string representation: i bet that there is ALOT of 
code that is using this trick. i myself borrowed it from some other module 
several years ago. and it looks that the module where i found it borrowed 
the trick from some another module. a really long history. ;-)


Re: Help me escape optional parens hell

2017-06-24 Thread ketmar via Digitalmars-d-learn

Meta wrote:


So I have no clue what I'm doing wrong. This is driving me insane.


h. known $#^#$@^@%.

enum SymName = ().stringof[2..$]; // this, instead of 
symbol.stringof

dirty hack, let's hope that DMD devs won't change `.toString()` output 
(i.e. first two chars will always be "& ").


besides this, i know no other way to stop compiler from calling the function 
there.


Re: Help me escape optional parens hell

2017-06-24 Thread ketmar via Digitalmars-d-learn

ketmar wrote:


`.toString()`


toChars().

;-)


Re: Is it possible to call a delegate at compile time?

2017-06-22 Thread ketmar via Digitalmars-d-learn

Andrew Edwards wrote:

I desire to call foo() at compile...  As implemented it does not happen, 
but it's not immediately clear what I am missing. Or is this simply not 
possible as yet? What is the proper way to redesign this template so that 
it will execute at compile time?


there are two caveats. the first is `ref` in Args: that won't work for 
arguments in CTFE (it works for nested functions, though).


and second, whith you can't fight right now: "Error: closures are not yet 
supported in CTFE".


so no, even if you'll remove `ref`, it will not work. sorry.


Re: Operator Overloading + / ~

2017-06-19 Thread ketmar via Digitalmars-d-learn

Martin Tschierschke wrote:


Just a thought it might be useful for cut-n-paste when porting code:

Would it be possible to define an operator overloading for '+'-Operator 
for strings to work as append? (like ~).
I understand, that '~' is in general a better choice than '+', so this is 
of more theoretical interest.

It is clear to me, that when I define my own string type this is possible.

Regards mt.


nope. it is not possible to overload operators for built-in types (and 
string is just an aliased array).


Re: Implementing interfaces using alias this

2017-06-14 Thread ketmar via Digitalmars-d-learn

Balagopal Komarath wrote:


On Wednesday, 14 June 2017 at 11:40:02 UTC, ketmar wrote:
interfaces *require* a full-featured class, with VMT, and some hidden 
pointers to support hidden interface machinery.


I don't think that is the problem here. The type Test!Duck is a class and 
that type is the one implementing the interface.


*sighs*


Re: Implementing interfaces using alias this

2017-06-14 Thread ketmar via Digitalmars-d-learn

Mike B Johnson wrote:


I don't think it has to do with pasting code.

d.Quack() is well defined through the alias. Inheritance requires that a 
Quack() exists, and it does, through the alias.


The compiler could easily create an implementation wrapper that uses the 
alias this.


this is called "code pasting".


Re: Implementing interfaces using alias this

2017-06-14 Thread ketmar via Digitalmars-d-learn

Balagopal Komarath wrote:


On Wednesday, 14 June 2017 at 09:41:49 UTC, ketmar wrote:

Balagopal Komarath wrote:

Why doesn't this work? The Test!Duck type has a void quack() method but 
the compiler says it is not implemented.


'cause `alias this` is *not* a tool that can be used to emulate 
inheritance. no, `quack` is NOT impemented. `alias this` won't 
automagically paste the code.


Thanks for the reply. Is there any reason for disallowing this? AFAIK, 
the alias this guarantees that the interface provided by Test!T is a 
superset of the interface provided by T. And, when T = Duck, T provides 
everything required by IDuck. Couldn't the compiler check while 
instantiating that Test!Duck provides all methods required by IDuck?


besides improper using of `alias this`, there is a technical reason too: 
`struct` is not a `class`, it doesn't have VMT, and other class goodies. as 
i said, `alias this` is not a macro, it doesn't paste code, it just tells 
the compiler to make "symbol redirection" on typechecking. interfaces 
*require* a full-featured class, with VMT, and some hidden pointers to 
support hidden interface machinery.


Re: Implementing interfaces using alias this

2017-06-14 Thread ketmar via Digitalmars-d-learn

Balagopal Komarath wrote:

Why doesn't this work? The Test!Duck type has a void quack() method but 
the compiler says it is not implemented.


'cause `alias this` is *not* a tool that can be used to emulate 
inheritance. no, `quack` is NOT impemented. `alias this` won't 
automagically paste the code.


Re: Weird template instantiation problem

2017-06-12 Thread ketmar via Digitalmars-d-learn

Arafel wrote:


I actually found a workaround for the original issue:


yeah, sorry for not proposing a workaround: i thought that you already did 
it, and now you're just interested why the original code doesn't work. ;-)


i think that this is a bug (or, rather, unimplemented feature).


Re: Generic operator overloading for immutable types?

2017-06-12 Thread ketmar via Digitalmars-d-learn

Gary Willoughby wrote:

In the following code is there any way to make the `opBinary` method 
generic to be able to accept immutable as well as a standard type? The 
code currently passes the unit test but I wonder if I could get rid of 
the duplication to overload the operator? I'm failing badly.


public inout(Rational) opBinary(string op)(inout(Rational) rhs) inout {
  static if (op == "+") {
return Rational(0, 0);
  } else {
static assert(0, "Operator '" ~ op ~ "' not implemented");
  }
}


Re: Weird template instantiation problem

2017-06-12 Thread ketmar via Digitalmars-d-learn
p.s.: while i understand the technical reason for second error message, it 
is still random and confusing.


Re: Weird template instantiation problem

2017-06-12 Thread ketmar via Digitalmars-d-learn

more funny compiler messages:

alias xx = size_t function (int[]);
struct S1(T, typeof(xx) X) {}
void main() {
  S1!(int, defaultChooser!int) s;
}

Error: type uint function(int[]) is not an expression

but:

struct S2(T, typeof(defaultChooser!T) chooser=defaultChooser!T) {}
void main() {
  S2!int s;
}

Error: undefined identifier T

error messages are totally random (and why `typeof()` is not allowed there?)


Re: a way to specily floating-point numbers as bit patters

2017-06-09 Thread ketmar via Digitalmars-d-learn

Honey wrote:


On Friday, 9 June 2017 at 16:34:28 UTC, ketmar wrote:

Try -0.1685f.


it doesn't matter if i can find the decimal representation for the given 
bit pattern or not. the whole post is about removing the need to rely on 
lossy binary->decimal->binary conversions.


Lossless turn-around is guaranteed if you are using sufficiently many 
digits. In case of IEEE-754 single precision it's 8 significant decimal 
digits.


it is highly platform-dependent. and both bin->dec, and dec->bin conversion 
routines can contain errors, btw. so using decimal forms for exact 
bit-patterns is the last thing i want to do, as i know how fragile they are.


Re: a way to specily floating-point numbers as bit patters

2017-06-09 Thread ketmar via Digitalmars-d-learn

Basile B. wrote:


On Friday, 9 June 2017 at 17:18:43 UTC, ketmar wrote:

Basile B. wrote:


 enum binFloat = *cast(float*) 


i was SO sure that this won't work in CTFE that i didn't even tried to 
do it. "it will fail anyway, there is no reason in trying!" ;-)


You can do the arithmetic as well. I don't know why but i supposed that 
my static asserts were a proof of CTFE-ability.


yeah, it is CTFEable. now i recall that such casting for floats was 
special-cased in interpreter exactly to allow this kind of things. my bad.


Re: a way to specily floating-point numbers as bit patters

2017-06-09 Thread ketmar via Digitalmars-d-learn

Basile B. wrote:


 enum binFloat = *cast(float*) 


i was SO sure that this won't work in CTFE that i didn't even tried to do 
it. "it will fail anyway, there is no reason in trying!" ;-)


Re: a way to specily floating-point numbers as bit patters

2017-06-09 Thread ketmar via Digitalmars-d-learn

Petar Kirov [ZombineDev] wrote:


Do HexFloats (http://dlang.org/spec/lex#HexFloat) help?


hm. i somehow completely missed "%a" format specifier! yeah, 
"-0x1.6ep-3" did the trick.


tnx. i should do my homework *before* posting big rants, lol.


Re: a way to specily floating-point numbers as bit patters

2017-06-09 Thread ketmar via Digitalmars-d-learn

Basile B. wrote:


ps. "-0.17 0xBE2AAAC1". it's not the same! (and yes, it matters).


-0.17f is not representable as a 32 bit float. The actuall value 
that's stored is -0.169994592259765625, hence the difference. See 
https://www.h-schmidt.net/FloatConverter/IEEE754.html and enter your 
value in the field labeled "You entered".


i'm completely aware about floating point values representation, and 
problems with bin->dec->bin conversions of floats. the post is about 
avoiding those conversions at all.


and this means that i can't inline my calculated values! each time i 
want to get floating value with a known bit-pattern, i have to store it 
as uint, and resort to ugly hack: 
`*cast(immutable(float)*)([2])`.


and i can't do this trick in CTFE, as such pointer tricks aren't 
permitted.


i tried different workarounds, but they're all ugly. it would be very 
nice to have a way to define IEEE floating point numbers as bit-patterns 
in the language itself. what do you think?


Yes, easy to do, a template alà octal or hexString.


can you show it, please? remember, CTFE-able!


  1   2   3   4   5   6   7   8   9   10   >