What is the best minimal runtime for d?
I've been playing around with d with a KL25Z eval board. However it is not easy, It's not easy to know what features are and are not usable. when will i get a linker error to some __eabi_something_not_in_the_runtime. So, question is, does there exist a minimal runtime that will work with LDC/GDC and is up to date? Also I find it interesting that its hard to distinguish what features are language features and which are run-time features. If that is even on someones radar. Also bonus question: How do you think should registers be read and written to in D?
Re: Whitch can replace std::bind/boost::bind ?
On 03/18/2016 09:14 AM, Dsby wrote: On Friday, 18 March 2016 at 11:09:37 UTC, Atila Neves wrote: On Friday, 18 March 2016 at 10:50:34 UTC, Dsby wrote: foreach (i ; 0..4) { auto th = new Thread(delegate(){listRun(i);});//this is erro _thread[i]= th; th.start(); } void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } I want to know how to use it like std::bind. I would suggest not using Thread directly: foreach(i; 0..4) { auto tid = spawn(, i); //from std.concurrency _tid[i] = tid; } Atila the listrun is in class. it is a delegate,it is not a function. Here is one that puts 'shared' in a lot of places: import std.stdio; import std.concurrency; class C { int i; this (int i) shared { this.i = i; } void listRun() shared { writeln("listRun for ", i); } } void worker(shared(C) c) { c.listRun(); } void main() { Tid[4] _tid; foreach(i; 0..4) { auto c = new shared(C)(i); auto tid = spawn(, c); _tid[i] = tid; } } Here is an equivalent that casts to and from 'shared' before and after the thread call: import std.stdio; import std.concurrency; class C { int i; this (int i) { this.i = i; } void listRun() { writeln("listRun for ", i); } } void worker(shared(C) c_shared) { auto c = cast(C)c_shared; c.listRun(); } void main() { Tid[4] _tid; foreach(i; 0..4) { auto c = new C(i); auto c_shared = cast(shared(C))c; auto tid = spawn(, c_shared); _tid[i] = tid; } } Ali
Re: Whitch can replace std::bind/boost::bind ?
On Friday, 18 March 2016 at 10:50:34 UTC, Dsby wrote: foreach (i ; 0..4) { auto th = new Thread(delegate(){listRun(i);});//this is erro _thread[i]= th; th.start(); } void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } I want to know how to use it like std::bind. I would suggest not using Thread directly: foreach(i; 0..4) { auto tid = spawn(, i); //from std.concurrency _tid[i] = tid; } Atila
Re: Gdmd compiling error
On Wednesday, 16 March 2016 at 12:17:42 UTC, Orkhan wrote: On Tuesday, 15 March 2016 at 18:26:48 UTC, Ali Çehreli wrote: I don't know where from shpuld I get help. Thanks. Is the xcomm library available somewhere, maybe if we had a link to the original documentation we could help.
Re: Class member always has the same address
On Saturday, 19 March 2016 at 20:24:15 UTC, szymski wrote: class A { B b = new B(); } This is *default* initialization, not per instance initialization. The compiler will create one instance of B and it will become the default initializer of b in *every* instance of A. You can verify that with this: class B {} class A { B b = new B; } void main() { auto as = [new A, new A, new A]; assert(as[0].b is as[1].b); assert(as[1].b is as[2].b); assert(as[0].b is as[2].b); } Here, all of the asserts will pass. But add a constructor to A that does this: this() { b = new B; } And now the first assert will fail. This is *per-instance* initialization.
Re: Obtaining argument names in (variadic) functions
On Wednesday, 16 March 2016 at 21:05:43 UTC, JR wrote: On Wednesday, 16 March 2016 at 20:43:09 UTC, jkpl wrote: I try to anticipate the reason why you want this. [...] I use something *kinda* sort of similar in my toy project to print all fields of a struct, for debugging purposes when stuff goes wrong. Getting the names of the member variables is crucial then. http://dpaste.dzfl.pl/748c4dd97de6 That's a nice learning piece. I think "with" is cool, reminds me of a nice R feature.
Re: Implementing virtual dispatch in D
Read the ABI page again, its fairly sufficient about this stuff. --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus
Destructor order
Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? 2) Is all the dtors always called when i call destroy ? Thanks for a reply !
Implementing virtual dispatch in D
So this is mostly curiosity and not completely related to D but I would like to know how a vtable is actually implemented. All the explanations that I have seen so far are a bit vague and it would be nice to actually see some code. I tried to implement the following myself interface Something{ void print(); int getNumber(); } This is how I would do it: struct VDispatch(Types...){ void* vptr; char typeId; void print(){ foreach(index, type; Types){ if(index == typeId){ (cast(type*)vptr).print(); } } } int getNumber(){ foreach(index, type; Types){ if(index == typeId){ return (cast(type*)vptr).getNumber(); } } throw new Error("Unknown Type"); } this(T)(T* ptr){ import std.meta: staticIndexOf; vptr = cast(void*)ptr; typeId = staticIndexOf!(T, Types); } } struct Foo{ int number; void print(){ import std.stdio; writeln("Foo: ", number); } int getNumber(){ return number; } } struct Bar{ int number; void print(){ import std.stdio; writeln("Bar: ", number); } int getNumber(){ return number; } } unittest{ import std.stdio; alias VFooBar = VDispatch!(Foo, Bar); auto t = VFooBar(new Foo(42)); auto t1 = VFooBar(new Bar(24)); t.print(); t1.print(); writeln(t.getNumber()); writeln(t1.getNumber()); } Is this how it works internally? I assume the compiler would generate which types actually supported at runtime? I have modeled this as a variadic template "Types..." and it has to be managed by the user.
Re: size_t index=-1;
On 3/16/16 2:40 PM, Laeeth Isharc wrote: should it be a compiler warning to assign a negative literal to an unsigned without a cast ? Why? They implicitly convert. int x = -1; uint y = x; I don't see a difference between this and your code. And we can't change this behavior of the second line, too much arguably valid code would break. -Steve
Re: Gdmd compiling error
On Tuesday, 15 March 2016 at 18:26:48 UTC, Ali Çehreli wrote: On 03/15/2016 02:45 AM, Orkhan wrote: > output of the gdc is : > > root@ubuntu:/home/alikoza/Downloads/i686-pc-linux-gnu# gdc > gdc: fatal error: no input files > compilation terminated. That makes sense. It should produce an executable if you give it a .d file: gdc foo.d Since you installed gdmd as well, you can get back to the Xcom server files. Have you tried building it now? If that still fails, please open another thread because I don't think I can help you any further with that project and I don't think anybody else is following this thread. :) Ali Dear Ali , I am still getting the same error although I installed gdc and gdmd . The command run giving output like below : root@ubuntu:/opt/xcomm# make dmd -O -inline -Isrc -version=daemon -op -of./xcomm src/misc_util.d src/socket_base.d src/xcomm_sockets.d src/msgserver_core.d src/char_outbuffer.d src/logging.d src/xml_util.d src/plugins.d src/xcomm_protocol/*.d src/stork/*.d src/stork/*/*.d -fPIC -q,-rdynamic -L-ldl Error: unrecognized switch '-q,-rdynamic' Makefile:35: recipe for target 'protocol-daemon' failed make: *** [protocol-daemon] Error 1 I don't know where from shpuld I get help. Thanks.
Re: Destructor order
On Friday, 18 March 2016 at 14:53:20 UTC, Steven Schveighoffer wrote: On 3/18/16 7:44 AM, Nicholas Wilson wrote: On Friday, 18 March 2016 at 10:20:40 UTC, Temtaime wrote: Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? yes 2) Is all the dtors always called when i call destroy ? yes. destroy calls __dtor() which recursively call __dtor() on its members I think technically not true. If you call __dtor directly, it does not recurse. But this is an implementation detail. -Steve Why doesn't this print ~B ~A? http://dpaste.dzfl.pl/0bef0a4316b7 It raises a bug on my code because dtor are called in "wrong" order. b holds a ref to a, why a is desctructed before b? Andrea
Re: size_t index=-1;
On Wednesday, 16 March 2016 at 21:49:05 UTC, Steven Schveighoffer wrote: No, please don't. Assigning a signed value to an unsigned (and vice versa) is very useful, and there is no good reason to break this. -Steve I'm not talking about removing it completely. The implicit conversion should only happen when it's safe: ``` int s; if (s >= 0) // VRP saves the day { uint u = s; } ``` ``` uint u; if (u > short.max) throw new Exception("Argument out of range"); // Or `assert` short s = u; ```
Re: How do I extend an enum?
On Saturday, 19 March 2016 at 17:40:27 UTC, Lass Safin wrote: Why: enum Base { A, B, } enum Derived : Base { C, // Gives error, says it can't implicitly convert expression to Base. D = 1, // Same error E = cast(Base)294, // Finally works. Can only be cast(Derived) instead. } void func(Derived d) {} func(Derived.E); // works. func(Derived.A); // Gives error, says it can't call function with Base.A. func(cast(Derived)Derived.A); // Works. So, what's the proper way of extending an enum? Look at the grammar: https://dlang.org/spec/enum.html There's no inheritance system for the enums. after the ":" can only be specified the type of the members, aka the "EnumBaseType". " EnumDeclaration: enum Identifier EnumBody enum Identifier : EnumBaseType EnumBody " So when you write enum Derived : Base {} It just means that "Derived" members must be of type "Base" So actually the only thing you can do is to reduce the members count: enum Base {A,B} enum Derived : Base {C = Base.A}
Re: immutable array in constructor
On Thursday, 17 March 2016 at 11:27:01 UTC, Rene Zwanenburg wrote: On Thursday, 17 March 2016 at 10:11:43 UTC, Jeff Thompson wrote: This is a simplified example from a larger class I have where I need an immutable constructor. This is because I need to construct an object an pass it to other functions which take an immutable object. So, how to keep an immutable constructor? In that case, new immutable C() should work I believe. Also, if you mark the constructor as pure, new C() should be implicitly convertible to an immutable C. new immutable C() worked! Thanks for the insight.
Re: Destructor order
On Friday, 18 March 2016 at 10:20:40 UTC, Temtaime wrote: Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? yes 2) Is all the dtors always called when i call destroy ? yes. destroy calls __dtor() which recursively call __dtor() on its members Thanks for a reply !
Re: Need help with delegates and vibed
On Saturday, 19 March 2016 at 19:53:01 UTC, Suliman wrote: Thanks! I am understand a little bit better, but not all. ``` shared static this() { auto settings = new HTTPServerSettings; settings.port = 8080; listenHTTP(settings, ); } void handleRequest(HTTPServerRequest req, HTTPServerResponse res) { if (req.path == "/") res.writeBody("Hello, World!", "text/plain"); } ``` https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/http/server.d#L104 I expected to see in listenHTTP() function some processing but it's simply get args and then do return: return listenHTTP(...) Could you explain why it's do so? -- Where is constructor of this class? http://vibed.org/api/vibe.http.client/HTTPClientRequest How I should use it if have only docs, and do not have examples? (I am trying understand how to use docs without cope-past examples) The function is overloaded; it's calling the main implementation at line 77 after transforming the arguments. The constructor for HTTPClientRequest is likely undocumented because you should not construct it yourself; vibe.d constructs it and passes it to the function you register with listenHTTP.
Re: Class member always has the same address
On 19.03.2016 21:24, szymski wrote: In my opinion should give different addresses for each instance of A, because it's not static. What am I doing wrong? Thanks in advance. The As are different, but they all reference the same B. Initialize b in a constructor instead.
Class member always has the same address
Hello! I'm having a big problem with class members. I'm kinda new to D, so this may be my fault, but look at the following code: import std.stdio; class B { int variable; } class A { B b = new B(); } void main() { // Create 10 instances of A foreach(i; 0 .. 10) { auto a = new A(); writeln(, " = ", a.b.variable); // Print a.b.variable address and its value a.b.variable++; } } When ran, it prints something totally different from what I expect: 430088 = 0 430088 = 1 430088 = 2 430088 = 3 430088 = 4 430088 = 5 430088 = 6 430088 = 7 430088 = 8 430088 = 9 In my opinion should give different addresses for each instance of A, because it's not static. What am I doing wrong? Thanks in advance.
Re: How do I extend an enum?
On Saturday, 19 March 2016 at 17:40:27 UTC, Lass Safin wrote: Why: enum Base { A, B, } enum Derived : Base { C, // Gives error, says it can't implicitly convert expression to Base. D = 1, // Same error E = cast(Base)294, // Finally works. Can only be cast(Derived) instead. } void func(Derived d) {} func(Derived.E); // works. func(Derived.A); // Gives error, says it can't call function with Base.A. func(cast(Derived)Derived.A); // Works. So, what's the proper way of extending an enum? There is no way to extend an enum. When you think about it, it's actually the opposite of what you'd generally want. Given two classes: class A {} class B : A {} Every instance of B is a valid A. That is, given a variable of type A, you could assign any B to it. Now consider enums: enum A { x, y, z } enum B : A {} Which values could you put in B? Only those that would be valid for A. That is, only x, y and z. Imagine that we could: enum B : A { w } A foo = B.w; foo now holds a value that is not valid for its type. Hence, you simply cannot. Are there cases where you want to define a new enum that contains all the items in a 'base' enum in addition to some new items? Absolutely, and D lacks a good way to do that. But subtyping would in any case not be the correct way to do it. Are there cases where you want to extend an enum by making a subtype with more items? I would argue that's a strong code smell in D, but I can see why you'd want to. -- Simen
Re: size_t index=-1;
On 3/16/16 4:55 PM, Mathias Lang wrote: On Wednesday, 16 March 2016 at 20:11:41 UTC, Steven Schveighoffer wrote: On 3/16/16 2:40 PM, Laeeth Isharc wrote: should it be a compiler warning to assign a negative literal to an unsigned without a cast ? Why? They implicitly convert. int x = -1; uint y = x; I don't see a difference between this and your code. And we can't change this behavior of the second line, too much arguably valid code would break. We can change it, and we should. But it should be deprecated properly, and we should put in place enough candy to make it viable (See http://forum.dlang.org/post/vbeohujwdsoqfgwqg...@forum.dlang.org ). No, please don't. Assigning a signed value to an unsigned (and vice versa) is very useful, and there is no good reason to break this. -Steve
Re: Solution to "statement is not reachable" depending on template variables?
On 3/16/16 9:48 PM, tsbockman wrote: On Wednesday, 16 March 2016 at 11:22:02 UTC, rikki cattermole wrote: Change those static if's to just plain old ifs. This only works (sometimes) because D's value range propagation doesn't understand comparisons or normal if statements very well. This will hopefully be fixed sooner or later: https://github.com/D-Programming-Language/dmd/pull/1913 https://github.com/D-Programming-Language/dmd/pull/5229 The only future-proof way to fix the "statement is not reachable" warning, is to guard the potentially unreachable code with a `static if` whose predicate precisely describes the circumstances in which it becomes unreachable... Which itself is a terrible solution that doesn't scale well at all to complex generic code and violates the "DRY" principle. We really ought to just remove the warning. It just doesn't mesh well with D's super-powered meta-programming features. Yes. I agree. The way I look at it is that the code *is* reached in some cases, so it should compile (and just remove that section in that instance). IMO any time a template value is used for branching, it should turn that warning off. -Steve
Re: Need help with delegates and vibed
Thanks! I am understand a little bit better, but not all. ``` shared static this() { auto settings = new HTTPServerSettings; settings.port = 8080; listenHTTP(settings, ); } void handleRequest(HTTPServerRequest req, HTTPServerResponse res) { if (req.path == "/") res.writeBody("Hello, World!", "text/plain"); } ``` https://github.com/rejectedsoftware/vibe.d/blob/master/source/vibe/http/server.d#L104 I expected to see in listenHTTP() function some processing but it's simply get args and then do return: return listenHTTP(...) Could you explain why it's do so? -- Where is constructor of this class? http://vibed.org/api/vibe.http.client/HTTPClientRequest How I should use it if have only docs, and do not have examples? (I am trying understand how to use docs without cope-past examples)
Re: Checking if a port is listening
On Saturday, 19 March 2016 at 18:24:38 UTC, Marc Schütz wrote: On Saturday, 19 March 2016 at 09:55:13 UTC, Lucien wrote: const int MAX = 64; Socket[] sockets = new Socket[MAX]; string ipb = "192.168.0."; for (int i = 1; i < MAX; i++) { Here's the reason for your SEGV: You need to start at 0, because otherwise `sockets[0]` is `null`. When you add that to the SocketSet, it will trigger the segfault. I guess you want to skip the 0 because it represents the subnet address; in that case, you simply mustn't add `sockets[0]` to the set. But then there is another problems: You're using `select()` the wrong way. The point of using select() is that you can check things asynchronously. Your code should be structured like this (pseudo code): auto ss = new SocketSet(); for(i; 1 .. MAX) { auto s = new Socket(...); s.blocking = false; s.connect(...); ss.add(s); } while(ss.count > 0) { auto write_ss = ss.dup; auto status = Socket.select(null /* read */, write_ss /* write */, null /* error */, 500.msecs); // for a connect()ing socket, writeability means connected if(status < 0) writeln("interrupted, retrying"); else if(status == 0) writeln("timeout, retrying"); else { writeln(status, " socket(s) changed state"); for(fd; 0 .. write_ss.maxfd+1) { // check whether this socket has changed if(!write_ss.isSet(fd)) continue; // if yes, remove it from the original SocketSet ss.remove(fd); writeln("successfully connected to 192.168.0.", fd+1); } } } thanks, but what's the type of fd ? current code: const int MAX = 64; // usefull ? Socket[] sockets = new Socket[MAX]; string ipb = "192.168.0."; SocketSet ss = new SocketSet(); for (int i = 0; i < MAX; i++) { string ip = ipb~to!string(i+1); Socket s = new Socket(AddressFamily.INET, std.socket.SocketType.STREAM, ProtocolType.TCP); s.blocking = false; InternetAddress ia = new InternetAddress(ip, 22); sockets[i] = s; s.connect(ia); ss.add(s); } while (ss.max > 0) { SocketSet write_ss = ss; auto status = Socket.select(null, write_ss, null, 50.msecs); // for a connect()ing socket, writeability means connected if(status < 0) writeln("interrupted, retrying"); else if(status == 0) writeln("timeout, retrying"); else { writeln(status, " socket(s) changed state"); for (int i = 0; i < write_ss.tupleof[1]; i++) { // tried to do something //Socket fd = write_ss.tupleof[0][i]; string ip = ipb~to!string(i+1); if(!write_ss.isSet(fd)) continue; ss.remove(fd); writeln("successfully connected to ", ip); } } }
Re: Solution to "statement is not reachable" depending on template variables?
On Thursday, 17 March 2016 at 17:12:07 UTC, Steven Schveighoffer wrote: Yes. I agree. The way I look at it is that the code *is* reached in some cases, so it should compile (and just remove that section in that instance). IMO any time a template value is used for branching, it should turn that warning off. -Steve That's what I think it should do, also. However, when we discussed it before, Daniel Murphy pretty much told me there is no practical way to actually implement that behavior in the compiler. So, the next best thing is to just remove the warning entirely.
Re: size_t index=-1;
On Thursday, 17 March 2016 at 17:09:46 UTC, Steven Schveighoffer wrote: Converting unsigned to signed or vice versa (of the same size type) is safe. No information is lost. Saying that "no information is lost" in such a case, is like saying that if I encrypt my hard drive and then throw away the password, "no information is lost". Technically this is true: the bit count is the same as it was before. In practice, though, the knowledge of how information is encoded is essential to actually using it. In the same way, using `cast(ulong)` to pass `-1L` to a function that expects a `ulong` results in a de-facto loss of information, because that `-1L` can no longer distinguished from `ulong.max`, despite the fundamental semantic difference between the two. VRP on steroids would be nice, but I don't think it's as trivial to solve. D's current VRP is actually surprisingly anemic: it doesn't even understand integer comparisons, or the range restrictions implied by the predicate when a certain branch of an `if` statement is taken. Lionello Lunesu made a PR a while back that adds these two features, and it makes the compiler feel a lot smarter. (The PR was not accepted at the time, but I have since revived it: https://github.com/D-Programming-Language/dmd/pull/5229)
Re: size_t index=-1;
On Wednesday, March 16, 2016 22:37:40 Mathias Lang via Digitalmars-d-learn wrote: > On Wednesday, 16 March 2016 at 21:49:05 UTC, Steven Schveighoffer > > wrote: > > No, please don't. Assigning a signed value to an unsigned (and > > vice versa) is very useful, and there is no good reason to > > break this. > > > > -Steve > > I'm not talking about removing it completely. The implicit > conversion should only happen when it's safe: > > ``` > int s; > if (s >= 0) // VRP saves the day > { >uint u = s; > } > ``` > > ``` > uint u; > > if (u > short.max) >throw new Exception("Argument out of range"); > // Or `assert` > short s = u; > ``` Now, you're talking about comparing signed and unsigned values, which is a completely different ballgame. Just assigning one to the other really isn't a problem, and sometimes you _want_ the wraparound. If you assume that it's always the case that assigning a negative value to an unsigned type is something that programmers don't want to do, then you haven't programmed in C enough. And while it could still be done by requiring casts, consider that every time you do a cast, you're telling the compiler to just shut up and do what you want, which makes it easy to hide stuff that you don't want hidden - especially when code changes later. D purposefully allows converting between signed and unsigned types of the same or greater size. And based on what he's said on related topics in the past, there's pretty much no way that you're going to convince Walter that it's a bad idea. And I really don't see a problem with the current behavior as far as assignment goes. It's comparisons which are potentially problematic, and that's where you'd have some chance of getting a warning or error added to the compiler. If you want to actually have the values check to ensure that a negative value isn't assigned to an unsigned integer, then use std.conv.to to do conversions or wrap your integers in types that have more restrictive rules. IIRC, at least one person around here has done that already so that they can catch integer overflow - which is basically what you're complaining about here. - Jonathan M Davis
Re: No property error message
On Saturday, 19 March 2016 at 18:36:10 UTC, ric maicle wrote: I got an error message with the following code saying: Error: no property 'length' for type 'int[string]' Shouldn't the error message say 'length()'? ~~~ import std.stdio; void main() { int[string] a; a["one"] = 1; a["two"] = 2; a["three"] = 3; auto len = a.length(); } ~~~ DMD 2.070.2 Well, if we think of it as separate steps, resolving the function "length" is what's failing here. The subsequent () would just call it, if it existed, but the name of the property/symbol would still be "length". But yes; you could make a case that, in the case of invalid function calls, it should include the whole erroneous attempted function signature in the error message. I can imagine it becoming ambiguous once templates enter the picture however, and for not much gain.
Re: How do I extend an enum?
On Saturday, 19 March 2016 at 17:41:29 UTC, Lass Safin wrote: On Saturday, 19 March 2016 at 17:40:27 UTC, Lass Safin wrote: Why: enum Base { A, B, } enum Derived : Base { C, // Gives error, says it can't implicitly convert expression to Base. D = 1, // Same error E = cast(Base)294, // Finally works. Can only be cast(Derived) instead. } void func(Derived d) {} func(Derived.E); // works. func(Derived.A); // Gives error, says it can't call function with Base.A. func(cast(Derived)Derived.A); // Works. So, what's the proper way of extending an enum? Meant "Can also be cast(Derived) instead." "enum B : A" doesn't mean "B extends A", but rather "enum B containing members of type A". Not specifying a type makes it implicitly convertible to int, I think. If you're looking to extend a named enum, I think you have to create a new one. It will become a new type too, though that might not matter. enum Foo { first=123, second=456, third=789 } // int type inferred enum Bar : int { // the ": int" here is important first = Foo.first, // implicit cast to int second = Foo.second, third = Foo.third, fourth = 42, fifth = 0 } If you don't define Bar as having members of type int, it will guess that you want Foo (because we're assigning members with values of Foo's). They would be limited to the range of values Foo offers, and Bar.fourth = 42 is irreconcilabe with that.
Re: Destructor order
On Friday, 18 March 2016 at 15:03:14 UTC, Steven Schveighoffer wrote: On 3/18/16 10:58 AM, Andrea Fontana wrote: On Friday, 18 March 2016 at 14:53:20 UTC, Steven Schveighoffer wrote: On 3/18/16 7:44 AM, Nicholas Wilson wrote: On Friday, 18 March 2016 at 10:20:40 UTC, Temtaime wrote: Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? yes 2) Is all the dtors always called when i call destroy ? yes. destroy calls __dtor() which recursively call __dtor() on its members I think technically not true. If you call __dtor directly, it does not recurse. But this is an implementation detail. Why doesn't this print ~B ~A? http://dpaste.dzfl.pl/0bef0a4316b7 It raises a bug on my code because dtor are called in "wrong" order. b holds a ref to a, why a is desctructed before b? Structs are contained completely within the class instance memory block (e.g. the OP's code). Classes are references. They are not destroyed when you destroy the holder, that is left up to the GC, which can destroy in any order. And in fact, it's a programming error to destroy any GC-allocated memory inside your dtor, because it may already be gone! -Steve Not the case. I'm writing a binding for a library. Class A and B wrap c-struct and on d-tor I have to free underlying c object calling c-library destroyer. I'm not destroying any d/GC-allocated object. But of course i have to destroy c object in the correct order... How to?
Re: size_t index=-1;
On Wednesday, 16 March 2016 at 20:11:41 UTC, Steven Schveighoffer wrote: On 3/16/16 2:40 PM, Laeeth Isharc wrote: should it be a compiler warning to assign a negative literal to an unsigned without a cast ? Why? They implicitly convert. int x = -1; uint y = x; I don't see a difference between this and your code. And we can't change this behavior of the second line, too much arguably valid code would break. -Steve We can change it, and we should. But it should be deprecated properly, and we should put in place enough candy to make it viable (See http://forum.dlang.org/post/vbeohujwdsoqfgwqg...@forum.dlang.org ).
Re: Destructor order
On 3/18/16 7:44 AM, Nicholas Wilson wrote: On Friday, 18 March 2016 at 10:20:40 UTC, Temtaime wrote: Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? yes 2) Is all the dtors always called when i call destroy ? yes. destroy calls __dtor() which recursively call __dtor() on its members I think technically not true. If you call __dtor directly, it does not recurse. But this is an implementation detail. -Steve
No property error message
I got an error message with the following code saying: Error: no property 'length' for type 'int[string]' Shouldn't the error message say 'length()'? ~~~ import std.stdio; void main() { int[string] a; a["one"] = 1; a["two"] = 2; a["three"] = 3; auto len = a.length(); } ~~~ DMD 2.070.2
Re: Checking if a port is listening
On Saturday, 19 March 2016 at 09:55:13 UTC, Lucien wrote: const int MAX = 64; Socket[] sockets = new Socket[MAX]; string ipb = "192.168.0."; for (int i = 1; i < MAX; i++) { Here's the reason for your SEGV: You need to start at 0, because otherwise `sockets[0]` is `null`. When you add that to the SocketSet, it will trigger the segfault. I guess you want to skip the 0 because it represents the subnet address; in that case, you simply mustn't add `sockets[0]` to the set. But then there is another problems: You're using `select()` the wrong way. The point of using select() is that you can check things asynchronously. Your code should be structured like this (pseudo code): auto ss = new SocketSet(); for(i; 1 .. MAX) { auto s = new Socket(...); s.blocking = false; s.connect(...); ss.add(s); } while(ss.count > 0) { auto write_ss = ss.dup; auto status = Socket.select(null /* read */, write_ss /* write */, null /* error */, 500.msecs); // for a connect()ing socket, writeability means connected if(status < 0) writeln("interrupted, retrying"); else if(status == 0) writeln("timeout, retrying"); else { writeln(status, " socket(s) changed state"); for(fd; 0 .. write_ss.maxfd+1) { // check whether this socket has changed if(!write_ss.isSet(fd)) continue; // if yes, remove it from the original SocketSet ss.remove(fd); writeln("successfully connected to 192.168.0.", fd+1); } } }
Re: Obtaining argument names in (variadic) functions
On Thursday, 17 March 2016 at 11:52:13 UTC, Edwin van Leeuwen wrote: On Wednesday, 16 March 2016 at 20:53:42 UTC, JR wrote: void printVars(Args...)() if (Args.length > 0) { import std.stdio : writefln; foreach (i, arg; Args) { writefln("%s\t%s:\t%s", typeof(Args[i]).stringof, Args[i].stringof, arg); } } void main() { int abc = 3; string def = "58"; float ghi = 3.14f; double jkl = 3.14; printVars!(abc,def,ghi,jkl)(); } Interesting, any idea if it is possible to do assignment within template.. Either: printVars!(int abc=5,string def="58")(); or something like printVars!("abc","def",ghi)(5,"58"); What would the use-cases for those be? I don't think the first is valid grammar, and I'm not sure what you want the second to do. Resolve symbols by string literals of their names? That might need a string mixin as they wouldn't be in scope when in the called template function, but I've never tried it. You *can* cook up something that modifies the values of variables you pass in -- like modifyVars!(abc,def,ghi)("asdf", 123, 3.14) -- but you just might be better off with runtime ref parameters then.
Re: Obtaining argument names in (variadic) functions
On 3/16/16 4:24 PM, data pulverizer wrote: Hi D gurus, is there a way to obtain parameter names within the function body? I am particularly interested in variadic functions. Something like: void myfun(T...)(T x){ foreach(i, arg; x) writeln(i, " : ", arg); } void main(){ myfun(a = 2, b = "two", c = 2.0); } This isn't valid code. The name of the parameters is x[0], x[1], and x[2]. You could do something like: myfun("a", 2, "b", "two", "c", 2.0); and process it properly. -Steve
Re: Solution to "statement is not reachable" depending on template variables?
On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote: Hi all, I've found discussions, but not an actual "recommended" solution for the problem of "statement is not reachable" warnings in templates with early returns, e.g.: ``` bool nobool(T...)() { foreach (i, U; T) { static if (is(U == bool)) { return false; } } return true; // emits "Warning: statement is not reachable" } [...] On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote: import std.meta; template isBool(U)() = is(U == bool); static if (!allSatisfy!(isBool, T)) { return true; // no longer emits a warning } Something like this should work.
Re: Solution to "statement is not reachable" depending on template variables?
On Wednesday, 16 March 2016 at 11:47:35 UTC, QAston wrote: import std.meta; template isBool(U)() = is(U == bool); static if (!allSatisfy!(isBool, T)) { return true; // no longer emits a warning } Something like this should work. Thanks, but: On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote: (I have heavily simplified the real-world code, please don't discuss alternative solutions to the "is(U==bool)" in particular. For sake of argument, assume that the predicate is a complicated beast.)
Re: Whitch can replace std::bind/boost::bind ?
On Friday, 18 March 2016 at 10:50:34 UTC, Dsby wrote: foreach (i ; 0..4) { auto th = new Thread(delegate(){listRun(i);});//this is erro _thread[i]= th; th.start(); } void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } I want to know how to use it like std::bind. This is a bug in the compiler: https://issues.dlang.org/show_bug.cgi?id=2043
Re: immutable array in constructor
On Thursday, 17 March 2016 at 10:04:53 UTC, Anonymouse wrote: On Thursday, 17 March 2016 at 09:57:37 UTC, Jeff Thompson wrote: In the following code, I explicitly declare array as immutable. But it compiles with the error shown below in the comment. The array object is declared immutable, so how can the compiler say it is a mutable object? In summary, how to pass an immutable array to an immutable constructor? class C { int i; this(immutable int[] array) immutable { i = array[0]; } } void func() { immutable int[] array = [1]; auto c = new C(array); // Error: immutable method C.this is not callable using a mutable object } The error message isn't very good, but remove immutable from the constructor and it works. this(immutable int[] array) { This is a simplified example from a larger class I have where I need an immutable constructor. This is because I need to construct an object an pass it to other functions which take an immutable object. So, how to keep an immutable constructor?
Re: How do I extend an enum?
On Saturday, 19 March 2016 at 17:40:27 UTC, Lass Safin wrote: Why: enum Base { A, B, } enum Derived : Base { C, // Gives error, says it can't implicitly convert expression to Base. D = 1, // Same error E = cast(Base)294, // Finally works. Can only be cast(Derived) instead. } void func(Derived d) {} func(Derived.E); // works. func(Derived.A); // Gives error, says it can't call function with Base.A. func(cast(Derived)Derived.A); // Works. So, what's the proper way of extending an enum? Meant "Can also be cast(Derived) instead."
How do I extend an enum?
Why: enum Base { A, B, } enum Derived : Base { C, // Gives error, says it can't implicitly convert expression to Base. D = 1, // Same error E = cast(Base)294, // Finally works. Can only be cast(Derived) instead. } void func(Derived d) {} func(Derived.E); // works. func(Derived.A); // Gives error, says it can't call function with Base.A. func(cast(Derived)Derived.A); // Works. So, what's the proper way of extending an enum?
Re: Solution to "statement is not reachable" depending on template variables?
On 17/03/16 5:05 AM, Johan Engelen wrote: On Wednesday, 16 March 2016 at 11:22:02 UTC, rikki cattermole wrote: Change those static if's to just plain old ifs. But then this wouldn't compile, would it? ``` static if(__traits(compiles, __traits(getMember, a, "b"))) { return a.b; } ``` (real code, I am not making this up) Hmm no. If that's in a foreach as well, you'll need to solve it some other way. --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus
Re: module renaming by declaration
On Saturday, 19 March 2016 at 16:02:33 UTC, Christof Schardt wrote: What am I doing wrong? Using rdmd. It assumes the filename will match the module name to locate the file, though the language itself doesn't require this. What you want to do to make this work is use ordinary dmd and pass both files to it at the same time: dmd aaa.d test.d and it will work then.
module renaming by declaration
The module declaration allows to define a module name different from the filename. (TDPL sec. 11.1.8) I tried a simple example: File test.d: - import bbb; - File aaa.d (same directory): - module bbb; - Running rdmd test.d does give an error: "module bbb is in file bbb.d which cannot be read" What am I doing wrong?
Re: immutable array in constructor
On Thursday, 17 March 2016 at 09:57:37 UTC, Jeff Thompson wrote: In the following code, I explicitly declare array as immutable. But it compiles with the error shown below in the comment. The array object is declared immutable, so how can the compiler say it is a mutable object? In summary, how to pass an immutable array to an immutable constructor? class C { int i; this(immutable int[] array) immutable { i = array[0]; } } void func() { immutable int[] array = [1]; auto c = new C(array); // Error: immutable method C.this is not callable using a mutable object } The error message isn't very good, but remove immutable from the constructor and it works. this(immutable int[] array) {
Re: Gdmd compiling error
On Wednesday, 16 March 2016 at 12:20:32 UTC, Edwin van Leeuwen wrote: On Wednesday, 16 March 2016 at 12:17:42 UTC, Orkhan wrote: On Tuesday, 15 March 2016 at 18:26:48 UTC, Ali Çehreli wrote: I don't know where from shpuld I get help. Thanks. Is the xcomm library available somewhere, maybe if we had a link to the original documentation we could help. thanks for your answer. the original unpacked project is in the link below : http://www.speedyshare.com/6y4Tv/47d2b57d/xcom.zip you can find the installation inside of the doc file . that is the only source of the project. In general it should not be difficult but I can not understand why it makes a problem . It is so important for me . .
Re: casting to a voldemort type
On Saturday, 19 March 2016 at 15:10:56 UTC, Alex wrote: void* funVoldemort(size_t my_size) The term 'voldemort type' refers to a public type, just an unnamed one. What you have here is a pointer to a private type... and void* is something you often should avoid since the compiler doesn't help you with them. You can pass an entirely different object and the function would never know (until it crashes). It might look like a feature now, passing those size_t's around, but you'll probably find it buggy later... The question is, how to write the accompanied function in the part, which should cast the pointer to the voldemort type? You can't, the struct is too private to be seen. ff @ 20 and encapsulate it all in the same struct. What I already thought about is: writing a union inside the struct, which is either my long or some other data. But this is in general not possible, as the "other data" could be together greater, then the long. The compiler knows how to handle that, or you could use a wrapped pointer and ordinary private definitions so the outside doesn't pry too far.
casting to a voldemort type
Finally. A question about Voldemort types :) I have the following class, with an accompanying function. Skip the code to the link for a runnable version. /*--- code begin ---*/ class roof { int huhu = 9; void* funVoldemort(size_t my_size) { auto gg = huhu; if(my_size < 5) { return new size_t(3); } struct Vold { int begin; int end; bool b; int ff() { return gg; } } return new Vold(); } } void rara_fun(void* ptr, uint mysize) { if(mysize < 5) { writeln("rara_fun: ", *(cast(size_t*)ptr)); } else { //??? } } /*--- code end ---*/ see http://dpaste.dzfl.pl/2e361adf04b6 for a runnable copy. First of all: it is a little bit unsatisfying, that the funVoldemort is not working with an auto or auto ref return type. But I see, the types are different after all. And, to solve this part I changed the return type to a void*. The question is, how to write the accompanied function in the part, which should cast the pointer to the voldemort type? What I already thought about is: writing a union inside the struct, which is either my long or some other data. But this is in general not possible, as the "other data" could be together greater, then the long. The obvious solution would be: to define the struct outside the function. But the point is, that these structs only defines behavior and the data inside them is just auxiliary data to pass the queries to the real data storages. The question is motivated by the following: I try to write some recursive structure. And if the accompanying function is called, it passes the question to a voldemort object. The voldemort object by itself doesn't store the information but knows, how to reduce the "my_size" parameter and which other voldemort object to ask. This goes on, till the real data is accessed.
Re: immutable array in constructor
On 03/17/2016 09:32 AM, Jeff Thompson wrote: On Thursday, 17 March 2016 at 11:27:01 UTC, Rene Zwanenburg wrote: On Thursday, 17 March 2016 at 10:11:43 UTC, Jeff Thompson wrote: This is a simplified example from a larger class I have where I need an immutable constructor. This is because I need to construct an object an pass it to other functions which take an immutable object. So, how to keep an immutable constructor? In that case, new immutable C() should work I believe. Also, if you mark the constructor as pure, new C() should be implicitly convertible to an immutable C. new immutable C() worked! Thanks for the insight. In case it's useful to others, I have qualified constructors covered at the following link (without the compilation error that you've faced but still pointing out the fact that the mutable constructor may be called unintentionally): http://ddili.org/ders/d.en/special_functions.html#ix_special_functions.qualifier,%20constructor Ali
Checking if a port is listening
Hello, I want to know if a port of an ip address is listening, actually, I've this : http://pastebin.com/pZhm0ujy (checking port 22/ssh) It works, but it took me ~10min to scan 30 addresses. How can reduce the expiration delay ?
Re: Obtaining argument names in (variadic) functions
On Wednesday, 16 March 2016 at 20:24:38 UTC, data pulverizer wrote: Hi D gurus, is there a way to obtain parameter names within the function body? I am particularly interested in variadic functions. Something like: void myfun(T...)(T x){ foreach(i, arg; x) writeln(i, " : ", arg); } void main(){ myfun(a = 2, b = "two", c = 2.0); } // should print a : 2 b : two c : 2.0 Thanks in advance Loving the mixins and tuples You can do it precisely like that if the variables/symbols you pass as (template) arguments are properly declared first. http://dpaste.dzfl.pl/0b452efeaaab void printVars(Args...)() if (Args.length > 0) { import std.stdio : writefln; foreach (i, arg; Args) { writefln("%s\t%s:\t%s", typeof(Args[i]).stringof, Args[i].stringof, arg); } } void main() { int abc = 3; string def = "58"; float ghi = 3.14f; double jkl = 3.14; printVars!(abc,def,ghi,jkl)(); }
Re: string and char[] in Phobos
When a string is not an in parameter, it can't be declared `in char[]`.
Re: Whitch can replace std::bind/boost::bind ?
On Friday, 18 March 2016 at 11:09:37 UTC, Atila Neves wrote: On Friday, 18 March 2016 at 10:50:34 UTC, Dsby wrote: foreach (i ; 0..4) { auto th = new Thread(delegate(){listRun(i);});//this is erro _thread[i]= th; th.start(); } void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } I want to know how to use it like std::bind. I would suggest not using Thread directly: foreach(i; 0..4) { auto tid = spawn(, i); //from std.concurrency _tid[i] = tid; } Atila the listrun is in class. it is a delegate,it is not a function.
Re: size_t index=-1;
On Wednesday, March 16, 2016 18:40:56 Laeeth Isharc via Digitalmars-d-learn wrote: > should it be a compiler warning to assign a negative literal to > an unsigned without a cast ? Maybe? It's a common enough thing to do that I'm willing to bet that Walter would object, but what you're really looking to do in most cases like that is to get something like uint.max, in which case it's better to just use the built-in constant. But I doubt that assigning negative literals to unsigned variables causes much in the way of bugs. The bigger problem is comparing signed and unsigned types, and a number of folks have argued that that should be a warning or error. - Jonathan M Davis
Obtaining argument names in (variadic) functions
Hi D gurus, is there a way to obtain parameter names within the function body? I am particularly interested in variadic functions. Something like: void myfun(T...)(T x){ foreach(i, arg; x) writeln(i, " : ", arg); } void main(){ myfun(a = 2, b = "two", c = 2.0); } // should print a : 2 b : two c : 2.0 Thanks in advance Loving the mixins and tuples
Re: Solution to "statement is not reachable" depending on template variables?
On Wednesday, 16 March 2016 at 17:08:20 UTC, Johan Engelen wrote: On Wednesday, 16 March 2016 at 11:47:35 UTC, QAston wrote: import std.meta; template isBool(U)() = is(U == bool); static if (!allSatisfy!(isBool, T)) { return true; // no longer emits a warning } Something like this should work. Thanks, but: On Wednesday, 16 March 2016 at 11:18:36 UTC, Johan Engelen wrote: (I have heavily simplified the real-world code, please don't discuss alternative solutions to the "is(U==bool)" in particular. For sake of argument, assume that the predicate is a complicated beast.) This method will work regarless of the predicate, just check if the predicate isn't matched for the whole array using allSatisfy/anySatisfy.
Re: size_t index=-1;
On Wednesday, 16 March 2016 at 22:07:39 UTC, Anonymouse wrote: size_t pos = "banana".indexOf("c"); if (pos > 0) { Although I also think it makes sense to warn (in specific cases) about mixed-sign comparisons, the example you give here does nothing that we can warn about. It is a comparison of an unsigned "pos" with a literal that is unsigned too. ("0" literal must be considered signed and unsigned without any warnings)
string and char[] in Phobos
Hi, I saw from the forum that functions with string like arguments better use `in char[]` instead of `string` type, because then it can accept both string and char[] types. But recently when actually using D, I found that many phobos functions/constructors use `string`, while many returns `char[]`, causing me to do a lot of conv.to!string. And many times I have to fight with the excessive template error messages. Is there a reason to use `string` instead of `in char[]` in function arguments? Do you tend to change those phobos functions?
Re: size_t index=-1;
On Saturday, 19 March 2016 at 10:01:41 UTC, Basile B. wrote: Yes and that's the opposite that should happend: when signed and unsigned are mixed in a comparison, the unsigned value should be implictly cast to a wider signed value. And then it works! That would be reasonable. Whether it's actually faster than just inserting an extra check for `signed_value < 0` in mixed comparisons is likely platform dependent, though. Honestly though - even just changing the rules to implicitly convert both operands to a signed type of the same size, instead of an unsigned type of the same size, would be a huge improvement. Small negative values are way more common than huge (greater than signed_type.max) positive ones in almost all code. (This change will never happen, of course, as it would be far too subtle of a breaking change for existing code.) Regardless, the first step is to implement the pre-approved solution to DMD 259: deprecate the current busted behavior.
Re: Obtaining argument names in (variadic) functions
On Wednesday, 16 March 2016 at 20:53:42 UTC, JR wrote: void printVars(Args...)() if (Args.length > 0) { import std.stdio : writefln; foreach (i, arg; Args) { writefln("%s\t%s:\t%s", typeof(Args[i]).stringof, Args[i].stringof, arg); } } void main() { int abc = 3; string def = "58"; float ghi = 3.14f; double jkl = 3.14; printVars!(abc,def,ghi,jkl)(); } Interesting, any idea if it is possible to do assignment within template.. Either: printVars!(int abc=5,string def="58")(); or something like printVars!("abc","def",ghi)(5,"58");
Re: size_t index=-1;
On Saturday, 19 March 2016 at 10:24:41 UTC, Ola Fosheim Grøstad wrote: On Saturday, 19 March 2016 at 10:01:41 UTC, Basile B. wrote: On Saturday, 19 March 2016 at 09:33:25 UTC, tsbockman wrote: [...] The reason that *attempting* such a comparison produces such weird results, is because the signed value is being implicitly cast to an unsigned type. Yes and that's the opposite that should happend: when signed and unsigned are mixed in a comparison, the unsigned value should be implictly cast to a wider signed value. And then it works! - https://issues.dlang.org/show_bug.cgi?id=15805 - https://github.com/BBasile/iz/blob/v0.5.8/import/iz/sugar.d#L1017 I have no problem with C++ compilers complaining about signed/unsigned comparisons. It sometimes means you should reconsider the comparison, so it leads to better code. The better solution is to add 7, 15, 31 and 63 bit unsigned integer types that safely converts to signed (this is what Ada does) FPC (Object Pascal) too, but that not a surpise since it's in the same family and remove implicit conversion for unsigned 8,16,32, and 64 bit integers. Yes that's almost that but in D the only solution I see is like in my template: widening. When widening is not possible (mainly on X86_64) then warning. The problem is that cent and ucent are not implemented, otherwise it would always work even on 64 bit OS. I'd like to propose a PR for this (not for cent/ucent but for the widening) but it looks a bit overcomplicated for a first contrib in the compiler...
Re: size_t index=-1;
On Saturday, 19 March 2016 at 10:01:41 UTC, Basile B. wrote: On Saturday, 19 March 2016 at 09:33:25 UTC, tsbockman wrote: [...] The reason that *attempting* such a comparison produces such weird results, is because the signed value is being implicitly cast to an unsigned type. Yes and that's the opposite that should happend: when signed and unsigned are mixed in a comparison, the unsigned value should be implictly cast to a wider signed value. And then it works! - https://issues.dlang.org/show_bug.cgi?id=15805 - https://github.com/BBasile/iz/blob/v0.5.8/import/iz/sugar.d#L1017 I have no problem with C++ compilers complaining about signed/unsigned comparisons. It sometimes means you should reconsider the comparison, so it leads to better code. The better solution is to add 7, 15, 31 and 63 bit unsigned integer types that safely converts to signed (this is what Ada does) and remove implicit conversion for unsigned 8,16,32, and 64 bit integers.
Re: size_t index=-1;
On Friday, 18 March 2016 at 23:35:42 UTC, tsbockman wrote: `ulong.max` and `-1L` are fundamentally different semantically, even with two's complement modular arithmetic. Different types implies different semantics, but not the literals in isolation. Under modular arithmetics for an ubyte the literals -128 and 128 both refer to 128. This follows from -128 == 0 - (128). Unfortunately in D, the actual arithmetics is not done modulo 2^8, but modulo 2^32. So, what we should object to is modular arithmetics over integers as defined in D. Just because a few operations (addition and subtraction, mainly) can use a common implementation for both, does not change that. Division, for example, cannot be done correctly without knowing whether the inputs are signed or not. Yes, both multiplication and division change with the type, but you usually don't want signed values in modular arithmetics? The major flaw is in how D defines arithmetics for integers.
Re: size_t index=-1;
On Saturday, 19 March 2016 at 09:33:25 UTC, tsbockman wrote: [...] The reason that *attempting* such a comparison produces such weird results, is because the signed value is being implicitly cast to an unsigned type. Yes and that's the opposite that should happend: when signed and unsigned are mixed in a comparison, the unsigned value should be implictly cast to a wider signed value. And then it works! - https://issues.dlang.org/show_bug.cgi?id=15805 - https://github.com/BBasile/iz/blob/v0.5.8/import/iz/sugar.d#L1017
Re: size_t index=-1;
On Saturday, 19 March 2016 at 09:35:00 UTC, tsbockman wrote: Both of the literals I used in my example explicitly indicate the type, not just the value. Yes, but few people specify unsigned literals and relies on them being implicitly cast to unsigned. You don't want to type 0UL and 1UL all the time. This is a another thing that Go does better, numeric literals ought to not be bound to a concrete type. So while I agree with you that the integer situation is messy, changing it to something better requires many changes. Which I am all for.
Re: Checking if a port is listening
On Friday, 18 March 2016 at 09:50:12 UTC, Marc Schütz wrote: Looking at an strace of nmap, it seems it opens a bunch of sockets, puts them into non-blocking mode, calls connect on them (which will return EINPROGRESS), and then uses select(2) to wait for them (in a loop, until all have either been accepted or rejected). select(2) accepts a timeout value, so you can determine how long you want to wait. Here's an excerpt: ... socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 50 fcntl(50, F_GETFL) = 0x2 (flags O_RDWR) fcntl(50, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(50, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(50, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(50, SOL_IP, IP_TTL, [-1], 4) = 0 connect(50, {sa_family=AF_INET, sin_port=htons(32778), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 51 fcntl(51, F_GETFL) = 0x2 (flags O_RDWR) fcntl(51, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(51, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(51, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(51, SOL_IP, IP_TTL, [-1], 4) = 0 connect(51, {sa_family=AF_INET, sin_port=htons(1029), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 52 fcntl(52, F_GETFL) = 0x2 (flags O_RDWR) fcntl(52, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(52, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(52, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(52, SOL_IP, IP_TTL, [-1], 4) = 0 connect(52, {sa_family=AF_INET, sin_port=htons(2013), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) select(53, [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], {0, 0}) = 100 (in [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], out [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], left {0, 0}) ... I'm pretty sure the setsockopt() calls aren't essential. I tried: -- // ... const int MAX = 64; Socket[] sockets = new Socket[MAX]; string ipb = "192.168.0."; for (int i = 1; i < MAX; i++) { string ip = ipb~to!string(i); Socket s = new Socket(AddressFamily.INET, std.socket.SocketType.STREAM, ProtocolType.TCP); s.blocking = false; sockets[i] = s; InternetAddress ia = new InternetAddress(ip, 22); s.connect(ia); } foreach (int i, Socket s; sockets) { SocketSet ss = new SocketSet(); //ss.add(s); if (s.select(ss, null, null, 500.msecs) > 0) { writeln("\n\nDONE: ", ipb~to!string(i), ":22"); } else { writeln("\n\nFAIL: ", ipb~to!string(i), ":22 is unreachable !\n"); } } writeln("DONE"); -- When I uncomment ss.add(s); , I got the error -11. Any suggestions ?
Re: size_t index=-1;
On Saturday, 19 March 2016 at 04:17:42 UTC, Jonathan M Davis wrote: The only thing that I'm aware of that Walter has thought _might_ be something that we should change is allowing the comparison between signed and unsigned integers, and if you read what he says in the bug report for it, he clearly doesn't think it's a big problem: https://issues.dlang.org/show_bug.cgi?id=259 And that's something that clearly causes bugs in way that converting between signed and unsigned integers does not. You're fighting for a lost cause on this one. - Jonathan M Davis You do realize that, technically, there are no comparisons between basic signed and unsigned integers in D? The reason that *attempting* such a comparison produces such weird results, is because the signed value is being implicitly cast to an unsigned type. The thing you say *is* a problem, is directly caused by the thing that you say is *not* a problem.
Re: Solution to "statement is not reachable" depending on template variables?
On Wednesday, 16 March 2016 at 17:34:13 UTC, Steven Schveighoffer wrote: On 3/16/16 7:18 AM, Johan Engelen wrote: Hi all, I've found discussions, but not an actual "recommended" solution for the problem of "statement is not reachable" warnings in templates with early returns, e.g.: ``` bool nobool(T...)() { foreach (i, U; T) { static if (is(U == bool)) { return false; } } return true; // emits "Warning: statement is not reachable" } Instead of foreach, you could use recursive mechanism. Not ideal, but it would work. Another possibility: foreach(i, U; T) { static if(is(U == bool)) { return false; } else static if(i + 1 == T.length) { return true; } } I like your second solution, it's clever :)
Re: size_t index=-1;
On Saturday, 19 March 2016 at 08:49:29 UTC, Ola Fosheim Grøstad wrote: On Friday, 18 March 2016 at 23:35:42 UTC, tsbockman wrote: `ulong.max` and `-1L` are fundamentally different semantically, even with two's complement modular arithmetic. Different types implies different semantics, but not the literals in isolation. Both of the literals I used in my example explicitly indicate the type, not just the value.
Re: Solution to "statement is not reachable" depending on template variables?
On Wednesday, 16 March 2016 at 11:22:02 UTC, rikki cattermole wrote: Change those static if's to just plain old ifs. This only works (sometimes) because D's value range propagation doesn't understand comparisons or normal if statements very well. This will hopefully be fixed sooner or later: https://github.com/D-Programming-Language/dmd/pull/1913 https://github.com/D-Programming-Language/dmd/pull/5229 The only future-proof way to fix the "statement is not reachable" warning, is to guard the potentially unreachable code with a `static if` whose predicate precisely describes the circumstances in which it becomes unreachable... ...Which itself is a terrible solution that doesn't scale well at all to complex generic code and violates the "DRY" principle. We really ought to just remove the warning. It just doesn't mesh well with D's super-powered meta-programming features.
Re: size_t index=-1;
On Thursday, 17 March 2016 at 22:46:01 UTC, tsbockman wrote: In the same way, using `cast(ulong)` to pass `-1L` to a function that expects a `ulong` results in a de-facto loss of information, because that `-1L` can no longer distinguished from `ulong.max`, despite the fundamental semantic difference between the two. Only providing modular arithmetics is a significant language design flaw, but as long as all integers are defined to be modular then there is no fundamental semantic difference either. Of course, comparisons beyond equality doesn't work for modular arithmetics either, irrespective of sign... You basically have to decide whether you want a line or a circle; Walter chose the circle for integers and the line for floating point. The circle is usually the wrong model, but that does not change the language definition...
Re: Checking if a port is listening
Looking at an strace of nmap, it seems it opens a bunch of sockets, puts them into non-blocking mode, calls connect on them (which will return EINPROGRESS), and then uses select(2) to wait for them (in a loop, until all have either been accepted or rejected). select(2) accepts a timeout value, so you can determine how long you want to wait. Here's an excerpt: ... socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 50 fcntl(50, F_GETFL) = 0x2 (flags O_RDWR) fcntl(50, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(50, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(50, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(50, SOL_IP, IP_TTL, [-1], 4) = 0 connect(50, {sa_family=AF_INET, sin_port=htons(32778), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 51 fcntl(51, F_GETFL) = 0x2 (flags O_RDWR) fcntl(51, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(51, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(51, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(51, SOL_IP, IP_TTL, [-1], 4) = 0 connect(51, {sa_family=AF_INET, sin_port=htons(1029), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 52 fcntl(52, F_GETFL) = 0x2 (flags O_RDWR) fcntl(52, F_SETFL, O_RDWR|O_NONBLOCK) = 0 setsockopt(52, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 setsockopt(52, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation not permitted) setsockopt(52, SOL_IP, IP_TTL, [-1], 4) = 0 connect(52, {sa_family=AF_INET, sin_port=htons(2013), sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in progress) select(53, [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], {0, 0}) = 100 (in [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], out [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52], left {0, 0}) ... I'm pretty sure the setsockopt() calls aren't essential.
Re: Obtaining argument names in (variadic) functions
On Wednesday, 16 March 2016 at 20:24:38 UTC, data pulverizer wrote: Hi D gurus, is there a way to obtain parameter names within the function body? I am particularly interested in variadic functions. Something like: void myfun(T...)(T x){ foreach(i, arg; x) writeln(i, " : ", arg); } void main(){ myfun(a = 2, b = "two", c = 2.0); } // should print a : 2 b : two c : 2.0 Thanks in advance Loving the mixins and tuples I try to anticipate the reason why you want this. As said in a previous answer you can access to an individual element by using the array syntax but also _param_, with X the index of the parameter: void myfun(T...)(T x) { import std.traits; import std.stdio; writeln(ParameterIdentifierTuple!(myfun!T)); writeln(_param_0); writeln(_param_1); writeln(_param_2); } void main() { int a=1,b=2,c=3; myfun(a,b,c); }
Re: Obtaining argument names in (variadic) functions
On Wednesday, 16 March 2016 at 20:53:42 UTC, JR wrote: On Wednesday, 16 March 2016 at 20:24:38 UTC, data pulverizer wrote: Hi D gurus, is there a way to obtain parameter names within the function body? I am particularly interested in variadic functions. Something like: void myfun(T...)(T x){ foreach(i, arg; x) writeln(i, " : ", arg); } void main(){ myfun(a = 2, b = "two", c = 2.0); } // should print a : 2 b : two c : 2.0 Thanks in advance Loving the mixins and tuples You can do it precisely like that if the variables/symbols you pass as (template) arguments are properly declared first. http://dpaste.dzfl.pl/0b452efeaaab void printVars(Args...)() if (Args.length > 0) { import std.stdio : writefln; foreach (i, arg; Args) { writefln("%s\t%s:\t%s", typeof(Args[i]).stringof, Args[i].stringof, arg); } } void main() { int abc = 3; string def = "58"; float ghi = 3.14f; double jkl = 3.14; printVars!(abc,def,ghi,jkl)(); } That's brilliant! Thanks JR
Re: Solution to "statement is not reachable" depending on template variables?
On 16/03/16 11:18 PM, Johan Engelen wrote: Hi all, I've found discussions, but not an actual "recommended" solution for the problem of "statement is not reachable" warnings in templates with early returns, e.g.: ``` bool nobool(T...)() { foreach (i, U; T) { static if (is(U == bool)) { return false; } } return true; // emits "Warning: statement is not reachable" } bool nobool_nowarning(T...)() { bool retval = true; foreach (i, U; T) { static if (is(U == bool)) { retval = false; } } return retval; } void main() { static assert ( nobool_nowarning!(int,bool)() == false ); static assert ( nobool_nowarning!(int,int)() == true ); static assert ( nobool!(int,bool)() == false ); static assert ( nobool!(int,int)() == true ); } ``` (I have heavily simplified the real-world code, please don't discuss alternative solutions to the "is(U==bool)" in particular. For sake of argument, assume that the predicate is a complicated beast.) The `nobool` template prevents compilation with `-w`. Is `nobool_nowarning`, with the early return eradicated, the only acceptable solution? (with the hope that there will not be a "dead store" warning in the future...) What if early returns cannot be avoided? Thanks, Johan Change those static if's to just plain old ifs. Imagine those foreach loops being unrolled and what that happens there isn't just one return there, imagine many many many of them and all of them valid. --- This email has been checked for viruses by Avast antivirus software. https://www.avast.com/antivirus
Re: size_t index=-1;
On Thursday, 17 March 2016 at 01:57:16 UTC, Jonathan M Davis wrote: or wrap your integers in types that have more restrictive rules. IIRC, at least one person around here has done that already so that they can catch integer overflow - which is basically what you're complaining about here. That's me (building on Robert Schadek's work): https://code.dlang.org/packages/checkedint Although I should point out that my `SmartInt` actually has *less* restrictive rules than the built-in types - all possible combinations of size and signedness are both allowed and safe for all operations, without any explicit casts. A lot of what `SmartInt` does depends on (minimal) extra runtime logic, which imposes a ~30% performance penalty (when integer math is actually the bottleneck) with good compiler optimizations (GDC or LDC). But, a lot of it could also be done at no runtime cost, by leveraging VRP. C's integer math rules are really pretty bad, even when taking performance into account. Something as simple as by default promoting to a signed, rather than unsigned, type would prevent many bugs in practice, at zero cost (except that it would be a breaking change). There is also `SafeInt` with "more restrictive rules", if it is for some reason necessary to work inside the limitations of the built-in basic integer types.
Re: Checking if a port is listening
On Wednesday, 16 March 2016 at 22:22:15 UTC, Anonymouse wrote: import core.thread; // for .seconds Nitpick: `seconds` is defined in `core.time`; `core.thread` just reexports it. s.setOption(SocketOptionLevel.SOCKET, SNDTIMEO, 10.seconds); s.setOption(SocketOptionLevel.SOCKET, RCVTIMEO, 10.seconds);
Re: size_t index=-1;
On Friday, March 18, 2016 21:17:42 Jonathan M Davis via Digitalmars-d-learn wrote: > On Friday, March 18, 2016 23:48:32 tsbockman via Digitalmars-d-learn wrote: > > I'm basically saying, "because information is lost when casting > > between signed and unsigned, all such casts should be explicit". > > See. Here's the fundamental disagreement. _No_ information is lost when > converting between signed and unsigned integers. e.g. > > int i = -1; > uint ui = i; > int j = i; > assert(j == -1); > > But even if you convinced us, you'd have to convince Walter. And based on > previously discussions on this subject, I think that you have an _extremely_ > low chance of that. He doesn't even think that there's a problem that > > void foo(bool bar) {} > void foo(long bar) {} > foo(1); > > resulted in call to the bool overload was a problem when pretty much > everyone else did. The only thing that I'm aware of that Walter has thought > _might_ be something that we should change is allowing the comparison > between signed and unsigned integers, and if you read what he says in the > bug report for it, he clearly doesn't think it's a big problem: > > https://issues.dlang.org/show_bug.cgi?id=259 > > And that's something that clearly causes bugs in way that converting between > signed and unsigned integers does not. You're fighting for a lost cause on > this one. And I really should have proofread this message before sending it... :( Hopefully, you get what I meant though. - Jonathan M Davis
Re: Checking if a port is listening
On Wednesday, 16 March 2016 at 20:44:12 UTC, Lucien wrote: Hello, I want to know if a port of an ip address is listening, actually, I've this : http://pastebin.com/pZhm0ujy (checking port 22/ssh) It works, but it took me ~10min to scan 30 addresses. How can reduce the expiration delay ? I don't know if they apply here, but you can lower the send and receive timeouts for the socket. I'm not sure which (or if either) of them you want to tweak. https://dlang.org/library/std/socket/socket_option.html import core.thread; // for .seconds s.setOption(SocketOptionLevel.SOCKET, SNDTIMEO, 10.seconds); s.setOption(SocketOptionLevel.SOCKET, RCVTIMEO, 10.seconds); I guess you could also use a non-blocking socket and decide yourself when enough time has passed to declare it a failed attempt.
Re: size_t index=-1;
On Thursday, 17 March 2016 at 01:57:16 UTC, Jonathan M Davis wrote: Just assigning one to the other really isn't a problem, and sometimes you _want_ the wraparound. If you assume that it's always the case that assigning a negative value to an unsigned type is something that programmers don't want to do, then you haven't programmed in C enough. Greater than 90% of the time, even in low level code, an assignment, comparison, or any other operation that mixes signed and unsigned types is being done directly (without bounds checking) only for speed, laziness, or ignorance - not because 2's complement mapping of negative to positive values is actually desired. Forcing deliberate invocations of 2's complement mapping between signed and unsigned types to be explicitly marked is a good thing, seeing as the intended semantics are fundamentally different. I interpret any resistance to this idea, simply as evidence that we haven't yet made it sufficiently easy/pretty to be explicit. Any idea that it's actually *desirable* for code to be ambiguous in this way is just silly.
Re: immutable array in constructor
On Thursday, 17 March 2016 at 11:27:01 UTC, Rene Zwanenburg wrote: Also, if you mark the constructor as pure, new C() should be implicitly convertible to an immutable C. Ah! That's a good tip. Now I understand why I never have to say `new immutable(C)()` in my own code. (I am in the habit of marking everything I can as `pure`.)
Re: Whitch can replace std::bind/boost::bind ?
On 03/18/2016 03:50 AM, Dsby wrote: foreach (i ; 0..4) { auto th = new Thread(delegate(){listRun(i);});//this is erro _thread[i]= th; th.start(); } void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } I want to know how to use it like std::bind. A workaround is an intermediate function that returns the delegate: import std.stdio; import core.thread; void listRun(int i) { writeln("i = ", i); // the value is not(0,1,2,3), it all is 2. } auto makeClosure(int i) { return delegate(){listRun(i);}; } void main() { Thread[4] _thread; foreach (i ; 0..4) { auto th = new Thread(makeClosure(i)); _thread[i]= th; th.start(); } } Prints different values: i = 1 i = 0 i = 2 i = 3 Ali
Re: Destructor order
On 3/18/16 10:58 AM, Andrea Fontana wrote: On Friday, 18 March 2016 at 14:53:20 UTC, Steven Schveighoffer wrote: On 3/18/16 7:44 AM, Nicholas Wilson wrote: On Friday, 18 March 2016 at 10:20:40 UTC, Temtaime wrote: Hi ! I wonder if i can rely on this code : http://dpaste.dzfl.pl/745cc5b1cdfb There's two questions: 1) Is dtors always called in reverse order ? yes 2) Is all the dtors always called when i call destroy ? yes. destroy calls __dtor() which recursively call __dtor() on its members I think technically not true. If you call __dtor directly, it does not recurse. But this is an implementation detail. Why doesn't this print ~B ~A? http://dpaste.dzfl.pl/0bef0a4316b7 It raises a bug on my code because dtor are called in "wrong" order. b holds a ref to a, why a is desctructed before b? Structs are contained completely within the class instance memory block (e.g. the OP's code). Classes are references. They are not destroyed when you destroy the holder, that is left up to the GC, which can destroy in any order. And in fact, it's a programming error to destroy any GC-allocated memory inside your dtor, because it may already be gone! -Steve
Re: size_t index=-1;
On 3/17/16 6:46 PM, tsbockman wrote: On Thursday, 17 March 2016 at 17:09:46 UTC, Steven Schveighoffer wrote: Converting unsigned to signed or vice versa (of the same size type) is safe. No information is lost. Saying that "no information is lost" in such a case, is like saying that if I encrypt my hard drive and then throw away the password, "no information is lost". Technically this is true: the bit count is the same as it was before. It's hard to throw away the "key" of 2's complement math. In practice, though, the knowledge of how information is encoded is essential to actually using it. In practice, a variable that is unsigned or signed is expected to behave like it is declared. I don't think anyone expects differently. When I see: size_t x = -1; I expect x to behave like an unsigned size_t that represents -1. There is no ambiguity here. Where it gets confusing is if you didn't mean to type size_t. But the compiler can't know that. When you start doing comparisons, then ambiguity creeps in. The behavior is well defined, but not very intuitive. You can get into trouble even without mixing signed/unsigned types. For example: for(size_t i = 0; i < a.length - 1; ++i) This is going to crash when a.length == 0. Better to do this: for(size_t i = 0; i + 1 < a.length; ++i) unsigned math can be difficult, there is no doubt. But we can't just disable it, or disable unsigned conversions. In the same way, using `cast(ulong)` to pass `-1L` to a function that expects a `ulong` results in a de-facto loss of information, because that `-1L` can no longer distinguished from `ulong.max`, despite the fundamental semantic difference between the two. Any time you cast a type, the original type information is lost. But in this case, no bits are lost. In this case, the function is declaring "I don't care what your original type was, I want to use ulong". If it desires to know the original type, it should use a template parameter instead. Note, I have made these mistakes myself, and I understand what you are asking for and why you are asking for it. But these are bugs. The user is telling the compiler to do one thing, and expecting it to do something else. It's not difficult to fix, and in fact, many lines of code are written specifically to take advantage of these rules. This is why we cannot remove them. The benefit is not worth the cost. VRP on steroids would be nice, but I don't think it's as trivial to solve. D's current VRP is actually surprisingly anemic: it doesn't even understand integer comparisons, or the range restrictions implied by the predicate when a certain branch of an `if` statement is taken. Lionello Lunesu made a PR a while back that adds these two features, and it makes the compiler feel a lot smarter. (The PR was not accepted at the time, but I have since revived it: https://github.com/D-Programming-Language/dmd/pull/5229) I'm not compiler-savvy enough to have an opinion on the PR, but I think more sophisticated VRP would be good. -Steve
Re: Checking if a port is listening
On Wednesday, 16 March 2016 at 22:22:15 UTC, Anonymouse wrote: On Wednesday, 16 March 2016 at 20:44:12 UTC, Lucien wrote: Hello, I want to know if a port of an ip address is listening, actually, I've this : http://pastebin.com/pZhm0ujy (checking port 22/ssh) It works, but it took me ~10min to scan 30 addresses. How can reduce the expiration delay ? I don't know if they apply here, but you can lower the send and receive timeouts for the socket. I'm not sure which (or if either) of them you want to tweak. https://dlang.org/library/std/socket/socket_option.html import core.thread; // for .seconds s.setOption(SocketOptionLevel.SOCKET, SNDTIMEO, 10.seconds); s.setOption(SocketOptionLevel.SOCKET, RCVTIMEO, 10.seconds); I guess you could also use a non-blocking socket and decide yourself when enough time has passed to declare it a failed attempt. When it's non-blocking, all adresses have the open 22 open, but it isn't the case.. When I setOption like you said, it's too long. Is there a good technique ? nmap can do it in only ~2 seconds. My current code : import std.process; import std.socket; import core.time; // ... // 32 for the moment for (int i = 1; i < 32; i++) { string ip = "192.168.0."~to!string(i); Socket s = new Socket(AddressFamily.INET, std.socket.SocketType.STREAM, ProtocolType.TCP); s.blocking = false; //s.setOption(SocketOptionLevel.SOCKET, SocketOption.SNDTIMEO, 1.seconds); //s.setOption(SocketOptionLevel.SOCKET, SocketOption.RCVTIMEO, 1.seconds); InternetAddress ia = new InternetAddress(ip, 22); try { s.connect(ia); writeln("\nDONE: ", ip, ":22"); } catch (Exception e) { writeln("\n\nFAIL: ", ip, ":22 is unreachable :\n", e.toString(), "\n"); } s.close(); } // ... -
Re: Destructor order
On Friday, 18 March 2016 at 15:07:53 UTC, Andrea Fontana wrote: On Friday, 18 March 2016 at 15:03:14 UTC, Steven Schveighoffer wrote: On 3/18/16 10:58 AM, Andrea Fontana wrote: On Friday, 18 March 2016 at 14:53:20 UTC, Steven Schveighoffer wrote: On 3/18/16 7:44 AM, Nicholas Wilson wrote: [...] I think technically not true. If you call __dtor directly, it does not recurse. But this is an implementation detail. Why doesn't this print ~B ~A? http://dpaste.dzfl.pl/0bef0a4316b7 It raises a bug on my code because dtor are called in "wrong" order. b holds a ref to a, why a is desctructed before b? Structs are contained completely within the class instance memory block (e.g. the OP's code). Classes are references. They are not destroyed when you destroy the holder, that is left up to the GC, which can destroy in any order. And in fact, it's a programming error to destroy any GC-allocated memory inside your dtor, because it may already be gone! -Steve Not the case. I'm writing a binding for a library. Class A and B wrap c-struct and on d-tor I have to free underlying c object calling c-library destroyer. I'm not destroying any d/GC-allocated object. But of course i have to destroy c object in the correct order... How to? You can't rely on classes to have their destructors call in any particular order. My guess is that the GC is going through and deallocating them in the order they appear on the heap. If you need destructors called in a reliable manner, use structs instead of classes or call destroy on your objects manually.
Re: Checking if a port is listening
see also: https://github.com/rejectedsoftware/vibe.d/issues/1431 api to find an available port On Fri, Mar 18, 2016 at 2:50 AM, Marc Schütz via Digitalmars-d-learn < digitalmars-d-learn@puremagic.com> wrote: > Looking at an strace of nmap, it seems it opens a bunch of sockets, puts > them into non-blocking mode, calls connect on them (which will return > EINPROGRESS), and then uses select(2) to wait for them (in a loop, until > all have either been accepted or rejected). select(2) accepts a timeout > value, so you can determine how long you want to wait. > > Here's an excerpt: > > ... > socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 50 > fcntl(50, F_GETFL) = 0x2 (flags O_RDWR) > fcntl(50, F_SETFL, O_RDWR|O_NONBLOCK) = 0 > setsockopt(50, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 > setsockopt(50, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation > not permitted) > setsockopt(50, SOL_IP, IP_TTL, [-1], 4) = 0 > connect(50, {sa_family=AF_INET, sin_port=htons(32778), > sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in > progress) > socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 51 > fcntl(51, F_GETFL) = 0x2 (flags O_RDWR) > fcntl(51, F_SETFL, O_RDWR|O_NONBLOCK) = 0 > setsockopt(51, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 > setsockopt(51, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation > not permitted) > setsockopt(51, SOL_IP, IP_TTL, [-1], 4) = 0 > connect(51, {sa_family=AF_INET, sin_port=htons(1029), > sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in > progress) > socket(PF_INET, SOCK_STREAM, IPPROTO_TCP) = 52 > fcntl(52, F_GETFL) = 0x2 (flags O_RDWR) > fcntl(52, F_SETFL, O_RDWR|O_NONBLOCK) = 0 > setsockopt(52, SOL_SOCKET, SO_LINGER, {onoff=1, linger=0}, 8) = 0 > setsockopt(52, SOL_SOCKET, SO_BINDTODEVICE, [0], 4) = -1 EPERM (Operation > not permitted) > setsockopt(52, SOL_IP, IP_TTL, [-1], 4) = 0 > connect(52, {sa_family=AF_INET, sin_port=htons(2013), > sin_addr=inet_addr("127.0.0.1")}, 16) = -1 EINPROGRESS (Operation now in > progress) > select(53, [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 > 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 > 51 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 > 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 > 52], [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 > 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 > 52], {0, 0}) = 100 (in [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 > 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 > 47 48 49 50 51 52], out [3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 > 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 > 47 48 49 50 51 52], left {0, 0}) > ... > > I'm pretty sure the setsockopt() calls aren't essential. >