Re: Why do immutable variables need reference counting?
On Sunday, 10 April 2022 at 23:19:47 UTC, rikki cattermole wrote: immutable isn't tied to lifetime semantics. It only says that this memory will never be modified by anyone during its lifetime. This is clearly where I am misunderstanding. In my mind immutable data means the data will not change and neither will the result of reading that data, ever. I don't get how you can have thread safety guarantees based on immutable if reading that data in a thread suddenly becomes undefined behaviour and could return anything. That isn't immutable then. Once instantiated immutable data persists for the remainder of the program. You may not have access if the variable goes out of scope, but if you do it will always be there and always return the same value when you read from memory. Thanks for replying, I am not trying to be argumentative here, just stating what I thought it meant and why I am confused. I'll be doing some more reading of the D spec to better understand immutability. Cheers, Norm
Why do immutable variables need reference counting?
Hi All, I am clearly misunderstanding something fundamental, and probably obvious :D Reading some of the discussions on __metadata I was wondering if someone could explain why a immutable reference counting type is needed. By definition a reference counter cannot be immutable, so what would be the use case that requires it? It cannot really be pure nor safe either because the ref goes out of scope and the allocation is freed. How is this immutable? Thanks, Norm
Re: best/proper way to declare constants ?
On Thursday, 5 August 2021 at 01:14:26 UTC, H. S. Teoh wrote: On Thu, Aug 05, 2021 at 12:47:06AM +, someone via Digitalmars-d-learn wrote: [...] 1) If the constant is a POD (int, float, etc.), use: enum myValue = ...; 2) If the constant is a string or some other array: static immutable string myString = "..."; static immutable Data[] myData = [ ... ]; Unless you have a specific reason to, avoid using `enum` with string and array literals, because they will trigger a memory allocation *at every single reference to them*, which is probably not what you want. enum myArray = [ 1, 2, 3 ]; ... int[] data = myArray; // allocates a new array int[] data2 = myArray; // allocates another array // they are separate arrays with the same contents assert(data !is data2); assert(data == data2); // allocates a temporary array, does the comparison, then // discards the temporary if (data == myArray) ... foreach (i; 0 .. 10) { int[] input = getUserInput(...); // allocates a new array at every single loop iteration if (input == myArray) { ... } } Don't do this. Use static immutable for arrays and strings, use enum only for PODs. T The fact it requires this much explanation on how to declare a "best/proper" constant is not a great selling point for D. Sure, it is easy...once you know it and it reminds me of C++. As a language D should strive to do better than this
Re: Compiler version "dirty"
On Monday, 8 March 2021 at 22:29:58 UTC, Q. Schroll wrote: When I enter `dmd --version`, it says: DMD64 D Compiler v2.095.1-dirty What should the "dirty" mean? To me, it seems looks something went wrong somewhere. This comes from `git describe --dirty` and indicates there were uncommitted changes in the repo when the release was built. This would raise red flags if seen in a commercial setting and looks a bit unprofessional but it is most likely harmless. Probably one of the build scripts or unittests are polluting the repo.
Re: why is "hello".writeln considered bad?
On Friday, 20 November 2020 at 18:46:40 UTC, Martin wrote: On Friday, 20 November 2020 at 10:03:18 UTC, Daniel Kozak wrote: I remember days when I liked UFCS too . Unfortunately it is not so awesome when you use it with IDE. And I would like to add: if you use in a bigger team. It's annoying when every dev have a own taste.. And together with optional () it's hell - no joke. The need to think about codeatyle definitions in such detail is a nogo for big projects. This is a good point. I find with D there are many different ways to write code and each can look different on the page. Where I work we mandated all D code will be implemented in Phobos style and use Phobos and mir source as guides. Some parts do heavily use UFCS/optional() and some parts do not. We have not had issues with readability, but maybe our D code isn't that complicated because it is mostly PC side data analysis tools. Personally a really like UFCS, even `"hello".writeln;` and I think I'd rather have UFCS than autocompletion. But then I did start out in industry well before autocomplete was a thing so maybe I have never relied on it too much. Thanks all for the replies! norm
why is "hello".writeln considered bad?
I was reading some posts and this was presented as a snippet of code and was immediately flagged as bad practice. I get some people don't like it but occasionally I prefer this syntax. It feels more declarative and fluent in style. Is there a good technical reason why it is bad practice, e.g. does it make it easier to write bugs? Or is it just what people are used to? Thanks, norm
Re: sort a string
On Friday, 1 May 2020 at 07:38:53 UTC, Chris Katko wrote: I'm making anagrams. According to the nextPermutation() docs, I need to 'sort by less' to get all permutations. ... Except the doc page doesn't mention how to do that, nor does std.algorithm.sort show how to sort a string. ... and the google results on the dlang forums from 2017 don't work. I've tried .byCodeUnit. , .representation. I've tried sorting on the dchar. I've tried sorting the on string. The closest I've gotten: string word = "bar"; string line2 = toLower!(string)(word); dchar[] line3 = sort(line2.to!(dchar[])); "Error: cannot implicitly convert expression sort(to(line2)) of type SortedRange!(dchar[], "a < b") to dchar[]" You need to convert the sort output to dchar[], e.g. --- dchar[] line3 = sort(line2.to!(dchar[])).to!(dchar[]); --- Cheers, Norm
Re: How to call a extern C++ class constructor ?
On Saturday, 1 February 2020 at 08:38:22 UTC, Luhrel wrote: On Saturday, 1 February 2020 at 08:32:51 UTC, Ferhat Kurtulmuş wrote: On Saturday, 1 February 2020 at 08:27:07 UTC, Luhrel wrote: On Saturday, 1 February 2020 at 08:21:29 UTC, Ferhat Kurtulmuş wrote: You cannot. https://dlang.org/spec/cpp_interface.html#using_cpp_classes_from_d You must use a factory method like createInstance. Oh I see, so there's definitively no way to call a c++ ctor without modifying the c++ code ? İf you are not allowed to modify that c++ code, you can write a createInstance function in your custom cpp file. That was my fear. It isn't too bad, you need a simple wedge written in C++ that returns an instance of any T you want. A simple template function usually works, or to make it more generic you can use a variadic template to handle N args, but I find variadic templates in C++ are still annoying to use.
Re: Indexed graphics for retro engine?
On Thursday, 19 September 2019 at 20:47:45 UTC, Shadowblitz16 wrote: On Thursday, 19 September 2019 at 19:16:03 UTC, Mike Parker wrote: On Thursday, 19 September 2019 at 18:25:05 UTC, Shadowblitz16 wrote: I wanted to do 4bpp 16 color graphics. and I didn't want to load anything unnecessary in the image like the palette but instead supply it myself as a Color[16]; I see. In that case, I suggest you find some tutorials on software rendering in C or C++ and adapt them to D. Most of the modern stuff out there is going to be targeting 24-bit or 32-bit graphics. You might find some older tutorials on indexed 8-bit rendering that you can adapt to 4-bit. Nothing to it but storing the palette indices in a byte array. can I do this in D and draw them to a 32bpp bitmap pixel by pixel? I would prefer do do this on the gpu but I don't know how. I'd create a fragment shader to convert each pixel to 8 bit. There are many examples on the web about creating fragment shaders and 2d opengl scenes, i.e. a 2d scene where OpenGL coordinates are integer pixel coordinates. Once you get that you then just implement the conversion routine. Using the shader you can render the image as a textured quad and send the colour look up table down as an additional 1d texture. This way you can have several D arrays for each colour table and simply swap the texture buffer pointer to instantly switch colours. You can also get cool effects this way when you move to 3d using 8 bit colour tables.
Re: static if (is (T==Complex))
On Wednesday, 18 September 2019 at 11:10:11 UTC, berni wrote: Is it possible to simplfy this? static if (is (T==Complex!double) || is (T==Complex!float) || is (T==Complex!real)) I usually do something like the following: --- import std.traits; template isComplexReal(T) { enum isComplexReal = is(T == Complex!R, R) && (isFloatingPoint!R); } static if(isComplexReal!T) {// do something} ---
Re: Make executable archive just like Java's .jar archive?
On Thursday, 12 September 2019 at 12:52:48 UTC, BoQsc wrote: Is there a way to archive multiple .d source code files and make that archive executable, or something similar? You can achieve something similar with rdmd and shell; $ tar -zcvf source_files.tar.gz source1.d source2.d ... sourceN.d $ rdmd $(tar -xvf source_files.tar.gz) I imagine it wouldn't take much for rdmd to support ZIP or tarballs directly but I'm sure there are corner cases to consider. Bye, norm
Re: Range violation error when reading from a file
On Monday, 17 June 2019 at 00:22:23 UTC, Samir wrote: On Sunday, 16 June 2019 at 23:55:41 UTC, lithium iodate wrote: There is *very* likely to be a terminating new-line at the end of the file (many editors add one without asking!). If that the case, the last line seen by the loop will be empty and you must not attempt to access any elements. On Monday, 17 June 2019 at 00:02:37 UTC, aliak wrote: The fail bit is only set after reading fails. So after you read the last line, your eof will still return true, and hence your range violation. H...maybe you and lithium iodate were onto something. Here is what the file looks like in vim: > line 1 line 2 line 3 > line 4 line 5 ~ ~ ~ The "5" in the last line is the last character I can put my cursor on. Also, if I run the program below with the same file, I don't get any range violation errors: import std.stdio; import std.string; void main() { File file = File("test.txt"); string line; while (!file.eof()) { line = file.readln().strip; //if (line[0] == '>') { // line 10 //writeln(line[1..$]); //} //else { writeln(line); //} } } HOWEVER, the output is interesting. There IS a blank line between the last line and the prompt: $ dmd -run readfile.d > line 1 line 2 line 3 > line 4 line 5 $ Any suggestions on how to rectify? You could change the IF to `if(line.length > 0 && line[0] == '>')` or use strip itself; `File("test.txt", "r").byLine.map!(line => line.strip(">")).writeln;` For "> line 1" your code and this above will generate " line 1" (note the leading space). To remove that change the string passed to `strip` to include a space, e.g.; `.strip("> ")).writeln;` bye, Norm
Re: variant .init value
On Thursday, 7 February 2019 at 07:44:17 UTC, Alex wrote: On Thursday, 7 February 2019 at 07:33:50 UTC, Norm wrote: [...] Hmm... found something similar from 2014... https://issues.dlang.org/show_bug.cgi?id=11864 Thanks, I've added a comment to that bug report. Cheers, Norm
variant .init value
Hi, I'm trying to use Variant in a struct and want a default init value like so: --- struct S { Variant v = Variant(10); } void main() {auto s = S();} but when I try to build this I get the following error: dmd2/linux/bin64/../../src/phobos/std/variant.d(661): Error: memcpy cannot be interpreted at compile time, because it has no available source code Error: cannot interpret at compile time --- I don't particularly need or want this to be available at compile time, I really only want the struct to have a default value when instantiated at runtime. Is there a way to do this with a Variant member? Thanks, Norm
Re: Singleton in Action?
On Saturday, 2 February 2019 at 16:56:45 UTC, Ron Tarrant wrote: Hi guys, I ran into another snag this morning while trying to implement a singleton. I found all kinds of examples of singleton definitions, but nothing about how to put them into practice. Can someone show me a code example for how one would actually use a singleton pattern in D? When I did the same thing in PHP, it took me forever to wrap my brain around it, so I'm hoping to get there a little faster this time. Here's the singleton code I've been playing with: class DSingleton { private: // Cache instantiation flag in thread-local bool // Thread local static bool instantiated_; // Thread global __gshared DSingleton instance_; this() { } // this() public: static DSingleton get() { if(!instantiated_) { synchronized(DSingleton.classinfo) { if(!instance_) { instance_ = new DSingleton(); writeln("creating"); } instantiated_ = true; } } else { writeln("not created"); } return(instance_); } // DSingleton() } // class DSingleton So, my big question is, do I instantiate like this: DSingleton singleton = new DSingleton; Or like this: DSingleton singleton = singleton.get(); And subsequent calls would be...? The same? Using get() only? Sorry, I should read the post fully before replying, my bad. You access the singleton via the get() function whenever you need it. It is static so there's no need to create a copy of the instance in a "singleton" variable. DSingleton singleton = new DSingleton; is bad. It bypasses all the checks in the "get()" method to ensure it is a singleton and outside the module where you defined DSingleton it won't compile. bye, norm
Re: Singleton in Action?
On Saturday, 2 February 2019 at 16:56:45 UTC, Ron Tarrant wrote: Hi guys, I ran into another snag this morning while trying to implement a singleton. I found all kinds of examples of singleton definitions, but nothing about how to put them into practice. [...] If you haven't already been to the d-idioms site it is well worth a look: https://p0nce.github.io/d-idioms/ It has a singleton example that you may find useful. https://p0nce.github.io/d-idioms/#Leveraging-TLS-for-a-fast-thread-safe-singleton bye, norm
Re: Fields with the same name not causing a warning?
On Friday, 16 November 2018 at 15:59:14 UTC, Vinay Sajip wrote: This code should IMO give at least a warning, but it doesn't: abstract class A { int kind; } [...] This is not unique to D you can do the same in Java or C++. bye, Norm
Re: remove file access denied
On Thursday, 13 September 2018 at 23:25:24 UTC, Josphe Brigmo wrote: I am trying to remove a file remove(filename); and I get an access denied! I can remove it from explorer just fine. I am able to remove other files but there should be no reason why the file can't be removed in this case. All I am doing to mess with the file is reading it's contents right before to do a file compare(I am removing the file if it is a duplicate). Does read() lock the file at all? (maybe the lock is persisting just long enough to make the remove fail? Since I can delete the file outside the program and since the filename is valid(I copied and pasted it to remove it to check), This seems like a D problem. Do you have the file open when you call remove? If so close the file handle before the remove call. If you can post a stripped down version of your code it would also help. bye, Norm
Re: Optional parameters?
On Sunday, 1 April 2018 at 15:54:16 UTC, Steven Schveighoffer wrote: I currently have a situation where I want to have a function that accepts a parameter optionally. I thought maybe Nullable!int might work: void foo(Nullable!int) {} void main() { foo(1); // error int x; foo(x); // error } Apparently, I have to manually wrap an int to get it to pass. In other languages that support optional types, I can do such things, and it works without issues. I know I can do things like this: void foo(int x) { return foo(nullable(x)); } But I'd rather avoid such things if possible. Is there a way around this? Seems rather limiting that I can do: Nullable!int x = 1; but I can't implicitly convert 1 to a Nullable!int for function calls. -Steve I don't know if this helps but when I hit this situation I usually resort to templates, e.g. --- void foo(T)(T val = Nullable!int()) if(is(T : int) || is(T == Nullable!int)) { writeln(val); } void main() { foo(1); // prints: 1 int x; foo(x); // prints: 0 auto val = Nullable!int(5); foo(val); // prints: 5 foo(); // prints: Nullable.null } --- Cheers, Norm
Re: D RAII with postblit disabled
On Thursday, 29 March 2018 at 04:16:55 UTC, Adam D. Ruppe wrote: On Thursday, 29 March 2018 at 04:12:38 UTC, Norm wrote: Is there a way to do this in D, or does it require special "create" functions for every struct that has a RAII-like struct as a member? You'll have to do it all the way up (unless you can use a constructor with an argument and call that instead) OK, thanks.
Re: D RAII with postblit disabled
On Tuesday, 27 March 2018 at 02:43:15 UTC, Adam D. Ruppe wrote: On Tuesday, 27 March 2018 at 02:35:23 UTC, Norm wrote: What's the best way to do this in D? I'd also add `@disable this();` and then a `static O make() { return O(theAllocator.make!int(99)); }` than you construct it with that static make function. OK, that got me over the first hurdle but I still cannot use RAII with struct member vars. E.g. --- struct Resource { this() {allocate_something();} ~this() {release_something();} } struct S { Resource resource; } --- Is there a way to do this in D, or does it require special "create" functions for every struct that has a RAII-like struct as a member? Thanks, Norm
Re: D RAII with postblit disabled
On Tuesday, 27 March 2018 at 02:43:15 UTC, Adam D. Ruppe wrote: On Tuesday, 27 March 2018 at 02:35:23 UTC, Norm wrote: What's the best way to do this in D? I'd also add `@disable this();` and then a `static O make() { return O(theAllocator.make!int(99)); }` than you construct it with that static make function. Perfect, thanks.
D RAII with postblit disabled
Hi All, What's the best way to do this in D? E.g. --- struct O { int* value; @disable this(this); /+ this() { this.value = theAllocator.make!int(99); } +/ ~this() { theAllocator.dispose(this.value); } } O obj = O(); // Ideally this would be allocated but it simply run O.init --- Thanks Norm
Re: Game and GC
On Friday, 23 February 2018 at 01:54:07 UTC, Leonardo wrote: Hi, I'm new to language and games. Many people say that GC is bad and can slow down your project in some moments. What can happen if I create a game using D without worrying with memory management? (using full GC) Have a look at https://github.com/gecko0307/atrium and see how memory is handled there. TBH though every game I've written I have not worried about the GC and just code it up. This works fine for 2d games, platformers etc. If it ever does bite you can always schedule the pauses (they are deterministic in the sense a collect will occur on allocation) or do pretty much what every game does in C++/C and allocate in pools. Cheers, Norm
inout question
Hi, I'm new to D so can someone explain to me what is happening here? void func(const char* s, char** e) { import core.stdc.stdlib; auto result = strtod(s, e); } Error: function core.stdc.stdlib.strtod (scope inout(char)* nptr, scope inout(char)** endptr) is not callable using argument types (const(char*), char**) I've found I have to use the following: void func(inout (char)* s, inout(char)** e) I thought inout was supposed to take const or non-const variants, so expected the original const char* s to work. Thanks, Norm
deprecation warning after upgrade
Hi All, In my generic code I now get this error, which requires manually finding all -a[] array ops, but that is another matter. $/src/druntime/import/core/internal/arrayop.d-mixin-57(57,20): Deprecation: integral promotion not done for -_param_1[pos], use '-transition=intpromote' switch or -cast(int)(_param_1[pos]) Is there a way to avoid this in generic code so I can still take advantage of array ops? E.g. this.vec[] = -this.vec[]; Or do I have to do some wrangling like this? this.vec = this.vec.map!(a => -cast(int)(a)).array.to!(T[]) ?? What would be a good idiomatic way to fix this deprecation issue? I do not want to use the flag but make my code better, not mask the issue. Thanks, Norm