Re: undefined symbol: _D3std7variant...
On Tuesday, 22 October 2019 at 13:07:54 UTC, Andrey wrote: On Tuesday, 22 October 2019 at 12:57:45 UTC, Daniel Kozak wrote: Have you try to clean all caches? Try to remove .dub folder I removed .dub folder but this error appears again. Try the "-allinst" option. It's possibly a bug with speculative template instantiation. "-allinst" deactivates speculation and everything is always instantiated and therefore present in the object files.
Re: crash when using &this in struct constructor
On Wednesday, 18 July 2018 at 11:35:40 UTC, baz wrote: On Wednesday, 18 July 2018 at 11:27:33 UTC, baz@dlang-community wrote: On Monday, 16 July 2018 at 22:21:12 UTC, H. S. Teoh wrote: On Mon, Jul 16, 2018 at 10:08:34PM +, Eric via Digitalmars-d-learn wrote: [...] It's not illegal per se, but a very, very bad idea in general, because in D, structs are expected to be int-like POD values that can be freely copied/moved around by the compiler. More specifically, when structs are passed into functions or returned from functions, they may be moved around. Which means internal pointers will wind up being wrong. [...] Moving doesn't seem to be the issue here. Despite of the ICE, this code shouldn't compile, unless "&this" is allowed at compile-time. still with .init() trick this works, so im' not super sure... NVM the .init() trick. Specs are clear : it's a global so it's evaluated at compile time (https://dlang.org/spec/declaration.html#global_static_init) Example code should not compile.
Re: crash when using &this in struct constructor
On Wednesday, 18 July 2018 at 11:27:33 UTC, baz@dlang-community wrote: On Monday, 16 July 2018 at 22:21:12 UTC, H. S. Teoh wrote: On Mon, Jul 16, 2018 at 10:08:34PM +, Eric via Digitalmars-d-learn wrote: [...] It's not illegal per se, but a very, very bad idea in general, because in D, structs are expected to be int-like POD values that can be freely copied/moved around by the compiler. More specifically, when structs are passed into functions or returned from functions, they may be moved around. Which means internal pointers will wind up being wrong. [...] Moving doesn't seem to be the issue here. Despite of the ICE, this code shouldn't compile, unless "&this" is allowed at compile-time. still with .init() trick this works, so im' not super sure...
Re: Why does this script BSOD-ize windows ?
On Tuesday, 21 July 2015 at 11:08:00 UTC, Rikki Cattermole wrote: On 21/07/2015 10:36 p.m., Baz wrote: [...] I'll summarize what my friend is saying. netsh is potentially going away. Don't use it if you can. Since you are using a localized system it, it may be causing issues for the interface name. Internally to Windows, it does not use the interface names. It uses id's. Oh and most importantly use Windows API not netsh. You should instead be using ConvertInterfaceAliasToLuid[0] to get the UID. There does not appear to be a c-function to disable/enable an interface. Supposedly[1] could be used to enable/disable the card which provides it. Although I would recommend against it. Lastly, this is half good news and half bad news. We have found a way[2] through WMI/COM to enable/disable them. Although I've never gone the path of COM let alone WMI which could be a rather mess to deal with in D. May be easier to use PowerShell for this. Either way, my current theory revolves around Windows kernel + subsystems not liking it toggling so frequently. Friend is a little more conservative on it. [0] https://msdn.microsoft.com/en-us/library/windows/desktop/aa365821(v=vs.85).aspx [1] https://msdn.microsoft.com/en-us/library/windows/hardware/ff552169(v=vs.85).aspx [2] https://msdn.microsoft.com/en-us/library/hh968170(v=vs.85).aspx That's an excellent expertise. However, I'd like to put the emphasis on the fact that it looks like a deterministic way to crash windows, even if to run the script, admin rights are necessary. Now there is also other questions in background: DHCP server, network interface driver even if nowadays they are all in 'user mode', (versus kernel mode).
Re: Why does this script BSOD-ize windows ?
On Tuesday, 21 July 2015 at 10:41:54 UTC, Kagamin wrote: try this: import std.process, std.stdio; import core.thread; import std.random; void main(string[] args) { string on = "netsh interface set interface \"Connexion au réseau local\" Enable"; string off = "netsh interface set interface \"Connexion au réseau local\" Disable"; while(true) { executeShell(on); const t=uniform(2000, 5000); writeln("timeout: ",t); readln(); Thread.sleep(dur!("msecs")(t)); executeShell(off); Thread.sleep(dur!("msecs")(2000)); } } Mmmmh i see, you think that t will be on TLS like this ? But i'll test later, actually the crash happens after a few iterations, eg i run the script, i check it works, i go away, then when i come back and windows restarted and i got "unexepected blue screen" message.
Re: Why does this script BSOD-ize windows ?
On Tuesday, 21 July 2015 at 10:28:27 UTC, Rikki Cattermole wrote: On 21/07/2015 10:14 p.m., Baz wrote: --- import std.process; import core.thread; import std.random; void main(string[] args) { string on = "netsh interface set interface \"Connexion au réseau local\" Enable"; string off = "netsh interface set interface \"Connexion au réseau local\" Disable"; while(true) { executeShell(on); Thread.sleep(dur!("msecs")(uniform(2000, 5000))); executeShell(off); Thread.sleep(dur!("msecs")(2000)); } } --- It's stable if i remove the random time after connecting, otherwise in the current shape it crashes Windows. Don't know why. Any idea ? Note that you can test by replacing the name of my interface by yours ('Connexion au réseau local'). This shouldn't be a D bug, it's reasonable D code. Can you give us the BSOD text? Also OS version + platform would be nice. I've asked a friend who knows Windows better then anybody should and basically relaying this to him FYI. - Window 7 64 bit (up to date) but the program is running in 32 bit, compiled with latest DMD 2.067.1. - involved hardware is onboard REALTEK on Gigabyte H97-HD3, driver up to date. I have not the BSOD error code because I ran this script while away.
Why does this script BSOD-ize windows ?
--- import std.process; import core.thread; import std.random; void main(string[] args) { string on = "netsh interface set interface \"Connexion au réseau local\" Enable"; string off = "netsh interface set interface \"Connexion au réseau local\" Disable"; while(true) { executeShell(on); Thread.sleep(dur!("msecs")(uniform(2000, 5000))); executeShell(off); Thread.sleep(dur!("msecs")(2000)); } } --- It's stable if i remove the random time after connecting, otherwise in the current shape it crashes Windows. Don't know why. Any idea ? Note that you can test by replacing the name of my interface by yours ('Connexion au réseau local').
Re: Virtual value types during compile-time for static type safety, static optimizations and function overloading.
On Friday, 17 July 2015 at 21:20:41 UTC, Tamas wrote: Although this code is fully operational, presents nice api and compile-time optimizations, the extra Struct wrapper is not without runtime penalty. Is there a solution that results the same static optimizations, but has no runtime penalty, i.e. the functions just operates with ints? (At least when compiled) Thanks, Tamas Hi, I don't see the runtime penalities you talk about. I've defined these alias: --- alias abs1 = abs!int; alias abs2 = abs!Positive; alias isqrt1 = isqrt!int; alias isqrt2 = isqrt!Positive; --- and the asm produced for the `Positive` type is clearly faster: ;--- abs1 --- 00402074h enter 000Ch, 00h 00402078h test eax, eax 0040207Ah js 00402081h 0040207Ch mov dword ptr [ebp-0Ch], eax 0040207Fh leave 00402080h ret 00402081h neg eax 00402083h mov dword ptr [ebp-08h], eax 00402086h leave 00402087h ret ; ;--- abs2 (Positive)--- 00402088h enter 0004h, 00h 0040208Ch leave 0040208Dh ret ; ;--- isqrt1 --- 00402090h enter 0008h, 00h 00402094h test eax, eax 00402096h jns 004020CFh 00402098h mov ecx, 00454D60h 0040209Dh push ecx 0040209Eh call 00403410h 004020A3h add esp, 04h 004020A6h push dword ptr [004540A4h] 004020ACh push dword ptr [004540A0h] 004020B2h push dword ptr [004540E4h] 004020B8h push dword ptr [004540E0h] 004020BEh push 001Bh 004020C0h push h 004020C2h call 004035C0h 004020C7h push eax 004020C8h call 00403400h 004020CDh jmp 004020E6h 004020CFh call 0040247Ch 004020D4h fsqrt 004020D6h sub esp, 04h 004020D9h fstp dword ptr [esp] 004020DCh call 00402494h 004020E1h mov dword ptr [ebp-08h], eax 004020E4h leave 004020E5h ret 004020E6h leave 004020E7h ret ; ;--- isqrt2 (Positive)--- 004020E8h enter 0008h, 00h 004020ECh call 00402560h 004020F1h fsqrt 004020F3h sub esp, 04h 004020F6h fstp dword ptr [esp] 004020F9h call 00402494h 004020FEh mov dword ptr [ebp-08h], eax 00402101h leave 00402102h ret ; (dmd win32 bit, -w -wi). Also note that i've tweaked the code to get rid of a few warnings: --- Positive abs(T)(T n) { static if (is(T == Positive)) { return n; } else { if (n >= 0) return Positive(n); else return Positive(-n); } } Positive isqrt(T)(T x) { static if (is(T == Positive)) { return Positive(sqrt(x.to!float).to!int); } else { if (x<0) throw new Exception("no root for negative numbers"); else return Positive(sqrt(x.to!float).to!int); } } ---
Re: Linked variables
On Monday, 13 July 2015 at 22:07:11 UTC, Tanel Tagaväli wrote: Does the standard library have a way to create a forward link between two variables of the same type? One variable is the source and the other is the sink. When the source variable is changed, the sink variable is too. Changing the sink variable has no effect on the source variable. I have already implemented it using std.signals and class templates(https://github.com/TheBlu/lockd/blob/master/source/engine.d), but is there a better way, either in the standard library or a third party library? I have done a data binding system using properties in my D learning library. (https://github.com/BBasile/iz/blob/master/import/iz/properties.d#L610) The problem encountered with data binding is that there must be a signal. So the most obvious way to do that is always more or less based on the observer pattern. But there are other solutions: - check a list of pointer in a thread or in a timer. (foreach target in targets...if target != source... ; Thread.sleep();) - check a list of pointer when a particular message is found within a message queue. (if messages.peek == msg.synchronize_bindings then foreach target in targets...) - similarly, check the target "on idle", for example on windows when no message is dispatched then an idleEvent can be defined. This solution works fine with GUI programs. A very D-ish way to do that would be to use UDA annotations to build the list of targets.
Re: Manually allocate delegate?
On Sunday, 12 July 2015 at 10:39:44 UTC, Tofu Ninja wrote: On Sunday, 12 July 2015 at 10:19:02 UTC, Baz wrote: [...] That is not manually allocating a delegate context, and & in that instance does not even allocate. For delegates to class methods, the context is just the "this" pointer of the object, so the context in that code is just foo, which you still allocated on the gc. The delegate itself (the function pointer and the context pointer) is just allocated on the stack. What I am talking about is the context that implicitly gets allocated when you make a delegate to a nested function. void main(string[] args) { auto d = bar(); d(); } auto bar() { int x = 5; void foo() { writeln(x); } auto d = &foo; // <-- allocates return d; } At least now your Question is clearer and understandable...but sorry goodbye. I don't feel good vibes here. See ya ^^.
Re: Manually allocate delegate?
On Sunday, 12 July 2015 at 09:03:25 UTC, Tofu Ninja wrote: On Sunday, 12 July 2015 at 08:47:37 UTC, ketmar wrote: On Sun, 12 Jul 2015 08:38:00 +, Tofu Ninja wrote: Is it even possible? what do you mean? Sorry, thought the title was enough. The context for a delegate(assuming not a method delegate) is allocated by the GC. Is there any way to allocate the context manually. You can copy a delegate in a GC-free chunk but so far i think that the simple fact to get a delegate with "&" will allocate from the GC. By the way i'd be interested to see the runtime function that creates a delegate. i see nothing in druntime. --- import std.stdio, std.c.stdlib, std.c.string; class Foo { void bar(){writeln("bang");} } void main(string[] args) { auto foo = new Foo; auto dg0 = &foo.bar; auto dg1 = *cast(void delegate()*) malloc(size_t.sizeof * 2); memmove(cast(void*)&dg1, cast(void*)&dg0, size_t.sizeof * 2); dg1(); } ---
Re: Replacement of std.stream
On Sunday, 28 June 2015 at 05:04:48 UTC, DlangLearner wrote: I will convert a Java program into D. The original Java code is based on the class RandomeAccessFile which essentially defines a set of methods for read/write Int/Long/Float/String etc. The module std.stream seems to be a good fit for this job, but in its documentation, it is marked deprecated. So I'd like to know what is the replacement for this module. If I don't use this module, what is the other apporach I should use. Thanks for help. You can use std.stream. There is no candidate to replace it. Even if tomorrow someone comes with one, it has to be reviewed, accepted in std.experimental and after a while it would totally replace the old one. I think it's safe to say that std.stream will exist for at least 2 years in its current shape.
Re: fast way to insert element at index 0
On Tuesday, 23 June 2015 at 13:29:41 UTC, Steven Schveighoffer wrote: On 6/23/15 8:12 AM, Baz wrote: On Tuesday, 23 June 2015 at 11:22:31 UTC, Steven Schveighoffer wrote: [...] according to the C library, memmove handle overlapps, you mismatch with memcpy which does not. The above is not memmove, it's slice assignment, which is specifically illegal for overlaps: $ cat testsliceassign.d void buffer[100]; void main() { buffer[1..$] = buffer[0..$-1]; } $ dmd testsliceassign.d $ ./testsliceassign object.Error@(0): Overlapping arrays in copy: 98 byte(s) overlap of 99 -Steve ok. i was, wrongly, suposing that this operation uses memmove under the hood. btw you forgot to grow the array size, if i dare.
Re: fast way to insert element at index 0
On Tuesday, 23 June 2015 at 11:22:31 UTC, Steven Schveighoffer wrote: On 6/23/15 1:51 AM, jkpl wrote: On Tuesday, 23 June 2015 at 05:16:23 UTC, Assembly wrote: [...] * Option 1/ if most of the time you have to insert at the beginning, then start reading from the end and append to the end, so that the existing block has not to be moved. You just have to add val at the end. * Option 2/ better way to move the whole block (this can be done with memmove too). --- void push(T val) { buffer.length += 1; buffer[1..$] = buffer[0..$-1]; This will fail. http://dlang.org/arrays.html#overlapping-copying I will note, dcollections had a deque, which allowed insertion at the front in O(1) (amortized) time. It basically worked by having 2 arrays front to front. -Steve according to the C library, memmove handle overlapps, you mismatch with memcpy which does not.
Re: Program exited with code -11
On Tuesday, 23 June 2015 at 07:25:05 UTC, Baz wrote: in dmd you have to pass - the .lib/.a files a source I meant "as source", actually. you pass the .lib or .a file without switch as if it's a main source.
Re: Program exited with code -11
On Tuesday, 23 June 2015 at 06:50:28 UTC, Charles Hawkins wrote: On Tuesday, 23 June 2015 at 03:31:37 UTC, weaselcat wrote: On Tuesday, 23 June 2015 at 03:29:14 UTC, Charles Hawkins wrote: Thanks, Adam. I'm coming from OCaml and haven't seen a seg fault in years. Didn't recognize it. :D Hopefully I can figure it out from here. Try to compile with either ldc or gdc and the -g flag, it should give you a backtrace. dmd seems to not like linux wrt backtraces. Thanks. I wish! I haven't had any success in compiling with anything but dub. gdc, dmd, rdmd always give me "module mylib is in file 'mylib.d' which cannot be read" on my "import mylib;" statement. I've tried every permutation of -I and -L that I can think of. It almost appears that one either uses dub for everything or nothing and I'm getting pretty frustrated with it as well. Perhaps I should just go back to old-fashioned make files? in dmd you have to pass - the .lib/.a files a source - the path to the lib source with '-I'. Sometimes when the path is not well indicated you get the error you talk about. This is because the '-I' path must follow carefully the structure of the lib, e.g 'import myLib.package.moduleThis': the '-I' must point to the folder that contains the folder 'myLib'.
Re: Return types of the methods of a struct
On Friday, 19 June 2015 at 13:52:54 UTC, Quentin Ladeveze wrote: On Friday, 19 June 2015 at 13:38:45 UTC, Steven Schveighoffer wrote: Does this work for you, or is there a further expectation? auto asTuple() { return Tuple!(int, "a", ...)(a, b, stringValue);} -Steve In fact, I was trying to use traits to create the tuple automatically and being able to add or remove methods to the struct without breaking the asTuple method. I used allMembers for the name of the methods, but I didn't found anything for their return types or their values. Thank you. when the return type is defined inside the function it's called a 'Voldemort type', see http://www.drdobbs.com/cpp/voldemort-types-in-d/232901591?pgno=2
Re: Return types of the methods of a struct
On Friday, 19 June 2015 at 13:40:01 UTC, Baz wrote: On Friday, 19 June 2015 at 13:27:15 UTC, Quentin Ladeveze wrote: On Friday, 19 June 2015 at 13:26:03 UTC, Steven Schveighoffer wrote: [...] Thank you :) Here is th corrected version : Hi, I have a struct with some methods int it, let's say ``` struct Example{ int a(){ return someValue; } float b(){ return someOtherValue; } string stringValue(){ return c; } } Is there any way to have a asTuple method in this struct that would returns something like : Tuple!(int, "a", float, "b", string, "c") and that will contain the values of the methods of the struct ? Thanks. in the declaration set the return type to 'auto'. Use 'tuple' instead of 'Tuple'. Ah, damn, haven't see Steven Schveighoffer answer while i was writing. cross post. same thing.
Re: Return types of the methods of a struct
On Friday, 19 June 2015 at 13:27:15 UTC, Quentin Ladeveze wrote: On Friday, 19 June 2015 at 13:26:03 UTC, Steven Schveighoffer wrote: On 6/19/15 9:13 AM, Quentin Ladeveze wrote: [...] You can't. The forum is backed by a newsgroup, just post the full corrected version :) -Steve Thank you :) Here is th corrected version : Hi, I have a struct with some methods int it, let's say ``` struct Example{ int a(){ return someValue; } float b(){ return someOtherValue; } string stringValue(){ return c; } } Is there any way to have a asTuple method in this struct that would returns something like : Tuple!(int, "a", float, "b", string, "c") and that will contain the values of the methods of the struct ? Thanks. in the declaration set the return type to 'auto'. Use 'tuple' instead of 'Tuple'.
Re: Casting MapResult
On Monday, 15 June 2015 at 20:10:30 UTC, jmh530 wrote: I suppose I would want whichever has the best performance. Without testing, I'm not sure which one would be better. Thoughts? I had been fighting with the map results because I didn't realize there was an easy way to get just the array. I'm actually not having much luck with your original function (and I tried some variations on it). It just kept outputting the original array without applying the function. I tried it in main also (without being in a function) without much luck either. Right, my bad. This one whould work: --- float[] test(float[] x) { auto result = x.dup; result.each!((ref a) => (a = exp(a))); return result; } ---
Re: Casting MapResult
On Monday, 15 June 2015 at 19:22:31 UTC, jmh530 wrote: On Monday, 15 June 2015 at 19:04:32 UTC, Baz wrote: In addition to the other answers you can use std.algorithm.iteration.each(): --- float[] _exp(float[] x) { auto result = x.dup; result.each!(a => exp(a)); return result; } --- Am I right that the difference is that map is lazy and each is greedy? Does that have any significant performance effects? i think that the OP wants greedy. That's why he had to fight with map results.
Re: Casting MapResult
On Monday, 15 June 2015 at 19:30:08 UTC, Baz wrote: On Monday, 15 June 2015 at 19:22:31 UTC, jmh530 wrote: On Monday, 15 June 2015 at 19:04:32 UTC, Baz wrote: In addition to the other answers you can use std.algorithm.iteration.each(): --- float[] _exp(float[] x) { auto result = x.dup; result.each!(a => exp(a)); return result; } --- Am I right that the difference is that map is lazy and each is greedy? Does that have any significant performance effects? i think that the OP wants greedy. That's why he had to fight with map results. Ah sorry it's you the OP. just get it. So you wanted greedy, didn't you ?
Re: Casting MapResult
On Monday, 15 June 2015 at 15:10:24 UTC, jmh530 wrote: I wrote a simple function to apply map to a float dynamic array auto exp(float[] x) { auto y = x.map!(a => exp(a)); return y; } However, the type of the result is MapResult!(__lambda2, float[]). It seems like some of the things that I might do to a float[], I can't do to this type, like adding them together. So I tried to adjust this by adding in a cast to float[], as in float[] exp(float[] x) { auto y = x.map!(a => exp(a)); cast(float[]) y; return y; } But I get an error that I can't convert MapResult!(__lambda2, float[]) to float[]. So I suppose I have two questions: 1) am I screwing up the cast, or is there no way to convert the MapResult to float[], 2) should I just not bother with map (I wrote an alternate, longer, version that doesn't use map but returns float[] properly). In addition to the other answers you can use std.algorithm.iteration.each(): --- float[] _exp(float[] x) { auto result = x.dup; result.each!(a => exp(a)); return result; } ---
Re: Extract template parameter at runtime?
On Monday, 15 June 2015 at 18:10:34 UTC, Yuxuan Shui wrote: Can is() operate on TypeInfo? yes, you can compare instance of TypeInfo using is or '==' too, using typeid which is returns at run-time the TypeInfo of the argument: --- void main() { assert(typeid(2) == typeid(1)); assert(typeid(2) is typeid(1)); Object a = new Object; Object b = new Object; assert(typeid(b) is typeid(a)); } ---
Re: Process a TypeTuple
On Monday, 15 June 2015 at 03:53:35 UTC, Yuxuan Shui wrote: Is it possible to apply some operation on every member of a TypeTuple, then get the result back? Say I have a TypeTuple of array types, and I want a TypeTuple of their element types, how could I do that? You can do that with std.typetuple.staticMap, example: --- import std.stdio; import std.typetuple; template ElemType(T) { alias ElemType = typeof(T.init[0]); } void main(string[] args) { alias T1 = TypeTuple!(int[],ubyte[]); alias T2 = staticMap!(ElemType, T1); writeln(typeof(T1.init).stringof); writeln(typeof(T2.init).stringof); } --- outputs: --- (int[], ubyte[]) (int, ubyte) --- It's like the higher-order function map() but for type list: http://dlang.org/phobos/std_typetuple.html#.staticMap
Re: dmd and string imports on Windows
On Wednesday, 10 June 2015 at 19:59:17 UTC, Atila Neves wrote: On Linux: foo.d: import std.stdio; void main() { writeln(import("dir/bar.txt")); } dmd -J. foo.d # ok On Windows: Error: file "dir/bar.txt" cannot be found or not in a path specified with -J I tried the obvious buildPath("dir", "bar.txt") instead and now: Error: file "dir\\bar.d" cannot be found or not in a path specified with -J I tried r"dir\bar.txt" and "dir\\bar.txt" and still nothing. What am I supposed to do? Thanks, Atila There is already a bug report for this problem: https://issues.dlang.org/show_bug.cgi?id=14349 Also the manual is not clear about the feature: should a -J path be recursive or not ? http://dlang.org/expression.html#ImportExpression
Re: ImplicitConversionTargets opposite
the line warping on this forum deserve a big slap in the face...
Re: ImplicitConversionTargets opposite
On Thursday, 21 May 2015 at 21:49:55 UTC, Freddy wrote: std.traits has ImplicitConversionTargets. Is there any template that returns the types that can implicty convert to T? You can write something like this: --- import std.stdio; import std.traits; import std.typetuple; void main(string[] args) { template PossibleType(From) { private alias All = TypeTuple!(byte,ubyte,short,ushort,int,uint); private alias Convertible(To) = isImplicitlyConvertible!(From,To); public alias PossibleType = Filter!(Convertible, All); } writeln((PossibleType!int).stringof); writeln((PossibleType!short).stringof); } --- which outputs: --- (int, uint) (short, ushort, int, uint) --- The idea is to reduce the list of all the possible types. It's easy because the high-order functional functions are implemented for the type list. `All` could be a template parameter, and more filled, but to keep the example simple here it's not.
Re: deserialization: creating a class instance without calling constructor
On Thursday, 21 May 2015 at 09:06:59 UTC, Timothee Cour wrote: Can I create an instance of A without calling a constructor? (see below) Use case: for generic deserialiaztion, when the deserialization library encounters a class without default constructor for example (it knows what the fields should be set to, but doesn't know how to construct the object). class A{ int x=2; this(int x){ this.x=x; } } This came up here: https://github.com/msgpack/msgpack-d/issues/54#issuecomment-104136148 I provide some hacky solution for that in that thread but I suspect it's not safe and something is missing. based on this: https://github.com/D-Programming-Language/druntime/blob/6698ee21d4eb00ec2e8c621993359d235618df75/src/rt/lifetime.d#L71 you can create an instance without calling the constructor like this: --- CT construct(CT, A...)(A a) if (is(CT == class)) { auto memory = malloc(typeid(CT).init.length); memory[0 .. typeid(CT).init.length] = typeid(CT).init[]; return cast(CT) memory; } --- actually it only copies the fields with their initial values.
control flow with a functional template ?
who's never had to do this: --- if (comparison) { statement; break; } --- ans then thought it's a pity to open/closes the braces just for a simple statement. Would it be possible to have a template to simplify this to: --- if (comparison) Break!(expression); --- or even at the language level: --- if (comparison) break(expression); if (comparison) continue(expression); --- so far it looks like it's only possible using a string mixin, which is a quite unelegant solution (because for example you loose the IDE completion while writting the statement): --- auto Break(string statement) { return format("{%s;break;}", statement); } // unelegant but works... if (condition) mixin("myVar = 8".Break); if (condition) mixin(q{myVar = 8}.Break); --- Any other solution ?
Re: mscoff x86 invalid pointers
On Sunday, 10 May 2015 at 12:20:39 UTC, Etienne Cimon wrote: On 2015-05-10 03:54, Baz wrote: On Sunday, 10 May 2015 at 04:16:45 UTC, Etienne Cimon wrote: On 2015-05-09 05:44, Baz wrote: On Saturday, 9 May 2015 at 06:21:11 UTC, extrawurst wrote: On Saturday, 9 May 2015 at 00:16:28 UTC, Etienne wrote: I'm trying to compile a library that I think used to work with -m32mscoff flag before I reset my machine configurations. https://github.com/etcimon/memutils Whenever I run `dub test --config=32mscoff` it gives me an assertion failure, which is a global variable that already has a pointer value for some reason.. I'm wondering if someone here could test this out on their machine with v2.067.1? There's no reason why this shouldn't work, it runs fine in DMD32/optlink and DMD64/mscoff, just not in DMD32/mscoff. Thanks! you can always use travis-ci to do such a job for you ;) doesn't -m32mscoff recquire phobos to be compiled as COFF too ? I think that travis uses the official releases (win32 releases have phobos as OMF) so he can't run the unittests like that... The dark side of the story is that you have to recompile phobos by hand with -m32mscoff...I'm not even sure that there is a option for this in the win32.mak... Meh, I ended up upgrading to 2.068 and everything went well. I clearly remember 2.067.1 working but spent a whole day recompiling druntime/phobos COFF versions in every configuration possible and never got it working again Could you tell me the way to compile druntime & phobos 32bit COFF ? Would you have some custom win32.mak to share ? Thx. I edited win64.mak, you need to change it to MODEL=32mscoff and remove all occurence of amd64/ in the file (there are 3), for both druntime and phobos. Save this to win32mscoff.mak You need to place the phobos32mscoff.lib into dmd2/windows/lib32mscoff/ (the folder doesn't exist) Obviously there is no config for gcc-cpp...thx anyway for the tips.
Re: mscoff x86 invalid pointers
On Sunday, 10 May 2015 at 04:16:45 UTC, Etienne Cimon wrote: On 2015-05-09 05:44, Baz wrote: On Saturday, 9 May 2015 at 06:21:11 UTC, extrawurst wrote: On Saturday, 9 May 2015 at 00:16:28 UTC, Etienne wrote: I'm trying to compile a library that I think used to work with -m32mscoff flag before I reset my machine configurations. https://github.com/etcimon/memutils Whenever I run `dub test --config=32mscoff` it gives me an assertion failure, which is a global variable that already has a pointer value for some reason.. I'm wondering if someone here could test this out on their machine with v2.067.1? There's no reason why this shouldn't work, it runs fine in DMD32/optlink and DMD64/mscoff, just not in DMD32/mscoff. Thanks! you can always use travis-ci to do such a job for you ;) doesn't -m32mscoff recquire phobos to be compiled as COFF too ? I think that travis uses the official releases (win32 releases have phobos as OMF) so he can't run the unittests like that... The dark side of the story is that you have to recompile phobos by hand with -m32mscoff...I'm not even sure that there is a option for this in the win32.mak... Meh, I ended up upgrading to 2.068 and everything went well. I clearly remember 2.067.1 working but spent a whole day recompiling druntime/phobos COFF versions in every configuration possible and never got it working again Could you tell me the way to compile druntime & phobos 32bit COFF ? Would you have some custom win32.mak to share ? Thx.
Re: Spawning a console in Windows (similar to forkpty on linux)
On Saturday, 9 May 2015 at 13:01:27 UTC, wobbles wrote: On Saturday, 9 May 2015 at 13:00:01 UTC, wobbles wrote: On Saturday, 9 May 2015 at 12:48:16 UTC, Kagamin wrote: On Saturday, 9 May 2015 at 12:26:58 UTC, wobbles wrote: What I mean is, if the cmd.exe hasnt flushed it's output, my cmdPid.stdout.readln (or whatever) will block until it does. I dont really want this. Are you sure cmd is the culprit? It should have sensible buffering. Also do you want just a console window or also a command interpreter attached to it? My windows knowledge isnt marvelous, but I believe I'll need the interpreter attached. Just as an example of running cmd through std.process, running this on my system: auto pipes = pipeShell("cmd.exe"); write(pipes.stdout.readln); write(pipes.stdout.readln); write(pipes.stdout.readln); return; will print ` Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved. ` and then exits. However, adding another "write" line before the return; will cause the program to hang there, waiting for the cmd.exe process to flush it's next line. On Linux, I'm able to edit a file descriptor after I've created it to tell it to read/write asynchronously, I cant seem to find anything similar on windows however. Spoke too soon. Looks like this is what I need: http://www.codeproject.com/Articles/534/An-Introduction-to-Processes-Asynchronous-Process You need a loop that run until the PID is invalid. something like: --- while(true) { Thread.sleep(dur!"msecs"(10)); // operation on i/o streams write(pipes.stdout.readln); if (pipes.pid.tryWait.terminated) break; } --- also note that the piped process needs its whole output to be read before it terminates, otherwise it can stick (never ends).
Re: mscoff x86 invalid pointers
On Saturday, 9 May 2015 at 06:21:11 UTC, extrawurst wrote: On Saturday, 9 May 2015 at 00:16:28 UTC, Etienne wrote: I'm trying to compile a library that I think used to work with -m32mscoff flag before I reset my machine configurations. https://github.com/etcimon/memutils Whenever I run `dub test --config=32mscoff` it gives me an assertion failure, which is a global variable that already has a pointer value for some reason.. I'm wondering if someone here could test this out on their machine with v2.067.1? There's no reason why this shouldn't work, it runs fine in DMD32/optlink and DMD64/mscoff, just not in DMD32/mscoff. Thanks! you can always use travis-ci to do such a job for you ;) doesn't -m32mscoff recquire phobos to be compiled as COFF too ? I think that travis uses the official releases (win32 releases have phobos as OMF) so he can't run the unittests like that... The dark side of the story is that you have to recompile phobos by hand with -m32mscoff...I'm not even sure that there is a option for this in the win32.mak...
Re: Bitfield-style enum to strings?
On Thursday, 7 May 2015 at 17:41:10 UTC, Nick Sabalausky wrote: Assuming a plain old bitfield-style enum like: enum Foo { optionA = 1<<0; optionB = 1<<1; optionC = 1<<2; optionD = 1<<3; optionE = 1<<4; } Does a function already exist somewhere to take an instance of Foo and get a list of the switch names as strings? Something kinda like: Foo fooVar = Foo.optionB | Foo.optionD; assert( DOES_THIS_FUNC_EXIST(fooVar) .equals(["optionB", "optionD"]) ); Seems entirely feasible, although my traits-fu is a bit rusty. Hi, i have a specialized struct for "bit sets" that handles the string representation: https://github.com/BBasile/enumset/blob/master/import/enumset.d#L242 however it's not std. Building the string is easy (cf toString()) but if it can help...
Re: Efficiently passing structs
On Monday, 4 May 2015 at 01:58:12 UTC, bitwise wrote: The documentation doesn't say anything about "in" being a reference, but it doesn't say that "out" parameters are references either, even though it's usage in the example clearly shows that it is. Thanks, Bit http://dlang.org/function.html#parameters it's specified in http://dlang.org/abi.html (at the bottom): "out and ref are passed as pointers". The logic seems to be that if it's not specified then it's copied. Maybe `const ref` is what you're looking for...passed as pointer but the compiler will prevent writing the parameter, though it's still possible to take the address and to modify the param if the function is not @safe.
why std.process.Pid & std.process.Environment are classes ?
In std.process, the following declarations: - final class Pid - abstract final class environment could be struct, couldn't they ? Any particular reason behind this choice ?
Re: Readonly-to-outside variable
On Tuesday, 28 April 2015 at 19:30:06 UTC, tcak wrote: Is there any way to define a variable or an attribute as read-only without defining a getter function/method for it? Thoughts behind this question are: 1. For every reading, another function call process for CPU while it could directly read the value from memory. 2. Repetition of same name for variable and getVariableName. (Some might not agree with this but I like the code when it looks nice.) an quick attempt: --- union ReadOnlyOutside(T) { alias value this; private T _value; public const T value; } --- when you declare such a variable inside a struct or a class, the code located in another module won't be able to modify the value: module1: --- struct Foo { ReadOnlyOutside!size_t roField; } --- module2: void something(ref Foo foo) { writeln(foo.roField); // OK writeln(foo.roField.value); // OK foo.roField = 1; // FAIL foo.roField.value = 1,// FAIL (because const). foo.roField._value = 1,// FAIL (because not visible). }
Re: std.json questions
On Saturday, 25 April 2015 at 09:56:25 UTC, tired_eyes wrote: I think this is ugly and clunky approach, what is the beautiful one? What you clearly need is a serializer: look at these: http://wiki.dlang.org/Libraries_and_Frameworks#Serialization and also: https://github.com/search?utf8=✓&q=serializer+language%3AD&type=Repositories&ref=searchresults some of them might have an API to save load an object or a struct in a single call.
Re: Weird link error
On Monday, 20 April 2015 at 17:02:18 UTC, CodeSun wrote: And where I can find the D symbol definition, because information like ‘_D2tt2Ti12__T3getTAyaZ3getMFAyaZAya’ makes me really confused. --- import std.demangle; auto friendlySymbol = demangle("_D2tt2Ti12__T3getTAyaZ3getMFAyaZAya"); ---
why cant function parameters be grouped by type ?
Hi, while variable declarations work in list: uint a,b,c; function parameters declarations don't: void foo(uint a,b,c); Because of this, function declarations are sometimes super-wide. (despite of the fact that: http://www.brainyquote.com/quotes/quotes/a/alanperlis177279.html) In the previous example, we could imagine that once a type defined, it'd valid until a new one appears (until a "redefinition" / an "override"). Is there anything in the grammar that prevents this syntax ? Thx.
Re: Specify an entire directory tree for string imports
On Monday, 30 March 2015 at 02:13:22 UTC, Alex Parrill wrote: I have a directory structure like this: . | test.d | \---test | test1.txt | \---subfolder test2.txt I am running test.d using this command: rdmd -Jtest test.d I can do `import("test1.txt")` from test.d successfully, however, `import("subfolder/test2.txt")` fails with the error `file "subfolder/test2.txt" cannot be found or not in a path specified with -J` I'm guessing that the -J option doesn't operate recursively, and that I'm not allowed to import files from `test/subfolder`. Is there a way to make the entire `test` directory tree available for string imports? It's a DMD Windows bug. It's just been reported 2 days ago: https://issues.dlang.org/show_bug.cgi?id=14349 so nothing wrong from you side.
Re: Format double in decimal notation without trailing zeros after the decimal point
On Friday, 27 March 2015 at 15:02:19 UTC, akaDemik wrote: The task seemed very simple. But I'm stuck. I want to: 1234567890123.0 to "1234567890123" 1.23 to "1.23" 1.234567 to "1.2346". With format string "%.4f" i get "1.2300" for 1.23. With "%g" i get "1.23456789e+12" for "1234567890123.0". I can not believe that it is not implemented. What did I miss? such a format specifier does not exist. [.number] means the minimal digits to display, so there is always at least `number` digits. In your three examples, there is no common way to format them, you have to write you own helper: struct YourExoticFormater { private float _value; alias _value this; string toString() { // here you test the number and you choose how to diplay it. // for example if frac() returns 0 you return the string repr // esentation of the the integral part, etc... // this will work with to!string(), probably format %s (?), and the // write() functions family. } }
Re: Associative Array of Const Objects?
On Friday, 27 March 2015 at 21:33:19 UTC, bitwise wrote: class Test{} void main() { const(Test)[string] tests; tests["test"] = new Test(); } This code used to work, but after upgrading to dmd 2.067, it no longer does. --Error: cannot modify const expression tests["test"] How do I insert an item into an associative array of const objects? Generally speaking, you can insert an item in a constructor: --- class Test{} const (Test)[string] tests; static this() { tests["test"] = new Test(); } class Bar { immutable (Test)[string] tests2; this() { this.tests2["test"] = new Test(); } } void main() { auto bar = new Bar; } --- The same problem already existed before 2.067 for AA with strings as value (string[string]), since they are immutable.
Re: PrimitiveRef ?
On Monday, 23 March 2015 at 16:58:49 UTC, Andre wrote: Hi, " (needed for specifying reference behavior in a type tuple). I need exactly that behavior. I am currently unsure whether it is possible at all to have such a construct which works at user side exactly like a boolean (booleans can be assigned and directly compared with ==) but internally are pointers... (The coding does not compile) Kind regards André struct PrimitiveRef(T) { private T* _value; alias _value this; void opAssign(T v) { _value = v; } } alias BoolRef = PrimitiveRef!bool; void test(BoolRef b) { b = true; } void main() { BoolRef b = false; test(b); assert(b == true); } even if the code would compile you'd get an AV because _value is null. Then when you initalize b with false this could not work because false is not a a pointer to a bool. struct PrimitiveRef(T) { private T* _value; alias _value this; void opAssign(T v) { *_value = v; } } alias BoolRef = PrimitiveRef!bool; void test(BoolRef b) { b = true; } bool btarget; void main() { BoolRef b; b._value = &btarget; test(b); assert(*b == true); } I don't know where you've read this, but i 'm interseted too. Maybe it's an ABI thing: since the only member is a reference (so `size_t.sizeof` bytes) the `struct` can be passed in a register during the function call, instead of being copied on the stack... --- void foo(BoolRef aRef) { // x86: aRef is in EAX // X86_64 aRef is in RAX } --- What is the source of "I read that if a structure only contains a reference, it will behave like a reference type in function calls" ?
Re: Text UI for D?
On Friday, 20 March 2015 at 10:29:45 UTC, DLearner wrote: Does D have a recommended package for this - like (n)curses for C? I cannot recommend it because i've just found the package, it like Pascal turbo vision but in D. https://github.com/bbodi/dvision A few years ago someine else started a similar project but i can't found the link, it's too old.
Re: chaining splitters
On Wednesday, 11 March 2015 at 00:00:39 UTC, dnoob wrote: Hello, I am parsing some text and I have the following; string text = "some very long text"; foreach(line; splitter(text, [13, 10])) { foreach(record; splitter(line, '*')) { foreach(field; splitter(record, '=')) { foreach(value; splitter(field, ',')) { // do something... } } } } I know there is a better way to do that but I'm a total D noob. Thanks! For this kind of things i tend to write a small lexer because you have a good control on what to do where to do it and the finally the pattern is quite simple: --- // empty/front/popFront for build-in arrays import std.array; string identifier; while (!text.empty) { auto current = text.front; // // test whites/memorize identifier/resetidentifier // test punctuation/reset identifier... // test keywords/reset identifier... identifier ~= current; text.popFront; } ---
Re: What's the rationale here? alias this and function arguments
On Tuesday, 10 March 2015 at 10:27:14 UTC, John Colvin wrote: struct S { int a; this(T)(T v) { this = v; } void foo(T)(T v) { import std.conv : to; a = v.to!int; } alias foo this; } void bar(S s){} void main() { S s0; s0 = "3"; //OK S s = "3"; //OK bar("3"); //Not OK } It would seem logical that the last one would work as well. What's the reasoning behind this? Do you think that the parameter should be automatically created from the argument ? Is this kind of thing even possible in another context ? Your alias looks more like an ```opCall()```. To my eyes the strange thing is that if you add the following statement at the end of you sample: --- s(0); --- DMD outputs: ```Error: cannot resolve type for s.foo(T)(T v)```
Re: string-int[] array
On Sunday, 8 March 2015 at 18:54:43 UTC, Meta wrote: On Sunday, 8 March 2015 at 18:38:02 UTC, Dennis Ritchie wrote: On Sunday, 8 March 2015 at 18:18:15 UTC, Baz wrote: import std.stdio; import std.typecons; alias T = Tuple!(string, int); void main(string[] args) { T[] tarr; tarr ~= T("a",65); tarr ~= T("b",66); writeln(tarr); } [Tuple!(string, int)("a", 65), Tuple!(string, int)("b", 66)] Thanks, will do. It might be better to use std.variant.Algebraic. An array of tuples is wasteful of memory as you only need one or the other. import std.variant; alias IntOrStr = Algebraic!(int, string); IntOrStr[] makeIntOrStrArray(T...)(T vals) { import std.algorithm; import std.array; auto result = new IntOrStr[](T.length); foreach (i, val; vals) { result[i] = IntOrStr(val); } return result; } void main() { IntOrStr[] arr = makeIntOrStrArray(4, "five"); } Yes, but the tuple is used here because i misunderstood the question, cf my own answer to my first answer, anyway, never mind.
Re: string-int[] array
On Sunday, 8 March 2015 at 18:18:15 UTC, Baz wrote: On Sunday, 8 March 2015 at 18:05:33 UTC, Dennis Ritchie wrote: Is it possible to create such an array in which you can store strings and numbers at the same time? string-int[] array = [4, "five"]; using an array of tuple it works: import std.stdio; import std.typecons; alias T = Tuple!(string, int); void main(string[] args) { T[] tarr; tarr ~= T("a",65); tarr ~= T("b",66); writeln(tarr); } [Tuple!(string, int)("a", 65), Tuple!(string, int)("b", 66)] mmmh maybe off-topic, you probably don't what pairs but either a string representing an int or an int, do you ? If so then an array of union ?
Re: string-int[] array
On Sunday, 8 March 2015 at 18:05:33 UTC, Dennis Ritchie wrote: Is it possible to create such an array in which you can store strings and numbers at the same time? string-int[] array = [4, "five"]; using an array of tuple it works: import std.stdio; import std.typecons; alias T = Tuple!(string, int); void main(string[] args) { T[] tarr; tarr ~= T("a",65); tarr ~= T("b",66); writeln(tarr); } [Tuple!(string, int)("a", 65), Tuple!(string, int)("b", 66)]
UFCS on template alias ?
Is this a normal behaviour ? --- void main() { import std.algorithm; auto list = [0,1,2,3]; alias poly = map; list.poly!(a => a + a); } --- outputs: "Error: no property 'poly' for type 'int[]'"
Re: const member function
On Saturday, 21 February 2015 at 07:31:19 UTC, rumbu wrote: On Saturday, 21 February 2015 at 07:01:12 UTC, Baz wrote: --- class S { private SomeType cache; public const(SomeType) SomeProp() @property { if (cache is null) cache = SomeExpensiveOperation(); return cache; } } --- the result of the getter will be read-only My intention is not to have a read-only getter, I want to call SomeProp on a const object: class S { private int cache = -1; private int SomeExpensiveOp() { return 12345; } public @property const(int) SomeProp() { if (cache = -1) cache = SomeExpensiveOp(); return cache; } } unittest { const(S) s = new S(); auto i = s.SomeProp; //mutable method S.SomeProp is not callable using a const object } right, i have not carefully read the body of the Q. my bad.
Re: const member function
--- class S { private SomeType cache; public const(SomeType) SomeProp() @property { if (cache is null) cache = SomeExpensiveOperation(); return cache; } } --- the result of the getter will be read-only
what is the offical way to handle multiple list in map() ?
while learning the map function, i've landed on this wikipedia page(http://en.wikipedia.org/wiki/Map_(higher-order_function)). For each language there is a column about handing multiple list, i thought it could be a good idea to see how D handle this: is this the official way ? --- auto fruits = ["apple", "banana", "orange"][]; auto vegies = ["grass", "salad"][]; // 1 list auto yougonna = map!(a => "eat " ~ a)(fruits); // 2 lists auto youreallygonna = map!( `map!(a => "eat " ~ a)(a)` )([fruits, vegies]); writeln(yougonna.stringof, yougonna); writeln(youreallygonna.stringof, youreallygonna); --- which outputs: --- yougonna["eat apple", "eat banana", "eat orange"] youreallygonna[["eat apple", "eat banana", "eat orange"], ["eat grass", "eat salad"]] --- The doc doesn't specify anything about multiple lists.
Re: Wrong overload resolution
On Sunday, 15 February 2015 at 23:48:50 UTC, rumbu wrote: This problem appears only if one of the parameters is an interface. Without it or using any other type as a second parameter instead of the interface, it compiles. Also it compiles if the passed interface is null. The example below uses short/ushort, but I found the same behaviour for any combination of integral types of the same bitsize (byte/ubyte/char, ushort/short/wchar, int/uint/dchar, long/ulong) D 2.066.1 interface I {} class C: I {} void func(ushort s, I i) { writeln("ushort overload"); } void func(short s, I i) { writeln("short overload"); } void call(short s) { C c = new C(); I d = new C(); func(s, c); // ERROR see below //but these are ok func(s, cast(I)c) //ok func(s, d) //ok func(s, null) //ok } main.func called with argument types (short, C) matches both: main.func(short s, I i) main.func(ushort s, I i) it's intereting to note that if func() are rewritten: --- void func(ref ushort s, I i){} void func(ref short s, I i){} --- or even --- void func(const ref ushort s, I i){} void func(const ref short s, I i){} --- the problem doesn't happend.
Re: Is there an object on given memory address?
On Thursday, 12 February 2015 at 11:14:05 UTC, tcak wrote: Or send a hash of the object along with the memory address, then query the GC wether the memory is still allocated. This part sounds interesnting. How does that GC querying thing works exactly? std [doc][1] is your friend but if you need guidance. --- import core.memory : GC; bool is_gc_allocated = addrOf(ptd) != null; --- [1]: http://dlang.org/phobos/core_memory.html#.GC.addrOf
Re: Wrong pointer calculation without casting on struct
On Friday, 6 February 2015 at 04:10:08 UTC, tcak wrote: On Friday, 6 February 2015 at 03:59:51 UTC, tcak wrote: I am on 64-bit Linux. I defined a struct that it 8 bytes in total. align(1) struct MessageBase{ align(1): ushort qc; ushort wc; ushort id; ushort contentLength; void[0] content; } I defined a function in this struct that tries to set a pointer to "contentLength" field. writeln( "Without: ", (&this + id.offsetof) ); writeln( "With : ", (cast(size_t)&this + id.offsetof) ); Results: Without: 774F5030 With : 140737342558228 0x774F5030 => 140737342558256 As it is seen, there is 28 bytes of difference between them. What is this behaviour exactly? By the way, writeln("Base Normal: ", &this); writeln("Base Cast : ", cast(size_t)&this); Result: Base Normal: 774F5010 Base Cast : 140737342558224 0x774F5010 => 140737342558224 These are same. So, the issue is about addition process. I've tried this; import std.stdio; struct MessageBase{ align(1): ushort qc; ushort wc; ushort id; ushort contentLength; void[0] content; void a(){ writefln("%.8X",(cast(void*)&this + id.offsetof)); writefln("%.8X",(cast(size_t)&this + id.offsetof)); } } void main() { MessageBase mb; mb.a; } and got the same value for both. Your problem is: typeof(&this).stringof is "MessageBase*" so with ptr arithmetic when you add 1 you actually shift by 1 * MessageBase.sizeof. typeof(cast(void*)&this) is "void*" so with ptr arithmetic you shift by a certain number of bytes.
Re: Virtual functions and inheritance
even more weird: --- module test; import std.conv; interface Meh{ final string typeName() {return to!string(this);} } class Parent : Meh {} class Child : Parent {} void main() { auto p = new Parent; auto c = new Child; assert(p.typeName == __MODULE__ ~ ".Parent"); assert(c.typeName == __MODULE__ ~ ".Child"); } ---
Re: Virtual functions and inheritance
On Tuesday, 27 January 2015 at 04:38:59 UTC, David Monagle wrote: Hi guys, I'm a former C++ developer and really enjoying working with D now. I have a question that I hope some of you may be able to answer. class Parent { @property string typeName() { return typeof(this).stringof; } } class Child : Parent { } void main() { auto p = new Parent; auto c = new Child; assert(p.typeName == "Parent"); assert(p.typeName == "Child"); } I'm looking for an explanation as to why this doesn't work, then a suggestion for how I may achieve child classes being able to generate a string description of their own type, without redefining the typeName property on each child. (I'm currently solving this with a mixin, but I was hoping for a better solution. I'm assuming it doesn't work because either typeof(this) or .stringof is evaluated at compile time? This is almost the same code as written initially, let somone explain why the hell this is working: --- module test; import std.conv; class Parent { @property final string typeName() { return to!string(this); } } class Child : Parent { } void main() { auto p = new Parent; auto c = new Child; assert(p.typeName == __MODULE__ ~ ".Parent"); assert(c.typeName == __MODULE__ ~ ".Child"); } ---
Re: How to copy object of class A to another object of class B?
On Wednesday, 28 January 2015 at 14:35:58 UTC, zhmt wrote: Anybody help? __Traits functions are evaluated at compile time so it's not as simple. The best you can do is to generate a string to mixin based on the aggragate members. here i have an example of how you can iterate through the members: https://github.com/BBasile/Iz/blob/master/import/iz/traits.d#L18 Writing an opAssign() operator will be as fast, you just need to remember to keep it in sync with the classe members. You could also generate the struct programmatically, based on the classes declaration.
Re: Virtual functions and inheritance
On Tuesday, 27 January 2015 at 08:19:46 UTC, Daniel Kozák wrote: You can use this T: class Parent { @property string typeName(this T)() { return T.stringof; } } class Child : Parent { } void main() { auto p = new Parent; auto c = new Child; assert(p.typeName == "Parent"); assert(c.typeName == "Child"); } Could 'this T' be used for a static constructor ? - class Bar { static T construct(this T, A...)(A a) { return new T(a); } } doesn't work. And similarly to the the orginal post: - class Bar { static typeof(this) construct(A...)(A a) { return new typeof(this)(a); } } class Foo: Bar{} Foo foo= Foo.construct; // fail construct() won't be redefined in the Bar descendants.
Re: Some array casts
On Wednesday, 21 January 2015 at 14:31:15 UTC, bearophile wrote: Currently this is accepted: int[2] m = cast(int[2])[1, 2]; But Kenji suggests that the cast from int[] to int[2][1] should not be accepted. Do you know why? Reference: https://issues.dlang.org/show_bug.cgi?id=7514 Bye and thank you, bearophile This is because of the .sizeof property, for example: void main(string[] args) { int[3] m = cast(int[3])[1, 2, 3]; writeln(m.sizeof); writeln([1, 2, 3].sizeof); } outputs 12 / 8 Your previous example is corner case, it's 8/8 in both.
Re: Some array casts
On Wednesday, 21 January 2015 at 14:41:48 UTC, Baz wrote: On Wednesday, 21 January 2015 at 14:31:15 UTC, bearophile wrote: Currently this is accepted: int[2] m = cast(int[2])[1, 2]; But Kenji suggests that the cast from int[] to int[2][1] should not be accepted. Do you know why? Reference: https://issues.dlang.org/show_bug.cgi?id=7514 Bye and thank you, bearophile This is because of the .sizeof property, for example: void main(string[] args) { int[3] m = cast(int[3])[1, 2, 3]; writeln(m.sizeof); writeln([1, 2, 3].sizeof); } outputs 12 / 8 Your previous example is corner case, it's 8/8 in both. with -m32 of course.
Re: idiomatic D: what to use instead of pointers in constructing a tree data structure?
On Wednesday, 7 January 2015 at 15:04:24 UTC, Paulo Pinto wrote: On Wednesday, 7 January 2015 at 15:02:34 UTC, Laeeth Isharc wrote: Not true. If you're using a tree structure, you *should* use pointers. Unless you're using classes, which are by-reference, in which case you can just use the class as-is. :-) Thanks v much. I just came to that realization also when I stepped away. class node { string name; node ref; } what's wrong with the code above ? i get an error no identifier for declarator node. (I have not used classes much, since structs often seem to be enough for what I need to do mostly). ref is a reserved keyword. -- Paulo this conversation is so funny: well what's wrong with this . It's a keyword... Aa Ha ha ha ha , rol. Seriously, is it so complicated to use a D editor ? I mean with syntax color...
Re: How to prevent sensitive information is displayed when the extension 'exe' is modified to 'txt' on windows?
On Wednesday, 7 January 2015 at 17:57:18 UTC, H. S. Teoh via Digitalmars-d-learn wrote: On Wed, Jan 07, 2015 at 05:16:13PM +, FrankLike via Digitalmars-d-learn wrote: >To hide the infos you can also (I've seen people say that you >can use >a packer) encrypt the strings and decode them at run-time (e.g >base64, a simple XOR, etc) and use the import() idiom: >https://p0nce.github.io/d-idioms/#Embed-a-dynamic-library-in-an-executable >to import the compiled things. > >I've made a simple software in this spirit, even if it's not >made to >encrypt/hide (it's more globally a resource manager), it can >be used >to hide the strings since it encodes in base 85 and base 64: >https://github.com/BBasile/Resource.d Good job. Thank you. Note that these encryption/decryption schemes can only serve as deterrent to the casual user, they do not prevent a determined attacker from decrypting the sensitive data. As long as the data is decrypted on the user's machine, the user can read it. For example, an encrypted executable has to decrypt itself at some point, since otherwise it couldn't run on the user's machine in the first place. So, in theory, all the user has to do is to run it inside a VM or a debugger and stop it immediately after the point where it decrypts itself, and the code will be in cleartext for all to read. Similarly, if a piece of sensitive data is decrypted by the program at some point during execution, a user can just run it inside a debugger and break it immediately past the point where the data is decrypted, and just read off the cleartext. Basically, the only way to be 100% safe with sensitive data that the user shouldn't read, is to never transmit said data to the user's machine in the first place. If the program needs to read something from a database, and the database has a password, don't store the password anywhere in any form on the user's computer (this includes inside the executable). Instead, use a database server that the program talks to; the server knows the DB password, the program doesn't (and shouldn't). T You're right, it works against "static analysis" (disassembly) but in a debugger, the attacker can track the content of the stack because before being used, the data **have** to be decripted somewhere, so before a CALL he detects the data put as parameter, then he tries to find where they are generated (e.g put a breakpoint on each dword ... or by putting a breakpoint on memory access for a particular address). As said before by other people in this topic, you cant do anything againt someone who really wants to get the thing, but you can reduce the amount of people able to to do it.
Re: How to prevent sensitive information is displayed when the extension 'exe' is modified to 'txt' on windows?
On Tuesday, 6 January 2015 at 17:15:28 UTC, FrankLike wrote: How to prevent sensitive information is displayed when the extension 'exe' is modified to 'txt' on windows? If you build a exe ,such as which can get Data from DataBase,when you modify the exe's extension to 'txt', and you open it by notepad.exe (on windows),you will find the info,it's important for me,so how to stop the info to display ? Notepad to display the infos ? are you serious ? Have you ever heard about IDA and more globally about the disassemblers ? In a disassembler you always have a "strings" display, in IDA you have the "Names"... which are basically like "strings" with infos about where they are used. It will blow your mind... To hide the infos you can also (I've seen people say that you can use a packer) encrypt the strings and decode them at run-time (e.g base64, a simple XOR, etc) and use the import() idiom: https://p0nce.github.io/d-idioms/#Embed-a-dynamic-library-in-an-executable to import the compiled things. I've made a simple software in this spirit, even if it's not made to encrypt/hide (it's more globally a resource manager), it can be used to hide the strings since it encodes in base 85 and base 64: https://github.com/BBasile/Resource.d
Re: getting all children classes in program
On Saturday, 3 January 2015 at 15:00:53 UTC, Ondra wrote: I'm not sure if there's a way around that other than to add some code in the class to register itself. You could use a static constructor that adds itself to a list. Or, to give each class a shared ID, you could add a static member which returns some variation of its typeinfo. In fact, typeid(any_class) returns a unique identifier for each class (an instance of TypeInfo), maybe you can use it directly. Hi Adam, static this is probably way to go, I wanted to avoid this solution because if it leads to copy-pasting code to every child. I need to have IDs small like 8bits, co I probably can't use typeid... Thank you for answer. Knowing that someting cannot be done is better than spend on this another few hour. Great book btw. Ondra Hello, here is another solution: a class ID is generated lazily, when queried It does not recquire a static constructor. module runnable; static string[] IDs; ptrdiff_t getClassID(ClassType)() if (is(ClassType == class)) { import std.algorithm; auto classTypeString = ClassType.stringof; ptrdiff_t result = countUntil(IDs, classTypeString); if (result == -1) { IDs ~= classTypeString; result = IDs.length -1; } return result; } void main(string[] args) { class A{} class B{} class C{} class D{} assert(getClassID!A == 0); assert(getClassID!B == 1); assert(getClassID!C == 2); assert(getClassID!D == 3); assert(getClassID!C == 2); assert(getClassID!B == 1); assert(getClassID!A == 0); } Hoping it matches to your needs.
Re: readln with buffer fails
On Wednesday, 29 October 2014 at 21:14:17 UTC, dcrepid wrote: I have this simple code: int main() { import std.stdio; char[4096] Input; readln(Input); //readln!(char)(Input); // also fails return 0; } I get these messages during compilation: test.d(39): Error: template std.stdio.readln cannot deduce function from argument types !()(char[4096]), candidates are: src\phobos\std\stdio.d(2818): std.stdio.readln(S = string)(dchar terminator = '\x0a') if (isSomeString!S) src\phobos\std\stdio.d(2851): std.stdio.readln(C)(ref C[] buf, dchar terminator = '\x0a') if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum)) src\phobos\std\stdio.d(2858): std.stdio.readln(C, R)(ref C[] buf, R terminator) if (isSomeChar!C && is(Unqual!C == C) && !is(C == enum) && isBidirectionalRange!R && is(typeof(terminator.front == (dchar).init))) Now, I'm used to 'buffer' meaning one thing, but here it seems that buffer means something more akin to a 'sink' object, or a forced dynamic array type? Is there some way I can avoid dynamic allocations? Thanks! try this instead -- module runnable; import std.stdio; void main(string args[]) { char[] Input; Input.length = 4096; readln(Input); } -- Your original sample does not compile because `char[4096]` is a static array and does not verifies the redln() template constraints, e.g input range, forward range etc. Another option would be to slice Input: readln(Input[0..$-1]);
Re: More uses of operator "in"
On Tuesday, 28 October 2014 at 16:32:13 UTC, Marc Schütz wrote: On Tuesday, 28 October 2014 at 15:11:01 UTC, Baz wrote: On Tuesday, 28 October 2014 at 13:50:24 UTC, Nordlöw wrote: Has there been any proposals/plans to make operator "in" work for elements in ranges such as assert('x' in ['x']); I'm missing that Python feature when I work in D. There is also something similar in Pascal, at the language level. Very handy when working with characters or enums. AFAIR it's limited to sets in Pascal, where its complexity is O(1). If "in" is used as a syntactic sugar, e.g to call "std.algorithm.canFind" in a custom type, then why would the bigO be a concern ? To be clear, I was just trying to suggest that it can be done by writting from scratch some helpers structs.
Re: More uses of operator "in"
On Tuesday, 28 October 2014 at 13:50:24 UTC, Nordlöw wrote: Has there been any proposals/plans to make operator "in" work for elements in ranges such as assert('x' in ['x']); I'm missing that Python feature when I work in D. There is also something similar in Pascal, at the language level. Very handy when working with characters or enums. I think in D it's possible to create some library types which allow an almost similar syntax. For example this one, briefly written after reading your post: import std.stdio; // global variable to get rid of https://issues.dlang.org/show_bug.cgi?id=11877 CharSet charSet; struct CharSet { private string str; public: typeof(this) opSlice(char lo, char hi) { CharSet result; foreach(c; lo .. hi) result.str ~= c; return result; } typeof(this) opSlice(char lohi) { CharSet result; result.str ~= lohi; return result; } bool opIn_r(char elem) { if (str == "") return false; else return ((elem >= str[0]) & (elem <= str[$-1])); } string toString() { return str; } } void main(string args[]) { auto a2k = charSet['a' .. 'k'+1]; auto A2K = charSet['A' .. 'K'+1]; auto Z29 = charSet['0' .. '9'+1]; assert( 'a' in a2k ); assert( !('x' in a2k) ); assert( 'A' in A2K ); assert( !('X' in A2K) ); import std.conv; assert( to!string(Z29) == "0123456789" ); assert( 'x' in charSet['x'..'x'+1] ); }
Re: enum-indexed arrays
On Saturday, 20 September 2014 at 22:00:24 UTC, bearophile wrote: Nordlöw: should be Enumerator start = Enumerator.min This also requires the enum to have adjacent values (in general enums can skip values). Bye, bearophile Not true, because you can use std.traits.EnumMembers to prepare an enum member rank lookup table, so that values have even not be consecutive. there is an example here: http://dlang.org/phobos/std_traits.html#EnumMembers and a concret application in this personal project (e.g line 111): https://github.com/BBasile/bitSet/blob/master/import/bitsets/bitsets.d
Re: Using the delete Keyword /w GC
On Monday, 25 August 2014 at 17:10:11 UTC, Etienne wrote: People have been saying for quite a long time not to use the `delete` keyword on GC-allocated pointers. I've looked extensively through the code inside the engine and even made a few modifications on it/benchmarked it for weeks and I still can't see why it would be wrong. Wouldn't it help avoid collections and make a good hybrid of manual management/collected code? The free lists in the GC engine look quite convenient to use. Any ideas? Until custom class de/allocators are not >>really<< deprecated, the delete keyword is not >>necessarly<< deleting from the GC. Look at this: http://wiki.dlang.org/Memory_Management#Explicit_Class_Instance_Allocation You can do the same but without adding the class reference to the GC. Then delete will call the custom deallocator which is itself not calling the GC. So in a way I think you're right when you say that delete could help into manual mem managment. But that's not a reliable (over time) situation.
Produce some COFF object with 2.066 ?
Hello, I've been very interested about the announce saying that DMD is able to produce COFF object files. Mostly because I'm thinking using some objects programmed in D in a software programmed in another lang, a bit like when statically linking a dll to a program but with an obj, to keep a nice monolithic executable. First thing: I've tried a simple thing: compile an exported function with the args "myfile.d -c -ms32mscoff" and dmd complains that "-ms32mscoff" is not a recognized switch. Second thing: If I understand well, it means that previously, to link D a object with a soft programmed in another lang was not possible because the OMF objs don't include everything (e.g the objs coming from other imported static libs) and that now it's faisable ? right ?
Re: Destroy two assumptions: interface implementation generated by TMP
On Tuesday, 12 August 2014 at 12:43:46 UTC, anonymous wrote: On Tuesday, 12 August 2014 at 12:08:14 UTC, John Colvin wrote: I think the problem is that impl3.tmp is not virtual because it's a template, and interfaces need to be implemented by virtual methods. The instantiations of the template are just normal functions though, no? They are not virtual. Ordinary methods (public, not final, not templated) are virtual. The virtual stuff is right. I've just realized that it's written black on white at the bottom of the manual page which describes templates: "Templates cannot be used to add non-static members or virtual functions to classes" "Templates cannot add functions to interfaces" Sorry for the loss of time.
Destroy two assumptions: interface implementation generated by TMP
Hi, I try to get why the last way of generating an interface implementation fails. I've put assumptions: is it right ? --- module itfgen; import std.stdio; interface itf{ void a_int(int p); void a_uint(uint p); } template genimpl(T){ char[] genimpl(){ char[] result; result = "void a_" ~ T.stringof ~ "("~ T.stringof ~ " p){}".dup; return result; } } class impl: itf{ mixin(genimpl!int); mixin(genimpl!uint); } // OK because: mixin is at the source code level, begining of the ana class impl2: itf{ static char[] genimplint(T)(){ char[] result; result = "void a_" ~ T.stringof ~ "("~ T.stringof ~ " p){}".dup; return result; } mixin(genimplint!int); mixin(genimplint!uint); } // FAILS because: alias are probably generated after the itf check class impl3: itf{ void tmp(T)(T p){}; alias a_int = tmp!int; alias a_uint = tmp!uint; } void main(string args[]){ auto I1 = new impl; auto I2 = new impl2; auto I3 = new impl3; } --- I get 'Error: class itfgen.impl3 interface function 'void a_int(int p)' is not implemented'.
Re: Preferred program config file format and parsing library?
https://en.wikipedia.org/wiki/Marshalling_(computer_science) bla. damn it.
Re: Preferred program config file format and parsing library?
On Saturday, 2 August 2014 at 12:42:00 UTC, Gary Willoughby wrote: What is the preferred format people here use for program config files? Json, Xml, ini, etc? Also what libraries exist to parse the preferred format? Preffered one is the one a RTL(run time library) or a VCL(visual component library) uses. I hate those using markups, like xml. ugly, hard to edit eg in notepad. I hate ini. ini is kind of a beginner format. ini is ridiculous. A good config file format has to - be editable. - be strongly used in the lang. standard library: the one used cause it's good. - not ini. ini files = child happy to discover he can save and load settings. - convertible: even if it's a proprietary format it must be convertible to json or xml or yaml (or ini for the children). https://en.wikipedia.org/wiki/Marshalling_(computer_science).