Re: from bytes to string
On Saturday, 27 November 2021 at 15:29:45 UTC, Adam D Ruppe wrote: On Saturday, 27 November 2021 at 15:24:43 UTC, Coder wrote: Question, why a function can not be nothrow if I catch in the body? Ever play Pokemon? You can't just catch the cute Bulbasaur and call it done (even though the grass type is like playing on easy mode). You gotta catch 'em all! void foo() nothrow { import std.utf : validate, UTFException; try { validate("a"); } catch(Exception){ // make that Exception } } cuz nothrow doesn't know about specific exception types, it only looks at Exception as a whole. It doesn't actually know what validate throws. All right, we gotta rap some pokemon like its 1998. electro diglet nidoran mankey venosaur Thumbs Up!
Re: from bytes to string
On Saturday, 27 November 2021 at 13:56:46 UTC, Adam D Ruppe wrote: On Saturday, 27 November 2021 at 13:54:11 UTC, Coder wrote: My application is receiving data over a socket as immutable(ubyte)[]. How to validate them and transform them to utf8 string? What is the best way? If they're already supposed to be utf8, just cast it to char[] then you can call std.utf.validate on it if you want and idup it into a string to keep. If it is some other encoding... then it depends on what encoding. Thank you Adam, Question, why a function can not be nothrow if I catch in the body? void foo() nothrow { import std.utf : validate, UTFException; try { validate("a"); } catch(UTFException){ } } Error: function `std.utf.validate!string.validate` is not `nothrow` Error: `nothrow` function `foo` may throw
from bytes to string
I'm lost, std.utf, std.conv, std.encoding, std.uni My application is receiving data over a socket as immutable(ubyte)[]. How to validate them and transform them to utf8 string? What is the best way? Thank you!
Re: Accurately serializing and deserializing a SysTime in binary format
On Tuesday, 21 July 2020 at 12:21:16 UTC, Steven Schveighoffer wrote: On 7/21/20 7:44 AM, Ecstatic Coder wrote: On Tuesday, 21 July 2020 at 11:01:20 UTC, drug wrote: On 7/20/20 10:04 PM, Ecstatic Coder wrote: I'm currently implementing a small open source backup tool (dub), and therefore I need to accurately store the file modification SysTime in binary format, so that I can later load this SysTime from the snapshot file to compare it with the current file modification SysTime. Having unfortunately not understood how to do this from the SysTime documentation, in despair, I've tried to directly serialize the 16 bytes of the SysTime value. This worked fine until I call the ".toISOString()" on the deserialized SysTime, which inevitably crashes the executable ;) That is probably a bug. I serialize SysTime as long by means msgpack for exchanging between C++ client and D server and it works pretty nice. Ah thanks for telling me :) The loaded byte array in the union type was indeed the same as the saved one, so I immediately thought it was crashing because of some hidden pointer for timezone or something which was then pointing to garbage at reloading, causing the crash of the ".toISOString" call. Not a bug. 8 of those 16 bytes is a pointer to the timezone, which is going to be different on different processes. What you should do I think is serialize the stdTime [1], and set the time zone to whatever you want: long serialize(SysTime st) { return st.stdTime; } SysTime deserialize(long st) { return SysTime(st, UTC()); } The stdTime is always stored as UTC to make math a lot easier. The time zone is only used for display. -Steve [1] https://dlang.org/phobos/std_datetime_systime.html#.SysTime.stdTime Smart :) Now I understand my mistake was to try to directly serialize a SysTime as provided by the "getTimes" function, instead of converting it to a StdTime, which is more versatile...
Re: Accurately serializing and deserializing a SysTime in binary format
On Tuesday, 21 July 2020 at 11:01:20 UTC, drug wrote: On 7/20/20 10:04 PM, Ecstatic Coder wrote: I'm currently implementing a small open source backup tool (dub), and therefore I need to accurately store the file modification SysTime in binary format, so that I can later load this SysTime from the snapshot file to compare it with the current file modification SysTime. Having unfortunately not understood how to do this from the SysTime documentation, in despair, I've tried to directly serialize the 16 bytes of the SysTime value. This worked fine until I call the ".toISOString()" on the deserialized SysTime, which inevitably crashes the executable ;) That is probably a bug. I serialize SysTime as long by means msgpack for exchanging between C++ client and D server and it works pretty nice. Anyway, that's not really want I intended to do, as in practice a "ulong" already has enough resolution for that purpose. So sorry for my ignorance, but I would definitely need some help on how to : - convert a file modification SysTime to a serializable number, for instance the number of hectonanoseconds since 1/1/1970 in UTC; - convert that number back into a SysTime that I can compare to the modification SysTime of the same file. Eric Ah thanks for telling me :) The loaded byte array in the union type was indeed the same as the saved one, so I immediately thought it was crashing because of some hidden pointer for timezone or something which was then pointing to garbage at reloading, causing the crash of the ".toISOString" call.
Re: Accurately serializing and deserializing a SysTime in binary format
As my question obviously didn't interest any expert, I took advantage of my lunch break to do some more research ;) Maybe I'm wrong, but to my knowledge, there is no function to get the number of hectonanoseconds since January 1, 1970. Fortunately I can get the number of seconds since the same date, and the number of remaining hectonanoseconds, and then use them in conjunction to create a new "SysTime". With that I've got everything needed to fix my problem, and as I can store those values as two independent "uint", it's easy to compress them in the snapshot file, so no regrets :)
Accurately serializing and deserializing a SysTime in binary format
I'm currently implementing a small open source backup tool (dub), and therefore I need to accurately store the file modification SysTime in binary format, so that I can later load this SysTime from the snapshot file to compare it with the current file modification SysTime. Having unfortunately not understood how to do this from the SysTime documentation, in despair, I've tried to directly serialize the 16 bytes of the SysTime value. This worked fine until I call the ".toISOString()" on the deserialized SysTime, which inevitably crashes the executable ;) Anyway, that's not really want I intended to do, as in practice a "ulong" already has enough resolution for that purpose. So sorry for my ignorance, but I would definitely need some help on how to : - convert a file modification SysTime to a serializable number, for instance the number of hectonanoseconds since 1/1/1970 in UTC; - convert that number back into a SysTime that I can compare to the modification SysTime of the same file. Eric
Re: Full precision double to string conversion
On Saturday, 3 November 2018 at 18:04:07 UTC, Stanislav Blinov wrote: On Saturday, 3 November 2018 at 17:26:19 UTC, Ecstatic Coder wrote: void main() { double value = -12.000123456; int precision = 50; import std.stdio; writefln("%.*g", precision, value); import std.format; string str = format("%.*g", precision, value); writeln(str); } Prints: -12.00012345600743415512260980904102325439453125 -12.00012345600743415512260980904102325439453125 That's not quite the -12.000123456 that you'd get from C#'s ToString(). Unfortunately, but that's still better though, thanks :) I don't think you understood what I meant. Neither C# nor D attempt to exhaust the precision when converting, given default arguments. It's merely a matter of those defaults. The snippet above obviously provides *more* digits that the default .ToString() in C# would. But indeed what I really need is a D function which gives a better decimal approximation to the provided double constant, exactly in the same way those in Dart and C# do. Is there really no such function in D ? When you call .ToString() in C# with no arguments, it assumes the "G" format specifier. https://docs.microsoft.com/en-us/dotnet/standard/base-types/standard-numeric-format-strings?view=netframework-4.7.2#the-general-g-format-specifier So for a double, it will use 15-digit precision. D's to!string simply uses lower default. If you want the exact same behavior as in C#, you can do this: string toStringLikeInCSharp(double value) { import std.format : format; return format("%.15G", value); } void main() { double value = -12.000123456; import std.stdio; writeln(value.toStringLikeInCSharp); // prints: -12.000123456 } This version perfectly gets the job done! Thanks a lot for your help :)
Re: Full precision double to string conversion
Actually, what I need is the D equivalent of the default ToString() function we have in Dart and C#. I don't think it means what you think it means: void main() { double value = -12.000123456; int precision = 50; import std.stdio; writefln("%.*g", precision, value); import std.format; string str = format("%.*g", precision, value); writeln(str); } Prints: -12.00012345600743415512260980904102325439453125 -12.00012345600743415512260980904102325439453125 That's not quite the -12.000123456 that you'd get from C#'s ToString(). Unfortunately, but that's still better though, thanks :) All of them? Most implementations of conversion algorithms actually stop when it's "good enough". AFAIR, D doesn't even have it's own implementation and forwards to C, unless that changed in recent years. What I meant was that getting too many significant digits would still be a better solution than not having them. But indeed what I really need is a D function which gives a better decimal approximation to the provided double constant, exactly in the same way those in Dart and C# do. Is there really no such function in D ?
Re: Full precision double to string conversion
On Saturday, 3 November 2018 at 12:45:03 UTC, Danny Arends wrote: On Saturday, 3 November 2018 at 12:27:19 UTC, Ecstatic Coder wrote: import std.conv; import std.stdio; void main() { double value = -12.000123456; writeln( value.sizeof ); writeln( value ); writeln( value.to!string() ); writeln( value.to!dstring() ); } /* 8 -12.0001 -12.0001 -12.0001 */ In Dart, value.toString() returns "-12.000123456". In C#, value.ToString() returns "-12.000123456". In D, value.to!string() returns "-12.0001" :( How can I convert a double value -12.000123456 to its string value "-12.000123456", i.e. without loosing double-precision digits ? Specify how many digits you want with writefln: writefln("%.8f", value); Actually, what I need is the D equivalent of the default ToString() function we have in Dart and C#. I mean a dumb double-to-string standard library conversion function which returns a string including all the double precision digits stored in the 52 significant bits of the value, preferably with the trailing zeroes removed. For an unknown reason, D's default double-to-string conversion function only expose the single-precision significant digits :(
Full precision double to string conversion
import std.conv; import std.stdio; void main() { double value = -12.000123456; writeln( value.sizeof ); writeln( value ); writeln( value.to!string() ); writeln( value.to!dstring() ); } /* 8 -12.0001 -12.0001 -12.0001 */ In Dart, value.toString() returns "-12.000123456". In C#, value.ToString() returns "-12.000123456". In D, value.to!string() returns "-12.0001" :( How can I convert a double value -12.000123456 to its string value "-12.000123456", i.e. without loosing double-precision digits ?
Re: Is there a pragma or command line option to ask DMD to show a warning when it implicitly casts from long to ulong ?
On Friday, 15 December 2017 at 21:55:12 UTC, Michael wrote: On Friday, 15 December 2017 at 21:29:10 UTC, Jonathan M Davis wrote: On Friday, December 15, 2017 20:40:10 Ecstatic Coder via Digitalmars-d-learn wrote: It's taken me some time to find an implicit cast bug ("if (my_sometimes_negative_index >= this_array.length)"), while a simple C++-like implicit-cast warning would have allowed me to find this nasty bug WAY sooner... No. https://issues.dlang.org/show_bug.cgi?id=259 - Jonathan M Davis How does something like this get left for so long... +1
Is there a pragma or command line option to ask DMD to show a warning when it implicitly casts from long to ulong ?
It's taken me some time to find an implicit cast bug ("if (my_sometimes_negative_index >= this_array.length)"), while a simple C++-like implicit-cast warning would have allowed me to find this nasty bug WAY sooner...
Re: Panda Antivirus puts the latest dmd installer in quarantine
Why is it put in quarantine? Posting the reason and some information about it would help a lot to identify the issue. If I remember well, it has detected a "W32/exploit.gen". The file was put in quarantine in the second I tried to execute the installer. Here is the current VirusTotal analysis : https://www.virustotal.com/fr/file/d12e9521ab0ad6a9c0babadeb789692b625fa3535ff406f27a7f47a096430a99/analysis/ The following malware signatures were detected a few hours ago : Baidu Win32.Trojan.WisdomEyes.16070401.9500.9674 20170706 CAT-QuickHeal Trojan.Generic 20170706 Comodo Heur.Packed.Unknown 20170706 TrendMicro-HouseCallSuspicious_GEN.F47V0606 20170706 To be sure, I've just submitted the file for a new analysis, from a file downloaded on my linux system. The Comodo detection has disappeared, but the others remain : Baidu Win32.Trojan.WisdomEyes.16070401.9500.9674 20170706 CAT-QuickHeal Trojan.Generic 20170706 TrendMicro-HouseCallSuspicious_GEN.F47V0606 20170706
Panda Antivirus puts the latest dmd installer in quarantine
But no problem with any file stored inside the current .7z archive file. So I guess the problem comes from the installer executable itself. Please try to fix this as soon as possible, as this immediately drives people away from D before they even got a chance to install it...
class destructors and sub-objects
Greetings I have a question on class destructor method. D documentation for destructors says: "The garbage collector is not guaranteed to run the destructor for all unreferenced objects. Furthermore, the order in which the garbage collector calls destructors for unreference objects is not specified. This means that when the garbage collector calls a destructor for an object of a class that has members that are references to garbage collected objects, those references may no longer be valid. This means that destructors cannot reference sub objects." Now I have a class A and it refers to subobject B. But B may or may not have other objects referring to it. As a result, an object of A is GCed, but subobject B may or may not be getting garbage collected. In this scenario, am I allowed to make a reference to subobject B from the destructor of A? Is there a way to find out if B is garbage collected or not? Regards - Puneet
Re: Initializing assoc array to non-null
Thanks Jonathan Do you think this could make a good enhancement request? Regards - Puneet On Sat, Jun 1, 2013 at 9:34 PM, Jonathan M Davis wrote: > On Saturday, June 01, 2013 20:21:42 d coder wrote: > > Greetings > > > > Is there a way to initialize an associative array to a non-null (but > still > > empty) state? The only way I know is by adding an element and then > removing > > it. Did I miss something obvious? Basically I want to write lines 7-8 in > > the following code in a cleaner fashion. Any ideas? > > Unfortunately, at the moment, I believe that that's the best that you can > do - > though it's trivial enough to write a function that does that for you so > that > you can make it a one-liner: > > auto aa = initAA!(string[int])(); > > or > > initAA(aa); > > - Jonathan M Davis >
Initializing assoc array to non-null
Greetings Is there a way to initialize an associative array to a non-null (but still empty) state? The only way I know is by adding an element and then removing it. Did I miss something obvious? Basically I want to write lines 7-8 in the following code in a cleaner fashion. Any ideas? Regards - Puneet class Foo { // 1 string[int] _aa; // 2 public string[int] aa() { // 3 return _aa; // 4 } // 5 this() { // 6 _aa[0] = "";// 7 _aa.remove(0); // 8 } // 9 } // 10 void main() { // 11 Foo foo = new Foo;// 12 string[int] bb = foo.aa; // 13 assert(bb !is null); // 14 bb[0] = "zero"; // 15 assert(bb is foo.aa); // 16 } // 17
Re: Multi-library project path issue
Thanks for the quick and helpful reply. I will give it a shot. On Friday, 25 May 2012 at 06:36:07 UTC, Jacob Carlborg wrote: On 2012-05-25 08:15, #coder wrote: Hi, I am using the Mono-D for building a project with 3-4 library projects and one console project. Although I am using the Mono-D but I think this issue is not unique to Mono-D. Please advise me with a solution, if I am missing something obvious here. Issue; I have two "library" project with something similar to following: AppFolder (AppFolder contains the below two folders for individual project) Lib1 | -- TestFile1.d | -- TestFile2.d (import TestFile1;) // TestFile2 is importing TestFile1 in same library project. Lib2 (Lib2 has linker path to "lib1.a" and include path to "AppFolder") | -- TestFile3.d (import Lib1.TestFile2). If I compile the Lib1 folder alone then it will work fine but now if I compile the Lib2 folder then the error will be in "TestFile2.d" of Lib1 project that "TestFile1" is not found. If I change the "Import" in TestFile2 to import Lib1.TestFile1; Then the compilation of Lib2 starts to work. Now, if I try to compile the Lib1 project alone in Mono-D (I also tried same on D-IDE) then it will not compile. I was ok with compiling only the Lib2 but now the next issue is that the code completion won't work in "Lib1.TestFile2" after changing the import statement (simply because Lib1.TestFile1 is not valid path for it any more). What should I do? How are other people working on multi-library projects in D? I tried to look into generating the ".di" files but I don't think that will work either. I looked at "Phobos" and it uses the convention like "Lib1.TestFile2" (std.conv) but I don't think it will help me with the compilation of Lib1 project. Thanks It depends on what naming scheme you want to have on your modules. I think you should go with "Lib1.TestFile1". Actually I would go with lower case package names, i.e. "lib1.TestFile1". In that case you need to add a flag to DMD to indicate the import search path. This search path should point to the parent folder of the root package(s), in this case the parent folder of "Lib1", i.e. AppFolder. AppFolder |- main.d |- Lib1 |- TestFile1.d |- TestFile2.d |- Lib2 |- TestFile3.d |- Lib3 |- TestFile4.d $ dmd AppFolder/main.d -I./AppFolder The module and import declarations of the TestFiles should look like this: module Lib1.TestFile1; import Lib1.TestFile2; import Lib2.TestFile3; import Lib2.Lib3.TestFile4; For Mono-D you need to be able to specify the same search path. I have no idea how to do that in Mono-D.
Multi-library project path issue
Hi, I am using the Mono-D for building a project with 3-4 library projects and one console project. Although I am using the Mono-D but I think this issue is not unique to Mono-D. Please advise me with a solution, if I am missing something obvious here. Issue; I have two "library" project with something similar to following: AppFolder (AppFolder contains the below two folders for individual project) Lib1 | -- TestFile1.d | -- TestFile2.d (import TestFile1;) // TestFile2 is importing TestFile1 in same library project. Lib2 (Lib2 has linker path to "lib1.a" and include path to "AppFolder") | -- TestFile3.d (import Lib1.TestFile2). If I compile the Lib1 folder alone then it will work fine but now if I compile the Lib2 folder then the error will be in "TestFile2.d" of Lib1 project that "TestFile1" is not found. If I change the "Import" in TestFile2 to import Lib1.TestFile1; Then the compilation of Lib2 starts to work. Now, if I try to compile the Lib1 project alone in Mono-D (I also tried same on D-IDE) then it will not compile. I was ok with compiling only the Lib2 but now the next issue is that the code completion won't work in "Lib1.TestFile2" after changing the import statement (simply because Lib1.TestFile1 is not valid path for it any more). What should I do? How are other people working on multi-library projects in D? I tried to look into generating the ".di" files but I don't think that will work either. I looked at "Phobos" and it uses the convention like "Lib1.TestFile2" (std.conv) but I don't think it will help me with the compilation of Lib1 project. Thanks
Re: Frustration [Was: mysql binding/wrapper?]
As for mysqln, I merged jrogers patches and changed uint to size_t so it compiles on x64. You can look at it here: https://github.com/simendsjo/mysqln/tree/compile-on-recent-dmd It hasn't been tested beyond connecting to the database and fetching metadata yet. And my repository will go away very soon as I'll rather help with the original library (if Steve Teale comes back) or the one in vibe. Thanks for sharing the modified code. I was able to compile it without any issue and I am able to fetch the meta data. I will be testing more to run insert and select queries. But I found a bug in the code. If you don't specify the password for your test mySQL server then the mysql.d fails. It is always expecting a password and on empty password it throws the exception. file: mysql.d function: open [line 1415] I think when it calls _socket.send then it fails. So far other that this issue, it is working good and if it gets stable then certainly I will move forward with a project in D Language. I will be using the mongoDB and mySQL so this driver will be important for me, in fact for other's too as they mentioned in this thread. One question though, is it thread safe? Thanks for everyone's effort to make this driver work!
Re: Unable to pass shared class method as delegate
> > > I've copy and pasted my reply to Benjamin below, you should be able to > adapt it to your needs: > Stupid me. Should have checked the list before posting. > > The only way I've found to do this that works is using an alias - this is > probably worth a bug report if there isn't one already. I checked and found that this is already reported http://d.puremagic.com/issues/buglist.cgi?quicksearch=shared+delegate And since Walter says that const issues are high on his priority list, I hope this would get resolved soon. Regards - Puneet
Unable to pass shared class method as delegate
Greetings I am facing problem passing a shared class method as an argument to a function. Look at the following minimized code snippet. class Foo { shared // compiles when commented out void bar() {} } void frop(void delegate() dg) { } void main() { shared Foo foo = new shared(Foo); frop(&foo.bar); } I get the following errors (using dmd 2.052) dg.d(11): Error: function dg.frop (void delegate() dg) is not callable using argument types (void delegate() shared) dg.d(11): Error: cannot implicitly convert expression (&foo.bar) of type void delegate() shared to void delegate() Please suggest a valid signature for the function frop, so that it can take shared delegates. Regards - Puneet
Next Release
Greetings All It has been 2 months since we had release 2.052. Just wondering when is the 2.053 release planned? Also, is there an automated way to create a snapshot release from the git repositories? Regards - Puneet
Why is the struct instance being copied here?
Greetings Please look at the code down here. When compiled and run, I get the message "Call to postblit" printed. I think it is because of the foreach block, because the variable "i" is not declared as ref there. Is there a way to make it a ref? Regards - Puneet import std.stdio; struct Foo { this(this) { writeln("Call to postblit"); } } class Bar { Foo foo; this() { foreach(i, f; this.tupleof) { // do nothing } } } void main() { Bar bar = new Bar(); }
Do I need to declare instances of Mutexes, Semaphores, and Barriers shared?
Greetings Do I need to declare instances of Semaphores, Mutexes and Barriers shared? In most situations these objects would be naturally accessed by many threads. Regards - Puneet
Re: Why is it necessary to use synchronized functions when passing shared variables?
> > > It's probably complaining because using shared without synchronizing is > generally very foolish. Now, I would have _thought_ that it would still > work > without, but I apparently not. Regardless, I'm not sure why you'd want to > use > shared anything without synchronizing your access of it. Thanks Jonathan Actually in my actual use case, I am using synchronized at code block level -- to limit the scope of locking. I am doing this to mitigate possible inefficiency due to indiscriminate use of mutex locked code. But D is forcing me to synchronize at function level, thus making most of my code go under mutex locks. Regards - Puneet
Why is it necessary to use synchronized functions when passing shared variables?
Greetings Why is it necessary to use synchronized functions when passing shared variables? I get error even when I am not modifying the shared variable in the function. Kindly look at the following code. I get a compile error unless I declare the functions parent and root synchronized. The compile error says: test.d(13): Error: function test.HierObject.root () const is not callable using argument types () shared const Thanks and Regards - Puneet // Reduced Code import std.exception; // synchronized // Compiles without error when uncommented class HierObject { private shared HierObject _root; private shared HierObject _parent; shared(const(HierObject)) root() const { if(_root) return _root; else { enforce(_parent, "HierObject Instance does not have a parent!"); return this.parent().root(); } } shared(const(HierObject)) parent() const { enforce(_parent); return _parent; } }
Re: Doubt about Synchronized Code Clocks
> I'm afraid that I have no idea what would be "stale" about a shared variable. > sychronized uses a mutex, and if you want to avoid race conditions, you need to > use mutexes or something similar when dealing with shared variables. But I don't > know what would be "stale" about a variable. > One thread modifies a shared variable and the other thread still gets an old value. I do not know if this is applicable to D at all. Just wanted to get a clarification after I read an article in "Java Concurrency in Practice" book. I quote a relevant paragraph: Locking is not just about mutual exclusion; it is also about memory > visibility. To ensure that all threads see the most up-to-date values of > shared mutable variables, the reading and writing must synchronize on a > common lock. Regards
Doubt about Synchronized Code Clocks
Greetings I have a doubt about synchronized code blocks. I learnt that in Java the synchronized keyword has two fold effect. Firstly it locks the code to make sure that only a single thread gets access to the code block at a given time. Secondly, it makes sure that the data elements accessed inside the code block are not "stale". As a result Java programming practice is to synchronize even access functions that access shared data elements. How about D? Does D synchronized keyword just result in mutex locking of the code block? Or does it also ensure that the accessed shared data elements are not stale? Thanks and Regards - Puneet
Re: Are function pointers compile time constants?
Thanks Simon.
Are function pointers compile time constants?
Greetings I tried to initialize a struct member with a function pointer, and found that DMD2 did not like it. Are not function pointers compile time constants? And why they should not be? Regards - Cherry
Error: this for ~this needs to be type foo not type foo[1u][1u]
Greetings I am getting this error when I am instantiating a struct array with a single element inside another class and only if there is the destructor for the struct is explicitly defined. Is it a known error? Here is a minimized snippet that gives error: $ rdmd --main -unittest test.d Error: this for ~this needs to be type foo not type foo[1u][1u] Error: this for ~this needs to be type foo not type foo[1u] // test.d struct foo { int foofoo; ~this() { // no error if explicit destructor not // defined } } class bar { foo fred; foo[2][2] foofoo; foo[1] frop; // this gives error foo[1][1] fropfrop; // this too } unittest { foo frop; foo[1][1] fropfrop; // this works bar burp; }
Re: Number of references to a Class Object
> However, it's not generally an issue, because you shouldn't normally be > keeping > references around for stuff that isn't used anymore. The garbage collector is > smart enough to deal with circular references and the like, so the biggest > cases > where you'd normally need weak references aren't actually a problem. You're > trying to do something fairly abnormal here. > Thanks Jonathon, with some effort I hope to wriggle out of the situation. Regards - Cherry
Re: Number of references to a Class Object
> If you know roughly what to do and want to take a stab at producing a viable > patch to fix the problem, then feel free. If it's solid, it may get in. I > don't > know. It doesn't hurt to try though (as long as you're prepared for the fact > that it may not be accepted). Thanks for letting me know of the licensing issues. I do not think I have the expertize required to fix this myself. So I hang my shoes here and wait for somebody else to get stuck in a similar situation. Regards - Cherry
Re: Number of references to a Class Object
> Also tango (for D 1.0) implements it. > Link: > http://www.dsource.org/projects/tango/docs/current/tango.core.WeakRef.html > > Might be worth a look if you are going to implement it for D 2.0. > I looked at the D1 implementation. It depends on GC methods weakPointerCreate and weakPointerDestroy. These functions are implemented in D1 GC as extern C functions. It seems most of this code should be directly portable to D2, it would certainly require changes in the DMD2 source code. I have never worked at that level and have used D2 only for past couple of months. While I can give that a blind try, it would be useful only if it gets excepted in DMD2. What do you guys suggest? Regards - Cherry
Re: Number of references to a Class Object
> I believe what you're referring to is generally called a Weak > Reference, which is a reference that the GC doesn't consider when > deciding to keep an object alive, but that the GC will update if an > object dies. > There's a feature request at > http://d.puremagic.com/issues/show_bug.cgi?id=4151 > Thanks Andrew Is there a way fro the users like myself to vote up an issue on DMD Bugzilla. Regards - Cherry
Number of references to a Class Object
Greetings I am in a situation where I need to know the number of references to a class' object. To explain, I have an array of class objects and I occasionally process this array. But if a particular object in this array is not being garbage collected just because it is part of this array, I would like to loose that object by making it null. So either I need to find out the number of references to that object and in case there is only one reference, I force the object null. If this is not possible, I am sure there would be alternative solutions since this should be a common situation faced by programmers. Please help. Regards - Cherry
Re: Dynamic and Static Casting
Thanks Lars and Bearophile, I will give it a try. I understand that static downcasting is dangerous. But there are places where efficiency is paramount and you are sure that the casting is safe. So I wholeheartedly second your proposal to have the stuff in phobos. Regards - Cherry
Dynamic and Static Casting
Greetings All I have learnt that D has only one casting operator and that is 'cast'. The same operator assumes different functionality depending on the context in which it he being used. Now I have a situation where I have to downcast an object and I am sure of the objects type and thereby I am sure that the downcast would only be successful. To make the operation faster, in C++ I could have used static_cast operator, thus giving the RTTI a skip. Would this be possible in D? Can I force a static_cast which downcasting? Regards - Cherry
Maximum Number of Threads?
Greetings Is there a limit on the maximum number of threads that can be spawned? Or does it just depend on the value in /proc/sys/kernel/threads-max on a linux system? Regards - Cherry
Re: Nested Structs
> A struct nested in a class does not have a hidden "outer" pointer as a > nested class does. It's because a struct is generally more bare-bones than > a class (which has loads of hidden pieces: vtable, interfaces, classinfo, > etc.). Also, instantiating such a struct does not tie it to a class > instance. > Thanks Steve As far as I am concerned, this is a very limiting behavior wrt structs nested inside classes. I have also observed that if you define a constant (using enum for example) inside the enclosing class, the constant remains visible in the nested struct too. So I believe the language is making the hidden "outer" scope visible to the nested struct (or maybe there is some other mechanism for enums that I am not aware of). > You need to implement this behavior on your own: > Actually I am trying to define a DSEL and the end users are not typically programmers. I am in a situation where the end-user decides the unit in an enclosing class (unit of length as an inch for example) and later whenever he instantiates a line or a shape, the particular unit is automatically considered at the time of instantiation. For my application, I need value semantics and therefor using nested classes in place of structs can not be considered. Making the end-users pass the unit or its context (in form of this pointer) everytime they instantiate a shape would be atrocious. It would defeat the very purpose of letting the end-user define a unit. I know I am not on the right mailing group, but I want to ask for this particular language enhancement. I believe this would make the behavior of the language more straight wrt nested structs inside classes (are not these beasts expected to serve like nested classes or even structs nested inside function scopes?). I hope my requirement is generic enough and fits the bill for an enhancement request. Regards - Cherry
Nested Structs
Greetings All I have a situation where I have a struct nested inside a class. I would like to make the enclosing class' members visible inside the nested struct's constructor. I see that such preposition is feasible for nested classes, but not for nested structs. Why so? Are there some alternative constructs which could give me this behavior for nested constructs? Regards - Cherry
Re: is expression for template structs/classes instances?
> I do know the template. I will try out your solution. Will let you > know if I face issues. > Simen It works perfect, And this is exactly what I was looking for. If you see my original post, I also thought this form of "is" expression should work. Just could not get around to the right syntax. With your help it is working now. I am using a slightly more elaborate check which is obvious but I am writing it here to just let the list know. static if ( is( typeof(foo) f == S!T, T : int) ) { // foo is an object of type S!T // where T is convertible to int } Thanks once more Warm Regards - Cherry
Re: is expression for template structs/classes instances?
> S!int foo; > static if ( is( typeof(foo) f == S!T, T ) ) { > // Here, T == int, f == typeof(foo) > } > > Note that the syntax "is ( Type Identifier : TypeSpecialization , > TemplateParameterList )" is only usable inside static if. > Thanks Simen I do know the template. I will try out your solution. Will let you know if I face issues. Regards - Cherry
Re: is expression for template structs/classes instances?
> For instance, given your definiton of S, you could use > _traits/std.traits to check that the type that you're testing has a member > variable t. You could then check that S!(typeof(t)) was the same as the type > that you were testing. So, if you get particularly cunning about it, I believe > that it can be tested for in specific cases, but I don't believe that it can > be > done in any general way. > Thanks Jonathan That is exactly what I had thought of doing. I was conscious that it may not be the cleanest way. Now that you are saying a cleaner way may not exist, I will go ahead and write the code. Regards - Cherry
is expression for template structs/classes instances?
Greetings I want to find if a given struct type is instantiated from a particular template struct type. For example: struct S (T) { alias T Type; T t; } And later I want to find out if a given type is of type S(*) (basically any type instantiated from template struct S). In fact I do not know the type value T used at the time of instantiating S!(T). I was looking at "is ( Type Identifier : TypeSpecialization , TemplateParameterList )" expression at http://www.digitalmars.com/d/2.0/expression.html#IsExpression . Thought there would be some way using that, but I could not find any. Regards Cherry
Re: List of derived types?
> I'm curious, why do you need that? > It is a long story. But basically I am creating a platform wherein the users would be deriving classes from some base classes that I write as part of the platform. And the users would often be deriving many such classes. The end-users would often not be programmers and would know little D (as you can see I am also learning D :-). I want to automate some code generation for them and I hope to do that by creating wrapper classes that would shadow the classes that the end-users have written. Since the and users would be instantiating these classes only inside a particular class scope, I wanted to create some code inside that class scope. Right now I am forcing the end-users to insert some mixin for every class that they code. I wanted to automate that process. Hope what I said makes sense to you. Regards Cherry Hope what I said makes sense.
List of derived types?
Greetings I need a way to know (using traits or other compile time constructs) all the types derived from a given type. Is it possible in D? Is it possible to get a list of all the user-defined classes? I could use that to filter out the classes that I need. Regards Cherry
Re: Facing problems with Class Properties
> Ah.. Now I think I understand. > > This new code I have written will all be run at compile time. So in > this case, the foreach statement inside the constructor would be > reduced to a bunch of writeln statements at compile time and those > writeln would be executed at the run time. This will not happen with > the actual code since there are other typeof and is statements in > there that can not be run at runtime. > > Did I get it right? > If I got it right now, It will be possible for me to unroll the foreach loop and the if statements in a mixin and that would work well. Or may be changing the "if" statement to "static if" would do the trick. I will give it a try. Thank you Steve and tank you Jesse for showing me the light. Regards - Cherry
Re: Facing problems with Class Properties
> Another thing, is(T : U) simply means T is implicitly castable to U. Due to > a compiler bug, Bar[] is implicitly castable to BaseClass[]. > Steve I realize that I am using this compiler bug as a feature. It would be kind of you to suggest me a code that would not exploit this bug. I was thinking of using something to the effect: if (__traits(isStaticArray, this.tupleof[i]) { if (is (typeof(this.tupleof[i][0]) : BaseModule)) { Regards - Cherry
Re: Facing problems with Class Properties
> What you are saying makes sense to me. The problem is that the > following code works perfectly. I have just commented out some part > and replaced it with some debug statements. Ah.. Now I think I understand. This new code I have written will all be run at compile time. So in this case, the foreach statement inside the constructor would be reduced to a bunch of writeln statements at compile time and those writeln would be executed at the run time. This will not happen with the actual code since there are other typeof and is statements in there that can not be run at runtime. Did I get it right?
Re: Facing problems with Class Properties
> Is there a reason you can't directly reference the members? After all, you > are writing the class. > Thanks Steve for your inputs. Actually this is part of a bigger code that I am trying to create. Though I am pretty new to D. What I have posted is a reduced code that illustrated the issue I am facing. In the actual code, I am using string mixins and there are too many classes (all derived from BaseClass) and too many class instances, and the constructor call for Bar (and other classes) is a bit more involved. There is a need to make sure that all the constructors are called in a seamless fashion. In fact, I will not be the end-user. I would just be coding the BaseClass and the mixin. The actual end-users are not supposed to be quite D-literate and I would be asking them to code something to the effect: class Foo: BaseClass { mixin(CreateInstances()); // Define your Bar and other sub-class instances here //... // More code here } Any ideas? Regards - Cherry
Re: Facing problems with Class Properties
> if(false) { > for (size_t j = 0; j < f.length...) > ... > } > > Semantically this code is wrong as you can't take the length of f which is > class Bar. The static if forces the compiler to not generate this code as it > is known to be false. > Thanks Jesse What you are saying makes sense to me. The problem is that the following code works perfectly. I have just commented out some part and replaced it with some debug statements. The output from this code makes me believe that "is" and "typeof" do have some run-time semantics. Or is it a D2 bug. BTW I am using Digital Mars D Compiler v2.050. Regards - Puneet import std.stdio; class BaseClass { } class Bar: BaseClass { } class Foo: BaseClass { this() { foreach(i, f; this.tupleof) { if (is (typeof(this.tupleof[i]) : BaseClass[])) { writeln("Creating new objects for all ARRAY types ", this.tupleof[i].stringof); // for (size_t j = 0; j < this.tupleof[i].length; ++j) { // this.tupleof[i][j] = new typeof(this.tupleof[i][j]) (); // } } if (is(typeof(this.tupleof[i]) : BaseClass)) { writeln("Creating new objects for all NON-ARRAY types ", this.tupleof[i].stringof); // this.tupleof[i] = new typeof(this.tupleof[i]) (); } } } Bar instance1; Bar instance2; Bar [10] instances; } unittest { Foo foo; foo = new Foo; } // I am getting the following output // Creating new objects for all NON-ARRAY types this.instance1 // Creating new objects for all NON-ARRAY types this.instance2 // Creating new objects for all ARRAY types this.instances
Facing problems with Class Properties
Greetings All I am trying to compile the following D2 code. The code giving compilation issues is the "this()" function of the class Foo. The constructor basically tries to initialize all the data members of the class, of type BaseClass and of type BaseClass array. I am using class property tupleof to iterate over members of the class. Then I check the type of each member and if the member is a BaseClass array, I new all the elements of the array. Otherwise if the member is of the type BaseClass, I new it as it is. The issue is that when I try to compile the program, I get the error bug.d(10): Error: no property 'length' for type 'test.Bar' I am explicitly checking the field type, and I am making sure that the field is an array type, before looking for its length. So I am not sure why this error appears. Please guide me. Regards Cherry import std.stdio; class BaseClass { } class Bar: BaseClass { } class Foo: BaseClass { this() { foreach(i, f; this.tupleof) { if (is (typeof(f) : BaseClass[])) { for (size_t j = 0; j < f.length; ++j) { f[j] = new typeof(f[j]) (); } } if (is(typeof(f) : BaseClass)) { f = new typeof(f) (); } } } Bar instance1; Bar instance2; Bar [10] instances; } unittest { Foo foo; foo = new Foo; }