Re: Get milliseconds from time and construct time based on milliseconds
On Tuesday, 28 May 2024 at 18:41:02 UTC, bauss wrote: On Tuesday, 28 May 2024 at 18:29:17 UTC, Ferhat Kurtulmuş wrote: On Tuesday, 28 May 2024 at 17:37:42 UTC, bauss wrote: I have two questions that I can't seem to find a solution to after looking at std.datetime. First question is how do I get the current time but in milliseconds? Second is how do I construct a time ex. systime or datetime based on milliseconds? Thanks Unixtime might be what you want: import std; import std.datetime; import std.stdio; void main() { // Get the current time in the UTC time zone auto currentTime = Clock.currTime(); // Convert the time to the Unix epoch (1970-01-01T00:00:00Z) Duration unixTime = currentTime - SysTime(DateTime(1970, 1, 1), UTC()); You can do `SysTime(unixTimeToStdTime(0))` to get a SysTime that is at the unix epoch. Also figured out the second question based on your result. Simply doing: ``` SysTime(DateTime(1970, 1, 1), UTC()) + dur!"msecs"(milliseconds) ``` Seems to work. Note there is an `msecs` function: ```d SysTime(unixTimeToStdTime(0)) + milliseconds.msecs; ``` https://dlang.org/phobos/std_datetime_systime.html#unixTimeToStdTime https://dlang.org/phobos/core_time.html#msecs -Steve
Re: Hide console on Windows with app running SDL2
On Tuesday, 28 May 2024 at 12:35:42 UTC, bauss wrote: Running into a couple of problems trying to hide the console that opens when running an app that uses sdl2. First of all I am trying to compile with this using dub: ``` "lflags": ["/SUBSYSTEM:windows"] ``` However that gives me the following error: ``` error LNK2019: unresolved external symbol WinMain ``` And then if I add a WinMain like below: ``` extern (Windows) int WinMain() { return 0; } ``` Then of course it doesn't work, but what is the obvious way to solve this? I basically just want to hide the console, but nothing seems to work straight out of the box. I think this is still relevant: https://wiki.dlang.org/D_for_Win32 -Steve
Re: North Korean Hackers Developing Malware in Dlang Programming Language
On Tuesday, 28 May 2024 at 11:14:07 UTC, aberba wrote: On Monday, 27 May 2024 at 23:00:58 UTC, ryuukk_ wrote: On Monday, 27 May 2024 at 16:17:07 UTC, aberba wrote: By Ionut Arghire: The North Korea-linked hacking group Lazarus has been observed deploying Dlang malware in attacks against organizations in the manufacturing, agriculture, and physical security sectors, Cisco’s Talos security researchers report. https://www.securityweek.com/north-korean-hackers-developing-malware-in-dlang-programming-language/ This does not belong to "Announce".. c'mon, this is a garbage article and is FUD I read his LinkedIn before posting but it could all be fake as well. If Mike is reading this, feel free to delete this and my other post as well. Since I can't verify their authenticity beyond their claimed credentials on LinkedIn. FWIW, this was discussed when it was in the news (this article is from December) https://forum.dlang.org/post/olpockqkosloluwys...@forum.dlang.org So this is probably legit, but also not new news. -Steve
Re: Beerconf May
On Saturday, 25 May 2024 at 17:57:50 UTC, Steven Schveighoffer wrote: On Thursday, 23 May 2024 at 17:42:38 UTC, Steven Schveighoffer wrote: I will do a very informal presentation (no slides, just talking and coding) at about 18:00 UTC on Saturday. We will send out an announcement when it's about to start as well. Happening in a few minutes! FYI, I recorded this, but there was some audio issues with the recording. I think it's salvageable, but I will post it when it's ready. -Steve
Re: Beerconf May
On Thursday, 23 May 2024 at 17:42:38 UTC, Steven Schveighoffer wrote: I will do a very informal presentation (no slides, just talking and coding) at about 18:00 UTC on Saturday. We will send out an announcement when it's about to start as well. Happening in a few minutes! The URL is https://meet.jit.si/Dlang2024MayBeerConf -Steve
Re: The D Programming Language and Its Role in Cybersecurity
On Monday, 20 May 2024 at 21:21:24 UTC, aberba wrote: Found this article by Raymond Andrè Hagen: https://www.linkedin.com/pulse/d-programming-language-its-role-cybersecurity-raymond-andr%C3%A8-hagen-nfvgf/ My goodness this is a terrible article. Almost no substance. Is this AI generated? -Steve
Re: Beerconf May
On Saturday, 11 May 2024 at 20:35:17 UTC, Steven Schveighoffer wrote: # BEERCONF! This month, we are having our favorite online gathering on the 25-26 of May. We will announce the stream the day of the 25th. Hi All, just a friendly reminder this is happening in 2 days! ## Presentations? Let me know if you have anything you want to schedule, via discord, email, or anywhere you find me. I will announce it, and get you an audience! Nobody has asked to show anything, so I thought I might do a quick dive into how the new [Interpolation Expression Sequences](https://dlang.org/spec/istring.html) (a.k.a. string interpolation) work. These were added in the last major version of D, and I'm excited to start using these in my libraries! I will do a very informal presentation (no slides, just talking and coding) at about 18:00 UTC on Saturday. We will send out an announcement when it's about to start as well. See you then! -Steve
Re: __gshared is "somewhat" transitive, isn't it ?
On Thursday, 16 May 2024 at 17:04:09 UTC, user1234 wrote: Given ```d struct S { int member; } __gshared S s; ``` It's clear that `s.member` is `__gshared` too, right ? What does happen for ```d struct S { int member; static int globalMember; } __gshared S s; ``` Is then `S.globalMember` a TLS variable ? (I'd expect that) `__gshared` is a storage class. It means, store this thing in the global memory segment. `static` storage class means store this thing in TLS. Storage classes are *not* transitive, and they are not type constructors. They optionally might apply a type constructor to the type (such as the `const` storage class), but not always. So in this case `typeof(s)` is `S`, not `__gshared S`. `s.member` is in the global segment since structs members are placed within the struct memory location (in this case, the global memory segment). `globalMember` is placed in TLS because it's storage class is `static`, and `static` means, do not store with the instance (which for `s` would mean the global memory segment), but rather in TLS. -Steve
Beerconf May
# BEERCONF! This month, we are having our favorite online gathering on the 25-26 of May. We will announce the stream the day of the 25th. Please note that May 17th is the deadline for dconf submissions! Don't be shy, we love new speakers, and you get a free trip if you are chosen! See the details here: https://dconf.org/2024/index.html#schedule Obligatory link to beerconf T's: https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is Beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf) ## Presentations? Let me know if you have anything you want to schedule, via discord, email, or anywhere you find me. I will announce it, and get you an audience! Cheers! -Steve
Re: D doesn't have weak references. So how can I make a associative array of objects without preventing their destruction?
On Friday, 10 May 2024 at 11:05:28 UTC, Dukc wrote: This also gets inferred as `pure` - meaning that if you use it twice for the same `WeakRef`, the compiler may reuse the result of the first dereference for the second call, without checking whether the referred value has changed! This would be weak pure since the reference is mutable. This cannot be memoized. -Steve
Re: "in" operator gives a pointer result from a test against an Associative Array?
On Friday, 10 May 2024 at 01:00:09 UTC, Andy Valencia wrote: On Friday, 10 May 2024 at 00:40:01 UTC, Meta wrote: Yes. The reason for this is that it avoids having to essentially do the same check twice. If `in` returned a bool instead of a pointer, after checking for whether the element exists (which requires searching for the element in the associative array), you'd then have to actually *get* it from the array, which would require searching again. Returning a pointer to the element if it exists (or `null` if it doesn't) cuts this down to 1 operation. Looking at Programming in D section 28.5, I'm guessing that pointer versus null is treated as the appropriate boolean value when consumed by an "if" test. So that example is getting a pointer to a string, or null, but the example looks exactly as the same as if it had directly gotten a bool. Yes, we say that a type has "truthiness" if it can be used in a condition (`while`, `if`, `assert`, etc). For a pointer, `null` is considered "false", whereas any other value is considered "true". So you can use statements like `if(key in aa)` to test for membership. A very nice idiom is to check if a key is in an associative array, and if so, use the value that it maps to: ```d if(auto v = key in aa) { // use *v as the value here } ``` You can change your code to `return (e in this.members) !is null;` -Steve
Re: I've finally released the source code of the neural network creator, along with the module with tools written in D.
On Wednesday, 8 May 2024 at 02:28:56 UTC, Murilo wrote: I've placed the whole thing in my Github, there is the module called neuralnetwork.d, which contains tools for you to create neural networks, it has classes and functions. And there is the software Neural Network Creator which allows you to create the network only by clicking with the mouse. It is all there for anyone to use as they wish, all written purely in D. Here is the link: https://github.com/MuriloMir/Neural-network Just to give you guys a spoiler, I'm writing a biology simulator in D, it is already very impressive, I will show more later. Awesome! Your talk was great this year. Looking forward to seeing more. -Steve
Re: TIL: statically initializing an Associative Array
On Tuesday, 7 May 2024 at 00:10:27 UTC, Andy Valencia wrote: I had a set of default error messages to go with error code numbers, and did something along the lines of: string[uint] error_text = [ 400: "A message", 401: "A different message" ]; and got "expression is not a constant" I eventually found this discussion: https://issues.dlang.org/show_bug.cgi?id=6238 I understand that it's problematic, but a message which makes it clearer that compile-time initialization of global AA's are not supported? Because it cost me about a half hour trying to figure out what I was doing wrong. This error message was changed in 2.101.x (unsure which point release): ``` onlineapp.d(1): Error: static initializations of associative arrays is not allowed. onlineapp.d(1):associative arrays must be initialized at runtime: https://dlang.org/spec/hash-map.html#runtime_initialization ``` (My workaround was to initialize the data structure once during app startup.) This was fixed [in 2.106.0](https://dlang.org/changelog/2.106.0.html#dmd.static-assoc-array) please upgrade your compiler. -Steve
Re: How can I put the current value of a variable into a delegate?
On Monday, 6 May 2024 at 06:29:49 UTC, Liam McGillivray wrote: Delegates can be a pain, as they often have results different from what one would intuitively expect. This can easily result in bugs. Here's a line that caused a bug that took me awhile to find: ``` foreach(card; unitCards) card.submitted = delegate() => selectUnit(card.unit); ``` Each `UnitInfoCard` object (which `card` is a member of) contains a `Unit` object called `unit`. The intention of this line was that each object in `unitCards` would call `selectUnit` with it's own `unit` every time it calls `submitted`. Instead, every card calls `submitted` with the *last* value of `card`. Yes, this is because the foreach loop reuses the same memory slot for `card`. Even though this is allocated as a closure, it still only allocates the frame stack of the *enclosing function*, and does not allocate a new slot for each loop iteration. You can force this by using a lambda which allocates the closure: ```d foreach(card; unitCards) card.submitted = (c2) { return () => selectUnit(c2.unit); }(card); ``` This is a lambda which accepts `card` as a parameter, and returns an appropriate delegate. It is important to use a parameter, because if you just use card inside there, it's still using the single stack frame of the calling function! I renamed the inner parameter `c2` to avoid confusion, but you could name it `card` also. Essentially, the stack frame of the inner function is now allocated a closure, and it has it's own reference to `card` as a parameter. This is a very old issue: https://issues.dlang.org/show_bug.cgi?id=2043 since "moved" to https://issues.dlang.org/show_bug.cgi?id=23136 I would love to see a solution, but the workaround at least exists! -Steve
Re: Show dialog box for uncaught exception (Windows, lld-link)
On Sunday, 5 May 2024 at 14:55:20 UTC, SimonN wrote: My application is a graphical game. I close stdout and stderr by passing `-subsystem:windows` to `lld-link` to suppress the extra console window. For a few fatal errors (missing required resources, can't open display, ...), I throw exceptions, log them to logfile, then re-throw them to crash. I can tell Windows users to look in the logfile, but it would be more fitting on Windows to show an error dialog box in addition to the logging. ```d int realMain(string[] args) { // all your normal code goes here } int main(string[] args) { version(Windows) { try { realMain(args); } catch(Exception e) { visualDisplayOfException(e); throw e; } } else { // presumably, non-windows systems shouldn't show a graphical Exception // trace? realMain(args); } } ``` -Steve
Re: Phobos function to remove all occurances from dynamic array?
On Wednesday, 1 May 2024 at 01:09:33 UTC, Liam McGillivray wrote: This is presumably such a common task that I'm surprised it isn't easy to find the answer by searching; Is there a standard library function that removes all elements from a dynamic array that matches an input argument? In `std.array` there's the `replace` function which is supposed to replace all occurrences that match an input with another. It seems to work as described on strings, but I get compiler errors when using it on other array types. I've tried using it to replace occurrences of a certain object in an array with `[]` in order to remove all occurrences, but it's not allowed. Is there a Phobos function that does what I want? It would be crazy if there isn't. `remove` https://dlang.org/phobos/std_algorithm_mutation.html#remove ```d arr = arr.remove!(v => shouldBeRemoved(v)); ``` Why the reassignment? Because `remove` removes elements *in place*, and does not change the range extents. It returns the portion of the range that contains the unremoved elements. So to give an example: ```d auto arr = [1, 2, 3, 4, 5]; auto result = arr.remove!(i => i % 2 == 1); // remove odd elements assert(result == [2, 4]); // first 2 are the slice that is stored in result // the last three are leftovers. assert(arr == [2, 4, 3, 4, 5]); ``` -Steve
Re: Beerconf April
On Saturday, 13 April 2024 at 18:39:29 UTC, Steven Schveighoffer wrote: # BEERCONF! To celebrate taxes, a great eclipse (and my birthday), we will have a nice online meetup known as Beerconf. This month it is on the 27-28. Just a friendly reminder, this is happening in 2 days! See you then -Steve
Re: photon v0.7.0 with Windows support(!)
On Tuesday, 23 April 2024 at 19:05:48 UTC, Dmitry Olshansky wrote: On Tuesday, 23 April 2024 at 17:15:13 UTC, Sönke Ludwig wrote: I guess that the Darwin support will be restricted to freely distributed macOS applications, as calling `__syscall` surely is a private API that cannot be used in any AppStore application, right? You tell me;) API looks just like any other libc function. I can tell you right off that this will not be allowed in approved apps. Not just for the `__syscall`, but for overriding the normal system calls of all libraries. I can't imagine Apple will be OK with that. -Steve
Re: Adapting foreign iterators to D ranges
On Monday, 22 April 2024 at 11:36:43 UTC, Chloé wrote: The first implementation has the advantage is being simpler and empty being const, but has the downside that next is called even if the range ends up not being used. Is either approach used consistently across the D ecosystem? I always go for the simplest approach. So that means, pre-fill in the constructor. Yes, the downside is, if you don't use it, then the iterator has moved, but the range hasn't. But returning to the iterator after using the range is always a dicey proposition anyway. The huge benefit is that all the functions become simple and straightforward. But there is no "right" approach. And using composition, you may be able to achieve all approaches with wrappers. Phobos does various things depending on what people thought was good at the time. It sometimes causes some very unexpected behavior. I recommend always using the same approach for the same library, that way your users know what to expect! -Steve
Re: Statically compiled binary with C interop crashes.
On Thursday, 18 April 2024 at 11:05:07 UTC, yabobay wrote: On Wednesday, 17 April 2024 at 15:24:07 UTC, Ferhat Kurtulmuş wrote: On Wednesday, 17 April 2024 at 11:03:22 UTC, yabobay wrote: I'm using [dray](https://code.dlang.org/packages/dray) in my project with dub, here's the relevant parts of the dub.json: [...] İt seems your issue is related to the raylib itself, neither the binding you use nor the d programming language. İnstalling x11 development package may resolve the issue. I have the equivalent package installed both on the build machine and the machine i tried to run the code on. Also, no i shouldn't. It's supposed to be a statically linked binary libglfw, which is embedded statically in raylib, is trying to dynamically open libx11. https://github.com/raysan5/raylib/blob/c1fd98591d7996dd45a5ce9ecbb4b571607d417b/src/external/glfw/src/x11_init.c#L1269 So what it appears to be is, glfw tries to open a specified libx11, and fails, and then the program errors and exits. The library selected is determined by a compiler directive (see above that line), you may have to rebuild raylib with the right directive based on what libx11 you have on the system. Note, these are not *dynamically linked* libraries, but *dynamically loaded* libraries. That is, the system linker ldd is not pre-loading the library, raylib is finding the library and loading it at runtime. -Steve
Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function
On Sunday, 14 April 2024 at 22:36:18 UTC, Liam McGillivray wrote: On Friday, 12 April 2024 at 15:24:38 UTC, Steven Schveighoffer wrote: ```d void InitWindow(int width, int height, ref string title) { InitWindow(width, height, cast(const(char)*)title); } ``` This is invalid, a string may not be zero-terminated. You can't just cast. Well, it did work when I tried it (using a string variable, not a literal of course). It displayed as it is supposed to. A cast "working" isn't enough. It could work in certain cases, with certain environmental conditions, etc., but fail horribly with memory corruption in other cases. It could even happen on different runs of the program. It could happen that it works 99.999% of the time. The risk is not worth it. But from the information I can find on the web it looks like strings are sometimes but not `always` zero-terminated. Not a great look for the language. Are there any rules to determine when it is and when it isn't (for string variables)? string literals are zero-terminated. All other strings are not. If you have a string generated at compile time, the chances are good it has zero termination. However, the implicit conversion to `char *` is the clue that it is zero terminated. If that doesn't happen automatically, it's not guaranteed to be zero terminated. A string generated at runtime only has zero termination if you add a 0. You should not cast to a pointer assuming the zero is going to be there. Casting is a blunt instrument, which does not validate what you are doing is sound. A cast says "compiler, I know what I'm doing here, let me do this even though it's outside the language rules". So there are a few things to consider: 1. Is the string *transiently used*. That is, does the function just quickly use the string and never refers to it again? Given that this is raylib, the source is pretty readable, so you should be able to figure this out. I suppose. But if it turns out that the string is used continuously (as I assume to be the case with `InitWindow` and `SetWindowTitle`) and it doesn't make a copy of it, I imagine it would be difficult to design the function overload, as it would need to store a copy of the string somewhere. In that case, the only clean solution would be to have a global array of strings to store everything that's been passed to such functions, but that doesn't feel like a very satisfying solution. I may take a look inside some Raylib functions if I get back to this task. You can pin memory in the GC to ensure it's not collected by using `core.memory.GC.addRoot`, which is effectively "storing in a global array". 2. If 1 is false, will it be saved in memory that is scannable by the GC? This is one of the most pernicious issues with using C libraries from D. In this case, you will need to either allocate the memory with C `malloc` or pin the GC memory. You mean that the GC can destroy objects that still have references from the C code? Yes. If the GC is unaware of the memory that is being used by the C code, it can't scan that code for pointers. It may collect these strings early. For transiently used strings, I would point you at the function [`tempCString`](https://github.com/dlang/phobos/blob/0663564600edb3cce6e0925599ebe8a6da8c20fd/std/internal/cstring.d#L77), which allocates a temporary C string using malloc or a stack buffer, and then frees it when done with it. Thank you. In a previous thread, someone told me that having to do many deallocations slows down the program, and the GC is more efficient because it deallocates many objects simultaneously. Is this something worth considering here, or is the overhead going to be tiny even when it's called a few times per frame? In an *application*, I would recommend not worrying about the allocation performance until it becomes an issue. I'm writing a simple game, and never have worried about GC performance. When you do need to worry, you can employ strategies like preallocating all things that need allocation (still with the GC). In a *general library*, you do have to worry about the requirements of your users. If you can allocate locally (on the stack), this is the most efficient option. This is what `tempCString` does (with a fallback to `malloc` when the string gets to be large). The obvious problem in all this is to avoid accepting string literals (which are magic and automatically convert to const char *). This is currently impossible with function overloading, and so you need a separate function name, or put them in a different module. Aren't there any compile-time conditions for this? Unfortunately no. `string` does not implicitly convert to `char *` unless it is a string literal, and string literals bind to `string` before `char *`. So you can't rely on the overload working. -Steve
Beerconf April
# BEERCONF! To celebrate taxes, a great eclipse (and my birthday), we will have a nice online meetup known as Beerconf. This month it is on the 27-28. Obligatory link to beerconf T's: https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is Beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf) ## Presentations? The next live dconf is in [September](https://dconf.org/2024/index.html), and submissions are due on May 17. This means April beerconf might be a good time to try out some ideas for a presentation. Let me know if you have anything you want to schedule, via discord, email, or anywhere you find me. I will announce it, and get you an audience! Cheers! -Steve
Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function
On Friday, 12 April 2024 at 00:04:48 UTC, Liam McGillivray wrote: Here's what I wanted to do. In the library I'm working on, there are various declarations for functions defined in an external C library following the line `extern (C) @nogc nothrow:`. Here are some examples of such declarations which have a `const(char)*` parameter: ```d void InitWindow(int width, int height, const(char)* title); void SetWindowTitle(const(char)* title); Shader LoadShader(const(char)* vsFileName, const(char)* fsFileName); ``` I wanted to generate definitions of overloads of these functions using strings as parameters instead of `const(char)*`. For the `InitWindow` function shown above, the overload should be defined like this: ```d void InitWindow(int width, int height, ref string title) { InitWindow(width, height, cast(const(char)*)title); } ``` This is invalid, a string may not be zero-terminated. You can't just cast. or alternatively, like the following: ```d void InitWindow(int width, int height, string title) { InitWindow(width, height, title.toStringz); } ``` This will allocate from the GC. So there are a few things to consider: 1. Is the string *transiently used*. That is, does the function just quickly use the string and never refers to it again? Given that this is raylib, the source is pretty readable, so you should be able to figure this out. 2. If 1 is false, will it be saved in memory that is scannable by the GC? This is one of the most pernicious issues with using C libraries from D. In this case, you will need to either allocate the memory with C `malloc` or pin the GC memory. For transiently used strings, I would point you at the function [`tempCString`](https://github.com/dlang/phobos/blob/0663564600edb3cce6e0925599ebe8a6da8c20fd/std/internal/cstring.d#L77), which allocates a temporary C string using malloc or a stack buffer, and then frees it when done with it. The obvious problem in all this is to avoid accepting string literals (which are magic and automatically convert to const char *). This is currently impossible with function overloading, and so you need a separate function name, or put them in a different module. -Steve
Re: How can I tell D that function args are @nogc etc.
On Friday, 12 April 2024 at 03:57:40 UTC, John Dougan wrote: What is the procedure for bug reporting? I'm looking at the issues tracker and have no clue how to drive the search to see if this is already there. https://issues.dlang.org While entering the bug title, it does a fuzzy search for existing open and closed issues. -Steve
Re: How can I tell D that function args are @nogc etc.
On Thursday, 11 April 2024 at 03:17:36 UTC, John Dougan wrote: Interesting. Thank you to both of you. On Wednesday, 10 April 2024 at 17:38:21 UTC, Steven Schveighoffer wrote: On Wednesday, 10 April 2024 at 11:34:06 UTC, Richard (Rikki) Andrew Cattermole wrote: Place your attributes on the right hand side of the function, not the left side. Use the left side for attributes/type qualifiers that go on the return type. Just a word of warning, this explanation suggests putting qualifiers on the left side would affect the return type, this is not the case. So in my example, what did I actually tell the compiler with the placement of the attributes? And how was it different between the function type alias declaration, and the actual function declaration? More specifically, what are the semantic differences below? ```d alias FnPrefixT = @nogc nothrow @safe bool function(int); // Versus alias FnSuffixT = bool function(int) @nogc nothrow @safe; ``` So D can provide a nice mechanism to show what is happening -- `pragma(msg, ...)` If I do that with the two types above I see something *very* interesting: ```d pragma(msg, FnPrefixT); pragma(msg, FnSuffixT); ``` ``` bool function(int) nothrow @nogc bool function(int) nothrow @nogc @safe ``` That surprises me. `nothrow` and `@nogc` go onto the type, but not `@safe` if put before the declaration? I have no idea why. All I can think of is that it is a bug. and ```d @nogc nothrow @safe bool fnPrefix(int) { stuff } // Versus bool fnSuffix(int) @nogc nothrow @safe { stuff } ``` ```d pragma(msg, typeof(fnPrefix)); pragma(msg, typeof(fnSuffix)); ``` ``` nothrow @nogc @safe bool(int) nothrow @nogc @safe bool(int) ``` (as expected) -Steve
Re: mmap file performance
On Thursday, 11 April 2024 at 00:24:44 UTC, Andy Valencia wrote: I wrote a "count newlines" based on mapped files. It used about twice the CPU of the version which just read 1 meg at a time. I thought something was amiss (needless slice indirection or something), so I wrote the code in C. It had the same CPU usage as the D version. So...mapped files, not so much. Not D's fault. And writing it in C made me realize how much easier it is to code in D! For a repeatable comparison, you should provide the code which does 1MB reads. I have found that mmapped files are faster than reading buffered files, but maybe only for large files? -Steve
Re: "Error: `TypeInfo` cannot be used with -betterC" on a CTFE function
On Tuesday, 9 April 2024 at 23:50:36 UTC, Richard (Rikki) Andrew Cattermole wrote: On 10/04/2024 11:21 AM, Liam McGillivray wrote: On Sunday, 7 April 2024 at 08:59:55 UTC, Richard (Rikki) Andrew Cattermole wrote: Unfortunately runtime and CTFE are the same target in the compiler. So that function is being used for both, and hence uses GC (appending). Are you sure that string appending was really the problem that caused the "TypeInfo" build error? I forgot about this, but I had already had a working CTFE function with string appending before adding the new one that lead to this error. The symbols that it generates could be used in the program compiled with `betterC`. No, for a string it shouldn't trigger the need for TypeInfo. But that wouldn't have worked regardless. Array appending calls a runtime function which accepts `TypeInfo` (In this case, `TypeInfoGeneric!char`). So this does indeed involve `TypeInfo`. But also, even if `TypeInfo` weren't involved, it also needs the GC which is unavailable with betterC. It's just that the `TypeInfo` error happens first. The move to use templates instead of `TypeInfo` is slowly happening. -Steve
Re: How can I tell D that function args are @nogc etc.
On Wednesday, 10 April 2024 at 11:34:06 UTC, Richard (Rikki) Andrew Cattermole wrote: Place your attributes on the right hand side of the function, not the left side. Use the left side for attributes/type qualifiers that go on the return type. Just a word of warning, this explanation suggests putting qualifiers on the left side would affect the return type, this is not the case. Attributes apply to the *declaration*. In some cases this effectively applies to the return type, in some cases it applies to the function, in some cases it applies to the context pointer. In order to apply type constructors to the return type, you need to use parentheses: ```d const int foo(); // const applies to the context pointer of `foo`, not `int` const(int) bar(); // const applies to `int` return type ref int baz(); // ref applies to `baz`, which in turn means "ref returning function" ``` Where this becomes tricky is return types that are function pointers/delegates. Then using the right side of the function/delegate *type* is the only way. ```d @safe void function() foo(); // `foo` is safe, the function pointer it returns is not void function() @safe bar(); // `bar` is not safe, the function pointer returned is void function() @safe baz() @safe; // both are safe ``` -Steve
Re: Boneheaded question regarding compilation...
On Monday, 1 April 2024 at 21:23:50 UTC, WhatMeWorry wrote: Huge fan of Mike Shah's YouTube videos regarding D and his latest for D conference: https://mshah.io/conf/24/DConf%20%20Online%202024%20_%20The%20Case%20for%20Graphics%20Programming%20in%20Dlang.pdf So I installed github desktop app and cloned his Talks repo. There is a build command commented out at the top of the main.d file which I've been trying to compile, via the command line: C:\Users\kheas\Documents\Talks\2024\dconf_online\hello_triangle>dmd -g -J. main.d ./glad/gl/*.d -L-L/usr/local/lib -L-lglfw3 -of=prog && ./prog Error: cannot find input file `.\glad\gl\*.d` import path[0] = C:\D\dmd2\windows\bin64\..\..\src\phobos import path[1] = C:\D\dmd2\windows\bin64\..\..\src\druntime\import I'm using a Windows 11 machine so I thought that maybe the syntax was for Linux environment. But replacing all the '/' with '\\' did not work. Those are indeed Linux parameters and not windows compatible. This can’t be fixed by switching slash styles. You need the appropriate libs and the appropriate linker switches. -Steve
Re: Release D 2.108.0
On Monday, 1 April 2024 at 22:34:14 UTC, Iain Buclaw wrote: Glad to announce D 2.108.0, ♥ to the 36 contributors. This release comes with 8 major changes and 36 fixed Bugzilla issues, including: - In the language, named arguments for functions have been implemented and documented. - In phobos, std.uni has been upgraded to Unicode 15.1.0. - In dub, the fetch command now supports multiple arguments, recursive fetch, and is project-aware. Also in this release -- Interpolation Expression Sequences (a.k.a. string interpolation). Looks like a pretty sweet release to upgrade to! -Steve
Re: Limits of implicit conversion of class arrays
On Monday, 25 March 2024 at 07:16:35 UTC, Per Nordlöw wrote: On Saturday, 23 March 2024 at 11:04:04 UTC, Dmitry Olshansky wrote: The first and second is unsound (infamously allowed in Java). In the general case, yes. But, do you see any errors with the code ```d class Base {} class Derived : Base {} @safe pure nothrow unittest { Base b; Derived d; b = d; // pass Base[] bs; Derived[] ds; bs ~= ds; // pass bs = ds; // fail [1], should pass bs = cast(Base[])ds; // fail [2], should pass } ``` Yes, it's unsafe, as you can replace an element of `ds` with something that has no relation to `Derived`. Once you cast the slice you can populate it with Derived2 objects that are not Derived, hence breaking type safety of the ds slice. Again, in the general case, yes. So what is different in this code example compared to the general case? Hint: this has overlaps with a missing compiler optimization in dmd (and many other statically typed languages) enabled by a specific kind of data flow analysis. Which one? If there is a way to end up with a `Derived` reference to point at something that is not a `Derived` *without a cast* in system code, or *even with a cast* in safe code, then it is an error. It doesn't matter if you aren't actually doing it. If you know you are not making that mistake, change it to system, and cast to inform the compiler that you "know what you are doing". -Steve
Re: Unittests pass, and then an invalid memory operation happens after?
On Wednesday, 27 March 2024 at 21:43:48 UTC, Liam McGillivray wrote: In my current [game project](https://github.com/LiamM32/Open_Emblem), [something strange](https://github.com/LiamM32/Open_Emblem/issues/20) has happened as of a recent commit. When running `dub test`, all the unittests appear to pass, but then after the last unittest has concluded an "Invalid memory operation" happens. Removing a few lines replaces this error with a segfault, but either way, these errors shouldn't be happening. Weirdly, the commit where these errors first appear did nothing but replace a single class-member function with a seemingly identical function through a mixin template. The errors seem to be related to object deletion. The traceback output for the first error, and where GDB points to for the second error, is the destructor for my `Unit` class. You see, every `Unit` object is associated with a particular `Map` object and `Faction` object, which it hold references to. Those objects in turn each have an array of `Unit` objects that they are associated with. In the `Unit` destructor, I have it call the `removeUnit` function in both the associated `Map` and `Faction` objects. The errors are happening in either the `Unit` destructor itself, or the `removeUnit` function that it calls. Until the commit that introduced these errors, the `removeUnit` function was written directly in the `Map` class in it's module, but this commit replaced it with the mixin template `UnitArrayManagement`, which `Faction` also uses. `Unit` destructor: ``` ~this() { this.alive = false; if (this.map !is null) this.map.removeUnit(this); if (this.faction !is null) this.faction.removeUnit(this); if (this.currentTile !is null) this.currentTile.occupant = null; } ``` The GC does not guarantee destructor order. So this code is not valid -- e.g. you can't count on `map` to be a valid object at this point. In my estimation, the code is not correct in principle anyway -- if the `map` has a pointer to the `unit`, then neither will be collected without both being garbage, and so there is no need to do these calls (they are all going away presently). The *only* thing you should be doing in a destructor is freeing non-GC resources. I read that the garbage collector *sometimes* but not *always* calls destructors on deletion, which sounds crazy to me. The GC is not guaranteed to delete memory or run destructors. In the current implementation, it will destroy everything at the end of the program that was allocated using the GC, but the language does not guarantee this. The second error, which can be achieved by removing the instances of `writeln` in `removeUnit` (making it seemingly identical now to the version of this function previously defined in the `Map` class) is also strange. It seems to be a case of the `Unit` object calling a `Map` object that no longer exists. However, that's also strange, as the `Map` object is supposed to delete all it's associated units on destruction. As mentioned, GCs do not work this way -- you do not need to worry about cascading removal of anything. You should assume in the destructor that all references in the type that were pointing at GC blocks are now invalid (i.e. dangling pointers). So why are these things even happening *after* the unittests have been run? What else do I need to know about object destruction? What may be happening? The GC is cleaning up all allocated memory, in *no particular order*. -Steve
Re: Beerconf March (dconf online)
On Monday, 18 March 2024 at 22:15:49 UTC, Richard (Rikki) Andrew Cattermole wrote: Perhaps we can do the usual end of month time as well, I'll give you a ping if I can do it. Depends upon how the week leading up to it for me goes (may not go well). I missed everything, due to being on a trip -- still haven't even watched the talks! And I should remind you that the last weekend of March is Easter (and I also would not be able to be there due to other events). -Steve
Re: Reworking the control flow for my tactical role-playing game
On Sunday, 17 March 2024 at 00:14:55 UTC, Liam McGillivray wrote: As many of you know, I have been trying to write a tactical role-playing game (a mix of turn-based stategy & RPG) in D. This is the furthest I have ever gotten in making an interactive program from the main function up. Right now, it is not yet playable as a game, but you can interact with it and get a rough idea of what I'm going for. Feel free to download and run it to see what I have so far. https://github.com/LiamM32/Open_Emblem I got it to run on my mac, I had to do a few updates to the dub.sdl file, but it did work, though I couldn't figure out how to make attacks work. ## The Current Structure: The code for Open Emblem (name subject to change) is split between a source library, which handles the internal game logic, and a graphical front-end program which uses that library, but makes it usable. This is kind of cool, I like the idea! ### The Library: All sounds good ### The Raylib Front-end: After looking at many libraries and taking a shot at [ae](https://github.com/CyberShadow/ae) & [godot-D](https://github.com/godot-d/godot-d) but not really figuring it out, I was recommended [raylib-d](https://github.com/schveiguy/raylib-d), a binding for [raylib](https://www.raylib.com/) by @Steven Schveighoffer. Raylib is a rather simple graphical library written in C. I ended up sticking with it because the website has so many easy-to-follow examples that make it easy as my first graphical library. They're written in, but I adapted them to D rather easily. Of course, being written in C has limitations as it isn't object-oriented. This is front-end is in the [`oe-raylib/`](https://github.com/LiamM32/Open_Emblem/tree/master/oe-raylib) directory. For this front-end, I've made the classes `VisibleTile` and `VisibleUnit`, which inherit `Tile` & `Unit`, but add sprite data and other graphics-related functionality. I then have the `Mission` class which inherits the `MapTemp` class. This class dominates the program flow in it's current state. It handles loading data from JSON files, switching between different game phases and does most of the function calls related to rendering and input. The way I have it currently, there's a `startPreparation` function and `playerTurn` function, each of which run a once-per-frame loop that renders all the necessary objects and takes user input. They each have a rather messy set of if-statements for the UI system. Any UI elements that may pop-up are declared before the loop begins, with if-statements to determine whether they should be visible this frame. For UI elements, I currently have `version` flags for either `customgui` (which I started writing before discovering raygui) and `customgui`, which you can select between using `dub --config=`. Having both makes the code messier, but I haven't yet decided on which I prefer. They are both currently achieve equivalent functionality. Everything here is single-threaded. Despite that, I still get thousands of frames-per-second when disabling the cap on framerate. Note that disabling the cap on framerate just avoids the sleep-per-frame that raylib does. I always recommend setting a cap of something like 60 unless you are going to use vsync. To get a glimpse of a flaw with the current approach (which may be simpler to fix with an overhaul), try asking one of the units to move during your turn, but then try moving the other unit while the first one hasn't reached their destination. The first unit will stop. So when doing video game development with a main loop that needs to refresh the screen every frame, you need to componentize long-running operations into frame-size bits. So for instance, an animation that needs to move an object from A to B, should be captured into a temporary item (class object, struct, member of the sprite, etc), where you tell it every time you are drawing a frame (or even better yet, each game tick), and let it make the changes necessary for one tick of time. For instance, build an object that takes start position, end position, time to animate, and maybe a path function (like linear, ease-in/ease-out, etc), and then each frame calculates where the position should be based on the current time vs. the start time. Encapsulating all this into an object makes things easy to deal with. Then you just need to call it every frame/tick. ## Should I rework things? So now I am thinking of reworking the rendering system, but also changing some of my approach to how the Open Emblem library works. I've been thinking of adopting an event-driven approach, using signals and slots, for both the library and the front-end (and between the two). I'm curious if more experienced programmers think this is the right approach. I'm not sure if you want to do event driven here. It's a possibility. But I find a game-tick system, where each tick, you update each object
Re: Disable wrilten buf in docker
On Tuesday, 12 March 2024 at 06:36:09 UTC, zoujiaqing wrote: Hi, my application use writeln in docker don't display. Python add -u disable it. https://stackoverflow.com/questions/29663459/why-doesnt-python-app-print-anything-when-run-in-a-detached-docker-container Use setvbuf to switch to line buffering. Then you don’t have to manually flush everything https://en.cppreference.com/w/c/io/setvbuf -Steve
Beerconf March (dconf online)
# BEERCONF! Dconf online is upon us next weekend! Instead of holding the normal beerconf at the end of the month, this month we will do a special early edition, to coincide with dconf online. We will start it on the 16th, and go through Sunday as usual. ## What is Beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf) ## Presentations? Um... yeah, there [are some](https://dconf.org/2024/online/index.html) Cheers! -Steve
Re: D Language Foundation November 2023 Monthly Meeting Summary
On Monday, 4 March 2024 at 11:07:07 UTC, Mike Parker wrote: ### Steve and Me I have to apologize to Steve. I managed to botch the initial recording, so whatever he and I said at the top of the meeting is lost. I'm pretty sure I talked about preliminary planning for DConf '24, but beyond that, I don't recall. I also know that whatever Steve reported, it wasn't anything that sparked debate. The first audible words I have from him are, "That's about all I have, really." Sorry, I can't remember what I talked about in that timeframe. Lost to history I guess. (UPDATE: Ultimately, [Átila finished the proposal](https://github.com/atilaneves/DIPs/blob/string-interpolation/Interpolation.md). After [a long discussion in the forums](https://forum.dlang.org/thread/unhv5u$1gps$1...@digitalmars.com), Walter approved the feature and [it was merged](https://github.com/dlang/dmd/pull/15715). Steven Schveighoffer [is working on a spec PR](https://github.com/schveiguy/dlang.org/blob/istring/spec/istring.dd).) The spec is updated (that link is dead because I deleted the branch, always good to use the `y` button on github to get a link to the direct commit). You can still see the PR here: https://github.com/dlang/dlang.org/pull/3768 To see the spec, just go to [the current spec](https://dlang.org/spec/istring.html), for some reason we publish the master branch of the spec as the current release. -Steve
Re: New update fix
On Saturday, 2 March 2024 at 09:18:58 UTC, user1234 wrote: On Saturday, 2 March 2024 at 08:41:40 UTC, Salih Dincer wrote: SLM, What exactly did this patch with the new update fix? Nothing, it looks like what happened is that the issue was wrongly referenced by a dlang.org PR (https://github.com/dlang/dlang.org/pull/3701/commits/4e8db30f0bf3c330c3431e83fe8a75f843b40857). Not wrongly referenced. The pr changed the spec to be clearer about the behavior. The behavior did not change. The bug was closed as “fixed” incorrectly. I switched it to “wontfix” The change log generator must have picked it up because of that. -Steve
Re: Error when using `import`.
On Monday, 26 February 2024 at 23:27:49 UTC, Liam McGillivray wrote: I don't know whether I should continue this topic or start a new one now that the problem mentioned in the title is fixed. I have now uploaded some of the code to [a GitHub repository](https://github.com/LiamM32/Open_Emblem). To make this game usable, I will need a library for graphics and input. I don't have any experience with making GUI programs aside from a little bit with Qt and C++. If you are going for game development, I would recommend raylib-d (https://code.dlang.org/packages/raylib-d), which is my wrapper around the very good raylib library. For doing GUI, raygui is supported, but I also can say I've seen some good things from fluid: https://code.dlang.org/packages/fluid -Steve
Re: Error when using `import`.
On Monday, 26 February 2024 at 22:40:49 UTC, Liam McGillivray wrote: On Sunday, 25 February 2024 at 03:23:03 UTC, Paul Backus wrote: You can't give a class the same name as the file it's in. If you do, then when you try to use it from another file, the compiler will get confused and think you're referring to the file instead of the class (that's what "import is used as a type" means). Thank you. In PHP, I was told to put every class definition in a file of the same name (whether I like it or not). However, I actually now have it working *without* having done that. Both the file name and the class name are capitalized, and it's working. However, maybe that's because they each start with a `module` line that makes the module name lowercase. I will keep this in mind, and maybe rename the files. So D is weird about this. I always recommend you use a *package* (i.e. module foo.bar) instead of just a module (i.e. module bar). When you omit the module declaration, the compiler assumes the module name is the same as the file name *without the path taken into account*. What happens is if you have `Map` as a module, and then `Map` as the class name, using the name `Map` is going to be confusing (did you mean the module or the class?) However, if you have everything under a package, for example `foo`, i.e. a file `foo/Map.d` which contains the `Map` class, then when referring to `Map`, it can't be referring to the module, since you would have to refer to `foo.Map` for that. This means the class name `Map` by itself is unambiguous. A whole host of problems occurs with name lookup when you don't use packages. -Steve
Re: Beerconf February 2024
On Saturday, 10 February 2024 at 17:07:04 UTC, Steven Schveighoffer wrote: # BEERCONF! February is the short month, but it's a tad bit longer this year. However, beerconf doesn't care about this, we still just pick the last weekend, and that isn't any different. This means, Feb 24-25 is the time for having conversations about D and other fun stuff! What day is it? It's the day I tell you that Beerconf is nigh! See you in a couple days. -Steve
Re: Crow programming language
On Thursday, 15 February 2024 at 23:46:10 UTC, andy wrote: On Thursday, 15 February 2024 at 15:24:37 UTC, IchorDev wrote: You can make a scope with `nothrow`, `@nogc`, etc.: I've been setting `@safe @nogc pure nothrow:` at the top of (almost) every module, but then I still have to do it at the top of each struct in the module (if it has functions) and after each delegate type. `@safe` permeates into structs, the others do not. If you make global variables `immutable`, you can access them in `pure` functions. Is it as simple as that? I'd have to cast away the `immutable` when adding a new interned string though. Is that still the correct way to do it? No, this is not correct. What you are doing is something that is logically immutable, but not actually immutable. What you need to do is to section this off into its own module, and then use language tricks to lie to the compiler. For instance, cast a function pointer that is not pure to a pure function. Then you need to carefully review the module for correctness from an API standpoint. The language does something similar with memory allocation, which uses a global data structure to allocate memory, but effectively is giving you back memory that is unique while it is valid. -Steve
Re: The difference between the dates in years
On Saturday, 10 February 2024 at 15:53:09 UTC, Alexander Zhirov wrote: Is it possible to calculate the difference between dates in years using regular means? Something like that ``` writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1))); ``` At the same time, keep in mind that the month and day matter, because the difference between the year, taking into account the month that has not come, will be less. My abilities are not yet enough to figure it out more elegantly. OK, so I thought this was already taking into account the day of the month. This is what I came up with: ```d int diffMonthNew(Date d1, Date d2) { auto diff = d1.diffMonths(d2); if(diff > 0) return diff + (d1.day < d2.day ? -1 : 0); else if(diff < 0) return diff + (d1.day > d2.day ? 1 : 0); return 0; } ``` Then if you want the years, it would be `diffMonthNew(d1, d2) / 12` -Steve
Re: The difference between the dates in years
On Saturday, 10 February 2024 at 23:48:56 UTC, Jonathan M Davis wrote: If I understand correctly, he cares about how far into the month the dates are, whereas diffMonths ignores the smaller units, meaning that you get the same result no matter when in the month the dates are. So, 2000-05-10 - 1990-05-09 would give 10, whereas 2000-05-10 - 1990-05-30 would give 9. diffMonths / 12 would give 10 in both cases. I thought `diffMonths` was actually already taking this into account... Looking at the impl, it's pretty simple. Would it make sense to have an overload that takes into account the day as well as the month/year? This kind of stuff is sometimes tricky to get right. -Steve
Re: The difference between the dates in years
On Saturday, 10 February 2024 at 15:53:09 UTC, Alexander Zhirov wrote: Is it possible to calculate the difference between dates in years using regular means? Something like that ``` writeln(Date(1999, 3, 1).diffMonths(Date(1999, 1, 1))); ``` At the same time, keep in mind that the month and day matter, because the difference between the year, taking into account the month that has not come, will be less. My abilities are not yet enough to figure it out more elegantly. Maybe I'm not understanding the question, but why not that result / 12? -Steve
Beerconf February 2024
# BEERCONF! February is the short month, but it's a tad bit longer this year. However, beerconf doesn't care about this, we still just pick the last weekend, and that isn't any different. This means, Feb 24-25 is the time for having conversations about D and other fun stuff! Obligatory link to beerconf T's: https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is Beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf) ## Presentations? We have dconf online coming up next month, but if you had something to talk about that isn't as formal, send me a note on discord or slack, and I will announce it here. Last month, Chibisi presented his library to hook D to the R programming langauge, and it was quite interesting! I uploaded a recording of it [here](https://forum.dlang.org/post/uleppyzlyiatpkhck...@forum.dlang.org), in case you missed it. See you in a few weeks! Cheers! -Steve
Re: Beerconf January 2024
On Sunday, 21 January 2024 at 02:27:03 UTC, Steven Schveighoffer wrote: Hi everyone! On Saturday the 27th, at 17:00 UTC, github user Chibisi has asked to give a presentation on his project, [Saucer](https://github.com/chibisi/saucer). The purpose of the saucer project is to create bidirectional interop between R, the statistics programming language and D. The aim is that in time, it will have easily accessible capabilities similar to libraries like Rcpp in terms of its features and capability, but with the added advantage that the D programming language is used with R, and can bring it’s expressive power and other capabilities to build analytical software that can be made available in R as well as D being able to access R’s rich API. A live demonstration of the library in use will be included by way of an example. Hope you all can join us! I'll post a reminder just before it happens. Thanks to @realdoigt, we have a recording of this! And of course, thanks to Chibisi for the great library and presentation! https://www.youtube.com/watch?v=sA1SeDNAqCc -Steve
Re: How to get the client's MAC address in Vibe
On Wednesday, 7 February 2024 at 22:16:54 UTC, Alexander Zhirov wrote: Is there a way to identify a client by MAC address when using the Vibe library? The `NetworkAddress` [structure](https://vibed.org/api/vibe.core.net/NetworkAddress) does not provide such features. Or did I miss something? Mac is a hardware address. By the time the packets get to your server, that info is long gone. Even if you could get it, it likely is the MAC address of your router, not the peer. -Steve
Re: Scripting with Variant from std.variant: parameter passing
On Friday, 2 February 2024 at 08:22:42 UTC, Carl Sturtivant wrote: It seems I cannot pass e.g. an int argument to a Variant function parameter. What's the simplest way to work around this restriction? You'd have to implement the function that accepts the parameters and wraps in a Variant. This is the best I can come up with, which should be copy/pasteable to other shims: ```d void foo(Variant x, Variant y) { ... } import std.meta : allSatisfy; enum isVariant(T) = is(T == Variant); // this is going to suck at CTFE but... string argsAsVariants(size_t count) { import std.format; import std.range; import std.alglorithm; import std.array; return iota(count).map!(i => format("Variant(args[%s])", i).join(","); } // shim auto foo(Args...)(Args args) if (!allSatisfy!(isVariant, Args)) { mixin("return foo(", argsAsVariants(args.length), ");"); } ``` -Steve
Re: import locality with function parameters
On Friday, 2 February 2024 at 00:29:51 UTC, Carl Sturtivant wrote: Hello, I seem to recall that there is surprising template to import a module and get a type from it inside the declaration of the type of a parameter to a function, so that the module need not be imported outside of the function definition. I think there was a blog article some years ago about this where there was some indication that this or something with equivalent effect would be incorporated into D in some way. How do I define a function with a parameter that is a type in an outside module while keeping module import local to that definition? Are you thinking of this? https://dlang.org/phobos/object.html#.imported -Steve
Re: Effective String to Date conversion?
On Monday, 22 January 2024 at 10:56:04 UTC, atzensepp wrote: Dear D-gurus, being new to D I am trying my first steps and the language is quite intuitive and appealing. When reading a file and creating a hash for the reocrds I want to get only the most recent ones. For this I need to convert Date/Time-Strings to comparable DateTime-Objects. The code below works but looks a bit clumsy. Is there a more efficient (shorter) way to accomplish this? That's how I would do it also. I would note there also is a library I've used which works pretty well: https://code.dlang.org/packages/dateparser -Steve
Re: Safety is not what you think
On Tuesday, 30 January 2024 at 15:38:26 UTC, Paul Backus wrote: This definitely isn't allowed in C or C++. I wonder what the rationale is for having this behavior in D? It isn't allowed in C, but allowed in C++ https://godbolt.org/z/9xTPhsb5G As for rationale... I don't know why it wouldn't be allowed? You clearly need an lvalue to use prefix ++, and the result is the value after adding one, so why can't it be bound to a reference? I don't see where the problem would arise. -Steve
Re: Preparing for the New DIP Process
On Thursday, 25 January 2024 at 15:03:41 UTC, Max Samukha wrote: On Monday, 22 January 2024 at 23:28:40 UTC, Jonathan M Davis wrote: Of course, ultimately, different programmers have different preferences, and none of us are going to be happy about everything in any language. It's not only about preferences. The feature is inconsistent with how 'invariant' and 'synchronized' are specified. They imply class-instance-level private, while the language dictates module-level. Consider: ```d synchronized class C { private int x; private int y; invariant () { assert (x == y); } static void foo(C c) { // mutate c } } ``` Same thing. Yet would still break with some sort of "class-only private" the unittest case is also similar -- what happens if you put the unittest next to the function being tested? It's now in the class, so it can access "true" private data. Same problems, this even can happen in Java. I don't see what the difference is. Same code, same file, just in a different spot? Seems more like you just need to... not do that. -Steve
Re: Accessing array elements with a pointer-to-array
On Friday, 26 January 2024 at 11:38:39 UTC, Stephen Tashiro wrote: On Thursday, 25 January 2024 at 20:36:49 UTC, Kagamin wrote: On Thursday, 25 January 2024 at 20:11:05 UTC, Stephen Tashiro wrote: void main() { ulong [3][2] static_array = [ [0,1,2],[3,4,5] ]; static_array[2][1] = 6; } The static array has length 2, so index 2 is out of bounds, must be 0 or 1. I understand that the index 2 is out of bounds in an array of 2 things. I'm confused about the notation for multidimensional arrays. I thought that the notation uint[m][n] is read from right to left, so it denotes n arrays of m things in each array. So I expected that static_array[k][j] would denotes the kth element of the jth array. I find the following rule very straightforward to explaining it. If you have an array, it's of type `T[]`. The `T` represents the type of each element. When you access element with index `n` of this array, it's `arr[n]`, which gives you the `n+1`th `T` element in the array. So how do you match this to a static array `ulong[3][2]`? Well, the `T` in this case is `ulong[3]`, and the array part is `[2]`. So this is an array of 2 `ulong[3]`. Therefore, when you index such an array, `static_array[2]` will get the 3rd element of this 2-element array, and fail. -Steve
Re: Beerconf January 2024
On Saturday, 27 January 2024 at 16:05:46 UTC, Richard (Rikki) Andrew Cattermole wrote: Reminder Chibisi's talk on https://github.com/chibisi/saucer is in an hour! The purpose of the saucer project is to create bidirectional interop between R, the statistics programming language and D. The aim is that in time, it will have easily accessible capabilities similar to libraries like Rcpp in terms of its features and capability, but with the added advantage that the D programming language is used with R, and can bring it’s expressive power and other capabilities to build analytical software that can be made available in R as well as D being able to access R’s rich API. A live demonstration of the library in use will be included by way of an example. Talk starting now! -Steve
Re: Beerconf January 2024
On Sunday, 14 January 2024 at 20:29:06 UTC, Steven Schveighoffer wrote: # BEERCONF! Happy new year! It's getting to be that time again, where we chat about our favorite language, and enjoy some beverages! If it seems like it's been a long time, that's because it has. Last month's Beerconf was early, but now that the holidays are over, we are back to a normal schedule. The next one will be January 27-28, and I hope to see you all there! Just a reminder that this is happening in 2 days! -Steve
Re: Would this be a useful construct to add to D? auto for constructor call.
On Tuesday, 23 January 2024 at 11:11:00 UTC, ryuukk_ wrote: On Tuesday, 23 January 2024 at 06:30:08 UTC, Jonathan M Davis wrote: That being said, I expect that it would be pretty easy to write a mixin to do something like that if you really wanted to. Also, if you're simply looking to not have to name the type, you could do dataGrid = new typeof(datagrid)(15); You like to turn off people before they get the chance to develop further, this is bad Would you like to encourage proposals/work/effort that will ultimately not be accepted? I don't. I would rather tell someone no early than tell them no later. And I agree with Jonathan, zero proposals that infer type from how they are used have been accepted by Walter, this one probably will be no different. To the OP, I think the value of the feature needs to be more than just avoiding repeating the name of the type. You also can do some library tricks (unfortunately this won't count as construction, but probably is fine in most cases) ```d auto create(T, Args...)(out T val, Args args) { static if(is(T == class)) val = new T(args); else static if(...) // do eveyrything else. } ... dataGrid.create(15); ``` -Steve
Re: Providing implicit conversion of
On Sunday, 21 January 2024 at 16:05:40 UTC, Gavin Gray wrote: The following code: ulong charlie = 11; long johnstone = std.algorithm.comparison.max(0, -charlie); writeln(format!"johnstone %s"(johnstone)); Results in (without any warning(s)): johnstone -11 However you choose to look at it, this means -11 > 0 (regardless of all arguments concerning implicit conversions, 1's and 2's complements, being efficient, etc). The language should not allow unary unsigned anything. This is unlikely to get fixed, just due to the nature of D's philosophy when it comes to C compatibility. It would also break a lot of existing code. -Steve
Re: sqlite support added to sqlbuilder
On Sunday, 21 January 2024 at 21:27:30 UTC, zoujiaqing wrote: Thank you! I want postgresql :) It should be pretty straightforward. I had to rewrite a lot of it to fit the API of sqlite, those changes should make it easier to add postgresql (which is on my todo list). -Steve
Re: Delegates and values captured inside loops
On Sunday, 21 January 2024 at 14:52:45 UTC, Renato wrote: On Saturday, 20 January 2024 at 16:53:12 UTC, ryuukk_ wrote: This is the workaround according to: https://issues.dlang.org/show_bug.cgi?id=21929#c9 Go used to have the same issue [but they fixed it](https://go.dev/blog/loopvar-preview) so this is no longer a problem in Go. Perhaps D could do something about it for the same reasons the Go blog post presented. Actually, D is much worse. It appears in that post that local variables in the loop were scoped on the loop iteration, but just not the iteration variables themselves. This means, the machinery to properly capture the loop variables was trivial, just change the scope where those variables are allocated. In D, there is no loop scope. So the compiler would have to establish a new mechanism to recognize which variables to stick into a closure. It's not impossible, but it is not the same scope as what Go had to do. -Steve
Re: Beerconf January 2024
On Sunday, 14 January 2024 at 20:29:06 UTC, Steven Schveighoffer wrote: # BEERCONF! The next one will be January 27-28, and I hope to see you all there! Hi everyone! On Saturday the 27th, at 17:00 UTC, github user Chibisi has asked to give a presentation on his project, [Saucer](https://github.com/chibisi/saucer). The purpose of the saucer project is to create bidirectional interop between R, the statistics programming language and D. The aim is that in time, it will have easily accessible capabilities similar to libraries like Rcpp in terms of its features and capability, but with the added advantage that the D programming language is used with R, and can bring it’s expressive power and other capabilities to build analytical software that can be made available in R as well as D being able to access R’s rich API. A live demonstration of the library in use will be included by way of an example. Hope you all can join us! I'll post a reminder just before it happens. -Steve
Re: vector crash
On Thursday, 18 January 2024 at 03:07:13 UTC, zjh wrote: ```d import dparse.ast; import dparse.lexer; import dparse.parser : parseModule; import dparse.rollback_allocator : RollbackAllocator; import core.stdcpp.vector; import core.stdcpp.string; ... ``` I have no experience with using cpp from D, and I'm not sure exactly what you are trying to do (your code is not complete), but using `string` in this context does not mean C++ std::string, it's a D string (`immutable(char)[]`). Are you sure this is what you are wanting to do? -Steve
Re: `static` function ... cannot access variable in frame of ...
On Monday, 15 January 2024 at 22:23:27 UTC, Bastiaan Veelo wrote: On Monday, 15 January 2024 at 18:43:43 UTC, user1234 wrote: The two calls are not equivalent. so what is passed as alias need to be static too. Thanks all. I thought a static member function just isn't able to access the instance of the struct, but as I understand now it is static all the way. What I am looking for is a way to have different structs that have a member function that has the same name in all of them, that is callable without a this pointer, and able to take an alias argument. That is probably asking too much. As a workaround, you can alias the outer function in the struct: ```d struct S { alias foo = S_foo; } ``` This might be less than ideal, but at least it works. -Steve
Re: Socket handle leak and active handle warning with Vibe-D
On Monday, 15 January 2024 at 18:40:00 UTC, bomat wrote: Sorry, I probably should have mentioned I was on Windows. For testing it under Linux I commented out the call to `connectMongoDB`, since I don't have it installed there - and the warning went away. Interesting, I did not suspect that as the source of the problem at all. :P I'm now looking into how to clean up MongoDB connections properly, but don't see anything besides `cleanupConnections()` (which I'm already calling without any effect). Maybe I need to initialize it differently... I'll experiment a bit. You may have to do the same thing I did with redis: https://github.com/vibe-d/vibe.d/pull/2372 Good luck! I would also say, I don't know why Windows doesn't do the same trace info debug thing, except that probably whomever added it didn't care about windows. -Steve
Re: Socket handle leak and active handle warning with Vibe-D
On Monday, 15 January 2024 at 17:24:40 UTC, bomat wrote: On Sunday, 14 January 2024 at 20:36:44 UTC, Steven Schveighoffer wrote: There should be a version you can enable that tells you where that socket handle was allocated. That might give you a further clue as to why it's not closed when the system shuts down. I think the program tells you which version to enable when this happens, but if not, let me know and I'll find it. Thanks for the response, Steve. Hmmm, not sure if I'm missing something, but this is all the output I get from the program: ``` [main() INF] Listening for requests on http://[::1]:8080/ [main() INF] Listening for requests on http://127.0.0.1:8080/ [() INF] Received signal 2. Shutting down. [main() INF] Stopped to listen for HTTP requests on ::1:8080 [main( ) INF] Stopped to listen for HTTP requests on 127.0.0.1:8080 Warning: 1 socket handles leaked at driver shutdown. Warning: 1 socket handles leaked at driver shutdown. ``` Unless there's some switch to make it more verbose? Which driver are you using? In the posix driver, it should mention (and use) the debug flag `EventCoreLeakTrace`. https://github.com/vibe-d/eventcore/blob/7fa0a15fa541c3fcf65640ee332fd3a09c34730c/source/eventcore/drivers/posix/driver.d#L130 I didn't realize this wasn't across the board... -Steve
Re: Socket handle leak and active handle warning with Vibe-D
On Saturday, 13 January 2024 at 20:49:54 UTC, bomat wrote: I am still getting this in 2024 and vibe.d 0.9.7: ``` Warning: 1 socket handles leaked at driver shutdown. ``` I was wondering if maybe someone has new info on this... There should be a version you can enable that tells you where that socket handle was allocated. That might give you a further clue as to why it's not closed when the system shuts down. I think the program tells you which version to enable when this happens, but if not, let me know and I'll find it. -Steve
Beerconf January 2024
# BEERCONF! Happy new year! It's getting to be that time again, where we chat about our favorite language, and enjoy some beverages! If it seems like it's been a long time, that's because it has. Last month's Beerconf was early, but now that the holidays are over, we are back to a normal schedule. The next one will be January 27-28, and I hope to see you all there! Obligatory link to beerconf T's: https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf) ## Presentations? I'm always happy to schedule some time to give a presentation on something. Please contact me via the D discord or slack and I will announce it here. Cheers! -Steve
Re: Non-blocking keyboard input
On Sunday, 14 January 2024 at 13:41:26 UTC, Joe wrote: This does not actually work on my computer. It still blocks. Adam is no longer using mainstream D, and apparently not posting on this forum. I suggest you try to contact him via the arsd github page: https://github.com/adamdruppe/arsd -Steve
Re: sqlite support added to sqlbuilder
On Thursday, 4 January 2024 at 18:03:56 UTC, Leonardo wrote: On Saturday, 30 December 2023 at 22:11:55 UTC, Steven Schveighoffer wrote: auto andrei = db.fetchOne(select(ads).where(ads.firstname, " = 'Andrei'")); How SQL injection are avoided here? SQL injection is avoided by passing parameter data. You use the `param` wrapper. So if you had unqualified user input, it would be: ```d string personname = getFromUser(); auto author = db.fetchOne(select(ads).where(ads.firstname, " = ", personname.param); ``` For everything except strings, it is a static error to pass them in without the `.param` wrapper. For strings, I can't help it, there is no mechanism to find out whether you are writing SQL or giving me a parameter. This should be fixable if interpolation ever happens (and I can get rid of the requirement for `.param`). -Steve
Re: Release D 2.106.1
On Tuesday, 2 January 2024 at 02:48:29 UTC, Andrej Mitrovic wrote: Does anyone know when did named arguments initially land in the compiler, as part of which release..? I never saw it as a headline feature in any previous release notes. They are not finished yet, which is why they were not announced. Judging by run.dlang.io, it was in 2.103. -Steve
Re: Synchronisation help
On Monday, 1 January 2024 at 15:48:16 UTC, Anonymouse wrote: What is the common solution here? Do I add a module-level `Object thing` and move everything accessing the AA into `synchronized(.thing)` statements? Or maybe add a `shared static` something to `Foo` and synchronise with `synchronize(Foo.thing)`? Yeah, and the thing should be a `Mutex` object. A `Mutex` object uses it's underlying mutex primitive as its monitor. This also gives options for usage with methods as well as `synchronized` statements. Just make sure you mark it `__gshared` or `shared` so all threads see it. -Steve
sqlite support added to sqlbuilder
https://code.dlang.org/packages/sqlbuilder This project is something I use extensively in my work project, and allows dynamic building of SQL statements in a way that automatically deals with joins. It also automatically serializes directly to structs representing database rows. It was featured in my dconf 2022 online talk -- Model all the things. I just added support to use sqlite. The API isn't stable yet, but still super useful. It's one of those build-it-as-I-need-it things, so while there's a semblance of a plan, things that are finished are things that I've needed. An example (with sqlite): ```d import d2sqlite3; import std.stdio; import std.file : exists; import std.array; // yeah, I know, I need a package include here... import sqlbuilder.uda; import sqlbuilder.dataset; import sqlbuilder.dialect.sqlite; import sqlbuilder.types; import d2sqlite3; struct Author { @primaryKey @autoIncrement int id; string firstname; string lastname; static @refersTo!Book @mapping("author_id") Relation books; } struct Book { @primaryKey @autoIncrement int id; string title; string description; @mustReferTo!Author("author") int author_id; } void main() { auto shouldInitialize = !exists("books.sqlite"); auto db = Database("books.sqlite"); if(shouldInitialize) { // create the tables db.execute(createTableSql!Author); db.execute(createTableSql!Book); // add some books and authors Author walter = Author( firstname: "Walter", lastname: "Bright"); db.create(walter); // automatic serialization to sql insertion statement Author andrei = Author( firstname: "Andrei", lastname: "Alexandrescu"); db.create(andrei); db.create(Book( title: "The D Programming Language", description: "The OG D manual", author_id: andrei.id)); db.create(Book( title: "Modern C++ Design", description: "The OG C++ template manual", author_id: andrei.id)); db.create(Book( title: "The D specification", description: "The Spec of the D programming language", author_id: walter.id)); } // get an author by name DataSet!Author ads; auto andrei = db.fetchOne(select(ads).where(ads.firstname, " = 'Andrei'")); // do some selections based on the dataset of books DataSet!Book bds; foreach(booktitle, author; db.fetch(select(bds.title, bds.author))) { writefln("Found book %s, written by %s %s", booktitle, author.firstname, author.lastname); } auto andreiBooks = db.fetch(select(bds) .where(bds.author_id, " = ", andrei.id.param)).array; writeln("Andrei's books: ", andreiBooks); } ``` Code is very similar for using mysql as well, just import mysql-native and sqlbuilder.dialect.mysql. Next up would be postgresql, not sure when I'll have a need to build that... -Steve
Re: jsoniopipe now supports JSON5
On Friday, 29 December 2023 at 08:04:31 UTC, Zz wrote: Any plans on having an interface similar to std.json? I replied on the [learn forum](https://forum.dlang.org/post/szepssmksyrcdzbvs...@forum.dlang.org). -Steve
Re: jsoniopipe - exaples?
On Friday, 29 December 2023 at 08:09:58 UTC, Zz wrote: Hi, Here are some samples from the std.json documentation. Any idea on how to do something similar using jsoniopipe? Directly copied from https://dlang.org/phobos/std_json.html import std.conv : to; // parse a file or string of json into a usable structure string s = `{ "language": "D", "rating": 3.5, "code": "42" }`; JSONValue j = parseJSON(s); // j and j["language"] return JSONValue, // j["language"].str returns a string writeln(j["language"].str); // "D" writeln(j["rating"].floating); // 3.5 // check a type long x; if (const(JSONValue)* code = "code" in j) { if (code.type() == JSONType.integer) x = code.integer; else x = to!int(code.str); } // create a json struct JSONValue jj = [ "language": "D" ]; // rating doesnt exist yet, so use .object to assign jj.object["rating"] = JSONValue(3.5); // create an array to assign to list jj.object["list"] = JSONValue( ["a", "b", "c"] ); // list already exists, so .object optional jj["list"].array ~= JSONValue("D"); string jjStr = `{"language":"D","list":["a","b","c","D"],"rating":3.5}`; writeln(jj.toString); // jjStr jsoniopipe is not focused on the `JSONValue` [equivalent](https://github.com/schveiguy/jsoniopipe/blob/7d63a2e19ae46a1ae56ccab4c6c872bcce094286/source/iopipe/json/dom.d#L22) You can see it's pretty basic and just serves as a "catch any type" thing. It could easily be replaced with `std.json.JSONValue`, though I like the fact that it's templated on the string type. The main focus of jsoniopipe is parsing and serialization -- I prefer to use real concrete structs/classes rather than variant types. In fact, the huge benefit from the library is that there is no intermediate type. But yeah, I could ingest all the functionality from std.json there. Or maybe even just use `JSONValue` from std.json. Could you make an issue? -Steve
Re: How to get serve-d to find dub dependencies
On Saturday, 23 December 2023 at 16:28:28 UTC, Renato wrote: On Saturday, 23 December 2023 at 16:13:01 UTC, Renato wrote: I am trying to use dependencies, so I need dub. On emacs, the imports from dub libraries cannot be found, even though dub can build it fine. How can I get emacs/serve-d to "see" the libraries added by dub? I found that dub has a command for letting the compiler know about the load paths: ``` dub describe --data=import-paths ``` This shows the correct paths for the project, so perhaps I can pass this to serve-d somehow? I've managed to kind of hack it by adding the paths to my `.dir-locals.el`: ``` ((nil . ((indent-tabs-mode . nil) (tab-width . 4))) (d-mode . ((compile-command . "dmd -L-ld_classic -run") (eglot-workspace-configuration . (:importPath ("/Users/renato/.dub/packages/console-colors/1.1.1/console-colors/source/")) ``` Far from ideal but this makes it half work... it actually shows the definitions in the library now and I can even navigate to the source, but still for some reason the import is shown as an error: ``` Expected 'consolecolors.d' or 'consolecolors/package.d' in one of the following import paths: ``` I believe that's because this is coming from d-mode, not serve-d (as serve-d actually "sees" it now)?! Anyway, would love to know how to get serve-d to automatically detect dub libs. dub recently changed how it stores packages. serve-d uses dub as a library to figure this out, so if the dub version serve-d is linked against does not match the version of dub you use to install/build, then it won't find the library includes. Check your version of dub against the version of dub serve-d is building against. Does the VS Code do that? If it does, this should work also on emacs. VS Code has a similar problem if you have a mismatch. The solution is to use the beta/nightly release channel of serve-d if you have a recent compiler. I will note there are some packages that serve-d just can't figure out for imports, because the configuration is done via dflags. -Steve
Re: Operator "+=" overloading for class?
On Monday, 18 December 2023 at 14:38:14 UTC, Ki Rill wrote: your code just return result value, but it should not return but save result to "this" see example at https://dlang.org/spec/operatoroverloading.html#index_op_assignment I get an error, but don't understand why. ```d auto opOpAssign(string op)(Value rhs) { this = this + rhs; return this; } // Error: `this` is not an lvalue and cannot be modified ``` Assigning an object is like copying a pointer. You may think you can try overloading the assignment, but it is [forbidden](https://dlang.org/spec/operatoroverloading.html#assignment): ``` However for class types, identity assignment is not allowed. All class types have reference semantics, so identity assignment by default rebinds the left-hand-side to the argument at the right, and this is not overridable. ``` But you aren't trying to do this. Instead you are trying to reassign the `this` reference, which is a local (and also forbidden). Think about it a second, your `this + rhs` is going to allocate a *new* object. Then if the assignment to the local `this` parameter succeeded, what happens outside the member function? The true reference that is calling this will not be updated! The only way to do this I can see is to reimplement for op=, or maybe perform the operation and swap the guts out. -Steve
Re: Beerconf December 2023
On Saturday, 2 December 2023 at 21:48:21 UTC, Steven Schveighoffer wrote: # BEERCONF! So it's now down to December 16-17, which is in 2 weeks. Now in 2 days. See you there! -Steve
Re: Manually relesing memory
On Saturday, 9 December 2023 at 10:12:11 UTC, Vlad Stanimir wrote: I am new to the language and am curios about manual memory management options. From what i can tell dlang offers the option for both manul and automatic management of memory resources. You might find all the answers in this blog series https://dlang.org/blog/the-gc-series/ -Steve
Re: now I need -allinst when dmd compiles the unittest
On Friday, 1 December 2023 at 22:00:52 UTC, kdevel wrote: If I not use -allinst the linker complains when using the current msgpack-d v1.0.5, e.g. [...]msgpack-d/src/msgpack/package.d:203: undefined reference to `pure nothrow @nogc @safe immutable(char)[] core.internal.dassert._d_assert_fail!(int)._d_assert_fail!(int)._d_assert_fail(scope const(immutable(char)[]), scope ref const(int), scope ref const(int))' [...]msgpack-d/src/msgpack/packer.d:1326: undefined reference to `pure nothrow @nogc @safe immutable(char)[] core.internal.dassert._d_assert_fail!(const(int))._d_assert_fail!(int)._d_assert_fail(scope const(immutable(char)[]), scope ref const(int), scope const(int))' [...]/msgpack-d/src/msgpack/unpacker.d:1505: undefined reference to `pure nothrow @nogc @safe immutable(char)[] core.internal.dassert._d_assert_fail!(int)._d_assert_fail!(int)._d_assert_fail(scope const(immutable(char)[]), scope ref const(int), scope ref const(int))' Are you using -checkaction=context? I have discovered that this happens if you build with -checkaction=context, but druntime has not been built with it, or you are using betterC. What happens is that an assert failure will trigger a call to a druntime function, and the compiler thinks that function is already instantiated in druntime, so it skips emitting the function, and expects druntime to be linked. I'm unsure whether druntime has the appropriate checkaction functions built by default, but definitely if you use betterC it won't be linked. For reference: https://issues.dlang.org/show_bug.cgi?id=22374 https://issues.dlang.org/show_bug.cgi?id=22902 https://issues.dlang.org/show_bug.cgi?id=19937 You even reported one of these... -Steve
Re: Advent of Code 2023
On Sunday, 3 December 2023 at 18:56:32 UTC, Johannes Miesenhardt wrote: On Sunday, 3 December 2023 at 14:51:37 UTC, Siarhei Siamashka wrote: [...] Thanks, this is super helpful. I have one other question, in the solution you posted and also the one I posted in the discord today. I was required to use byLineCopy. I first used byLine but I for some reason that I can't really explain only got the last line from that. I switched to byLineCopy because I saw it in other peoples solution and that magically fixed all problems I had. What exactly happened here? byLine reuses the buffer. So it is only valid while you haven’t fetched the next line. byLineCopy makes a copy of the line to give you so it will always remain valid. In these simple small type problems I find it easier to just fetch the whole file into a string and work with that. The performance of parsing the input is negligible. -Steve
Beerconf December 2023
# BEERCONF! Beerconf this month is not on December 30-31, because that's new years eve. It's not on December 23-24 because that's Christmas eve So it's now down to December 16-17, which is in 2 weeks. Note that even though I didn't get much response to the poll I posted on Beerconf scheduling, it seems like the majority of those who answered like the current schedule, so we will keep that. Looking for the perfect gift for yourself? https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf). ## Presentations? If anyone has anything they want to share with the D world, please let me know via slack or discord and I will announce it here! Cheers! -Steve
Re: msghdr and cmsghdr mismatch for alpine musl
On Saturday, 25 November 2023 at 05:04:57 UTC, d007 wrote: `import core.sys.posix.sys.socket : msghdr, cmsghdr, iovec;` `msg_iovlen`, `msg_controllen`, `cmsg_len` is ulong for x86-64 in druntime. in alpine musl, they are int, socklen_t(uint), socklen_t(uint). Is this mismatch can cause problems is I use related api ? Yes. Mismatch of types is a really bad error for c interaction. -Steve
Re: Beerconf November
On Sunday, 12 November 2023 at 20:59:57 UTC, Steven Schveighoffer wrote: # BEERCONF! This month we will be having beerconf in 2 weeks on November 25-26. Online as usual, hope to see you all there! Happy Thanksgiving to my American friends! Beerconf in 2 days. If you haven’t yet voted, I posted a poll on moving beerconf. https://forum.dlang.org/post/igntdbcczalroyxex...@forum.dlang.org -Steve
Re: Dirty DMD
On Saturday, 18 November 2023 at 18:52:07 UTC, JN wrote: Latest DMD for Windows downloaded from here: https://downloads.dlang.org/releases/2.x/2.105.3/dmd-2.105.3.exe reports version as dirty: DMD64 D Compiler v2.105.3-dirty Copyright (C) 1999-2023 by The D Language Foundation, All Rights Reserved written by Walter Bright what does it mean by dirty? Something in the build process changes a file and therefore the thing that checks the version marks it as dirty. It’s perfectly fine, this is the official release. It’s a bit embarrassing to be honest. The windows binaries have been reporting dirty for years and nobody cares to fix it. -Steve
Re: D: How to check if a function is chained? a().b().c();
On Saturday, 18 November 2023 at 07:47:19 UTC, BoQsc wrote: Let's say we have a chain of functions. ``` a().b().c(); ``` I would like to have a behaviour in `a()` that would check if there is `b()` or `c()` chained to it. If `a();`is not chained: do a `writeln("You forgot to chain this function!");` A function that executes a program For me syntactically it is important. One real world application would be: `program("someProgramName").pipe("someOtherProgramName");` Executes and pipes output to another program. `program();` - Only executes the program. Consider adding @mustuse on the return type. https://dlang.org/spec/attribute.html#mustuse-attribute -Steve
Re: DLF September 2023 Planning Update
On Tuesday, 14 November 2023 at 20:09:53 UTC, Dennis wrote: On Tuesday, 14 November 2023 at 19:13:38 UTC, Steven Schveighoffer wrote: As I understand the current thinking, that is not what D is intending to do. Additional changes don't require a new edition to be enabled, only breaking changes. I expect editions to mostly subtract code, by turning existing deprecations into errors and enabling preview switches like nosharedaccess, dip1000, fixImmutableConv, systemVariables. This sounds like it's not the mechanism being envisioned for modifying phobos or druntime. Looking forward to the full description! -Steve
Re: Beerconf November
On Sunday, 12 November 2023 at 21:12:34 UTC, Sergey wrote: At last beerconf was discussion that last week of the month is always under pressure of deadlines and plans.. There were proposals to postpone it in the middle of the month I must not have been online during that discussion. I'm certainly open to moving it to another weekend, I can drink a beer any time of month ;) I'll set up a poll. I also just realized, this is the weekend after Thanksgiving... But my turkey coma should be over by then. -Steve
Re: DLF September 2023 Planning Update
On Tuesday, 14 November 2023 at 18:40:58 UTC, Adam D Ruppe wrote: On Tuesday, 14 November 2023 at 17:57:36 UTC, Steven Schveighoffer wrote: That's not any better. If you have to opt-in to the language as it exists, people are going to quit immediately. Counterpoint: javascript's "use strict". The absence of "use strict" does not prevent you from using latest features. If you use the later features, it infers you meant "use strict". As I understand the current thinking, that is not what D is intending to do. This could potentially work for D editions -- if you use a newer syntax/feature, then you have opted into that version of the language? But I am not sure this is worth the complication. Much easier to do the dumb thing and require specification. Does "use strict" involve library API changes? -Steve
Re: DLF September 2023 Planning Update
On Tuesday, 14 November 2023 at 16:07:26 UTC, Mike Parker wrote: Experience with deprecations has shown people don't want to take extra steps to make their outdated dependencies compile. The goal with editions is that you should never have to take any extra steps to use older code in your program. You can't do that if the default edition changes with every new compiler release. But you can do that if each module explicitly declares which edition it needs. What do we want the first experience with D to be like? A person trying out D, who writes a one-file simple application using phobos *does not care* that a lib abandoned in 2018 still compiles. So why should they be the ones paying the penalty? I get that we want to stop breaking builds. But the answer there is simple -- provide a way to do it by attributing the files, or by telling the compiler "these files are edition X" or whatever. And once you attribute it, it never breaks again. Sounds like a reasonable cost to me for those who want long-lasting code! There are other options here. Like use the filesystem to identify the edition either via config or filenames. An option to specify the latest edition via the attribute came up in our discussions, so I'm sure we'll have that. And I anticipate there'll be some way to generate source files with the appropriately decorated module declarations, probably through third-party tools like code-d, maybe from a tool that ships with (or is built into) the compiler. That's not any better. If you have to opt-in to the language as it exists, people are going to quit immediately. I'm not joking about this. Imagine spending 2 hours trying to figure out why your app that is trying out some new feature doesn't compile, only to find out after posting online that it was looking at some ancient version of phobos. -Steve
Re: First Beta 2.106.0
On Thursday, 2 November 2023 at 00:57:23 UTC, Iain Buclaw wrote: Glad to announce the first beta for the 2.106.0 release, ♥ to the 33 contributors. Kind of buried in the changelog (because it's just a few issues closed) is a really significant change coming to this version: the much-hated "statement is not reachable" warning is being removed. This might be one of the greatest releases of D ever. -Steve
Re: Struct copy constructor with inout
On Tuesday, 14 November 2023 at 13:58:17 UTC, Paul Backus wrote: It's easier to see if you compare the actual and expected argument lists side-by-side Expected: (ref const(S1) s) const Actual: (const(S1) ) ^ Mismatched 'this' argument This would be a much better output. Is this something you made up or did you get it from one of the compilers? LDC2, which is what I tested with, reported in the format that I mentioned. It might be something to add to the compiler that mismatches in `this` qualifiers should be reported separately, especially since the mutable form has no explicit qualifier. But I guess this is only an issue for constructors, because normal const functions can be called with mutable objects. That being said, I still consider this a bug, if the inout version works, the const version should work as well. I don't see the difference. So an interesting thing, if I change the `int i` to `int *i` in `S2`, instead of compiling I get the error: ``` Error: `inout` constructor `testinoutctor.S2.this` creates const object, not mutable ``` Which gives a much nicer error message! -Steve
Re: DLF September 2023 Planning Update
On Tuesday, 14 November 2023 at 08:18:20 UTC, Mike Parker wrote: * Editions will most likely be implemented via an attribute on the module declaration. We haven't discussed any details about that, but for now, just imagine something like `@edition(2024) module foo;`. When considering how this should work, I would strongly suggest it be the default to work with the current edition of the language. Nobody wants to always have to attribute their module (or whatever other opt-in mechanism) to use current features. It's going to be a WTF moment for all newcomers to D. This brings us to the problem that no prior libraries have editions marked on them. So I think there needs to be an external mechanism to be able to set the edition for a package or module from the command line, or somehow in a config file. Or you can set the "assumed" edition using a switch (but it should still default to "current"). -Steve
Re: Struct copy constructor with inout
On Tuesday, 14 November 2023 at 08:50:34 UTC, dhs wrote: I am using following code: ```d struct S1 { this(ref const S1 s) const { writeln("copy"); } int i; } struct S2 { this(ref inout S2 s) inout { writeln("copy"); } int i; } void test() { const(S1) s1; S1 ss1 = s1; // error, ss1 not qualified as const const(S2) s2; S2 ss2 = s2; // fine, why? } ``` Isn't "inout" supposed to copy the const-ness of its parameter to the constructor's attribute? In other words: why doesn't ss2=s2 fail here? `ss2 = s2` does not fail because the type is implicitly convertible to non-const (a const int can be converted to a mutable int). Change `i` to `int *` and it will fail. IMO, the first should succeed as well. And I will note that the error looks different from what you say: ``` Error: copy constructor `testinoutctor.S1.this(ref const(S1) s) const` is not callable using argument types `(const(S1))` ``` I'm not sure what this means. There shouldn't be a copy being made here, as the thing is already const. I don't understand this error, and it looks like a bug to me. -Steve
Beerconf November
# BEERCONF! This month we will be having beerconf in 2 weeks on November 25-26. Online as usual, hope to see you all there! The usual post for the official beerconf t-shirt: https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf). ## Presentations? If you want to give a presentation, please let me know either by email or discord or slack. I will make sure to announce it here! Cheers! -Steve
Re: Dlang installer with VSCode broken
On Sunday, 5 November 2023 at 22:28:29 UTC, Daniel Donnelly, Jr. wrote: This is on my friend's machine, who I am teaching D. What can be done? Can you describe what you did? Also, might be helpful to file an issue on the code-d github repository itself: https://github.com/Pure-D/code-d -Steve
Re: Convert String to Date and Add ±N Hours
On Saturday, 4 November 2023 at 18:11:53 UTC, Vahid wrote: Hi, I have a date string with the format of "2023-11-04 23:10:20". I want to convert this string to Date object and also, add ±N hours to it. For example: `"2023-11-04 23:10:20" + "+2:00" = "2023-11-05 01:10:20"` `"2023-11-04 23:10:20" + "-2:30" = "2023-11-05 20:40:20"` How can I do this? Parse the date. There is a nice package on code.dlang.org that is for date parsing: https://code.dlang.org/packages/dateparser -Steve
Re: why remove octal literal support?
On Friday, 3 November 2023 at 15:07:41 UTC, d007 wrote: dlang is know for compile speed, but in reality d project compile slow because so much ctfe and tempalte. Why bring more ctfe call by remmove octal literal ? octal literals are extremely error prone, because people sometimes use leading zeroes for alignment, not realizing that it means the number is completely different. Actual correct octal literal use is vanishingly small. Banning C-style octal literals just makes it so the compiler flags unintended errors like this. -Steve
Re: What are the best available D (not C) File input/output options?
On Thursday, 2 November 2023 at 15:46:23 UTC, confuzzled wrote: I tried std.io but write() only outputs ubyte[] while I'm trying to output text so I abandoned idea early. Just specifically to answer this, this is so you understand this is what is going into the file -- bytes. You should use a buffering library like iopipe to write properly here (it handles the encoding of text for you). And I really don't have a good formatting library, you can rely on formattedWrite maybe. A lot of things need to be better for this solution to be smooth, it's one of the things I have to work on. -Steve
Re: Beerconf October 2023
On Saturday, 14 October 2023 at 20:15:49 UTC, Steven Schveighoffer wrote: # BEERCONF! This month we will be having beerconf in 2 weeks on October 28-29. Online as usual, hope to see you all there! A reminder that this is tomorrow! -Steve
Beerconf October 2023
# BEERCONF! This month we will be having beerconf in 2 weeks on October 28-29. Online as usual, hope to see you all there! Halloween is coming up, need a costume? https://www.zazzle.com/store/dlang_swag/products?cg=196874696466206954 ## What is beerconf? Check out the [wiki article](https://wiki.dlang.org/Beerconf). ## Presentations? If you want to give a presentation, please let me know either by email or discord or slack. I will make sure to announce it here! Cheers! -Steve