Interfacing with Rust
https://forum.dlang.org/post/dudpbkerfrdlnggiz...@forum.dlang.org On Saturday, 1 October 2022 at 03:14:44 UTC, mw wrote: extern(C++)? Why do you think Rust export C++ linkage? Rust support [two mangling version](https://doc.rust-lang.org/rustc/symbol-mangling/index.html#mangling-versions) : `legacy` (C++ compatible) and `v0` (theoretical equivalent to `extern(D)`). Until the 2021 edition, legacy is still the default. Do it in plain C style, you may make it work. C ABI is more practical and stable. However, there are cases where adapting to the C style can be limiting compared to C++/D/Rust using more advanced features, including generic programming. An example of this is the use of cbindgen which mixes C with `cpp_compat`.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: Is there a way to achieve this? dub concerns ctfe risky whats this fud about? Will try to generate a .d file that would contain a static D object instead and then compile this .d file. While ctfe json is bad, you should still try to ctfe; without clarification of what the data is idk, but if you could get something like csv that would be trivial.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: Hello hello everyone ^_^, I am new in D, and started this morning. I found a way to read a file at compile time with `-J.` and `static string content = import("my_json_file.json")` https://dlang.org/spec/expression.html#import_expressions
Re: Wrapper for PAM
On Friday, 4 October 2024 at 12:39:45 UTC, Alexander Zhirov wrote: On Thursday, 3 October 2024 at 23:56:37 UTC, Salih Dincer wrote I meant taking the function to D for the elements of the C syntax. To get only an API to which we can pass our callback, and hide everything else inside the wrapper. I have no experience porting from C to D, but I would like to try to learn the basics to make a small library for PAM. https://dlang.org/spec/importc.html
Re: Wrapper for PAM
On Thursday, 3 October 2024 at 23:56:37 UTC, Salih Dincer wrote I meant taking the function to D for the elements of the C syntax. To get only an API to which we can pass our callback, and hide everything else inside the wrapper. I have no experience porting from C to D, but I would like to try to learn the basics to make a small library for PAM.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
Thank you everyone, true the compilation speed with the `static immutable string s` is unbearable for my workflow right now. Will try to generate a `.d` file that would contain a static D object instead and then compile this `.d` file.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: I am new in D, and started this morning. I found a way to read a file at compile time with `-J.` and `static string content = import("my_json_file.json")` static usually means "give this declaration the same semantics as if it were at global scope". So: ```D void main() { static struct S { int x, y; } static string v; static void fun() { } } // Same meaning as these declarations: struct S { int x, y; } string v; void fun() { } ``` This turns local variables into global variables, and nested functions which usually can access local variables into functions without access to locals. When you add `static` to a variable that is already at global scope, it does nothing. The confusion is understandable, because `static` has a million other meanings across programming languages. For example, in C and C++, static global variables/functions do have a meaning, which is similar to D's `private`. Also, `static if` and `static foreach` do imply compile time execution in D, but to enforce compile time execution on a variable, you need the `enum` or `immutable` keyword. ```D immutable string content = import("my_json_file.json") // Or inside a function: void main() { static immutable string content = import("my_json_file.json") } ``` My goal is to have a JSONValue at runtime that would be already present in the binary. Cause the JSONValue is huge. Like megabytes of data... Be careful that Compile Time Function Execution (CTFE) is not very performant, so parsing a large JSON string at compile time can be very slow and RAM hungry. If you're using dub to build your program, you might want to put the JSON object into its own package so it will be cached, and you won't have to wait so long for your build to finish every time.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 10:33:37 UTC, Ferhat Kurtulmuş wrote: On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: [...] Your issue is related to static that seems it does not trigger a compile time evaluation. According to the docs, static does not imply immutability at al. For your case, you can also use enum. https://dlang.org/spec/attribute.html#static
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: Hello hello everyone ^_^, I am new in D, and started this morning. I found a way to read a file at compile time with `-J.` and `static string content = import("my_json_file.json")` But then tried to statically evaluate with `static JSONValue j = parseJson(content)` but it fails. ```sh main.d(12): Error: variable `content` cannot be read at compile time main.d(12):called from here: `readJSON(content)` ``` Is there a way to achieve this? My goal is to have a JSONValue at runtime that would be already present in the binary. Cause the JSONValue is huge. Like megabytes of data... And no I don't want to deal with a database for now. Thank you ! Your issue is related to static that seems it does not trigger a compile time evaluation.
Re: How to evaluate a JSON file at compile time and create a struct out of it?
On Friday, 4 October 2024 at 08:45:49 UTC, holyzantaclara wrote: Hello hello everyone ^_^, I am new in D, and started this morning. I found a way to read a file at compile time with `-J.` and `static string content = import("my_json_file.json")` But then tried to statically evaluate with `static JSONValue j = parseJson(content)` but it fails. ```sh main.d(12): Error: variable `content` cannot be read at compile time main.d(12):called from here: `readJSON(content)` ``` Is there a way to achieve this? My goal is to have a JSONValue at runtime that would be already present in the binary. Cause the JSONValue is huge. Like megabytes of data... And no I don't want to deal with a database for now. Thank you ! If you use dub, have a "stringImportPaths" field in dub.json which works for me. dub.json: ``` { "name": "foo", "stringImportPaths": [ "./" ] } ``` my_json_file.json: ``` { "name": "foo" } ``` ``` import std; void main(){ immutable content = import("my_json_file.json"); pragma(msg, content); immutable mjson = parseJSON(content); writeln(mjson); } ``` ``` yields: ``` { "name": "foo" } Linking foo Running foo.exe {"name":"foo"} ```
How to evaluate a JSON file at compile time and create a struct out of it?
Hello hello everyone ^_^, I am new in D, and started this morning. I found a way to read a file at compile time with `-J.` and `static string content = import("my_json_file.json")` But then tried to statically evaluate with `static JSONValue j = parseJson(content)` but it fails. ```sh main.d(12): Error: variable `content` cannot be read at compile time main.d(12):called from here: `readJSON(content)` ``` Is there a way to achieve this? My goal is to have a JSONValue at runtime that would be already present in the binary. Cause the JSONValue is huge. Like megabytes of data... And no I don't want to deal with a database for now. Thank you !
Re: Wrapper for PAM
On Thursday, 3 October 2024 at 22:54:53 UTC, Alexander Zhirov wrote: I want to try to make access via D to PAM. ```d /// I added it here: import pam_wrapper; int main(string[] args) { if (args.length < 3) { writeln("Usage: ", args[0], " "); return 1; } /// I added it here. string username = args[1]; string password = args[2]; int result = authenticate_user(username, password); if (result == 0) { writeln("Authentication succeeded!"); } else { writefln("Authentication failed with code: %d", result); } return EXIT_SUCCESS; } ``` It is possible to implement PAM (Pluggable Authentication Modules) support in the D programming language using the standard library. The D standard library provides extern(C) support to access C language APIs and a strong FFI (Foreign Function Interface) support to adapt to C data structures. However, D itself does not include a special module for PAM, so it is necessary to work with C-based PAM libraries in the D language. I think you should use 2 separate modules! This can make type conversions and memory management safer. Here is the pam_wrapper.d file: ```d module pam_wrapper; import pam; // You have this module. import std.string, std.conv : to; import core.stdc.string : strdup; import core.stdc.stdlib : malloc, free; public import std.stdio; struct pam_data { string password; } extern(C) { int conversation_func(int num_msg, const pam_message **msg, pam_response **resp, void *appdata_ptr) { pam_data *data = cast(pam_data*)appdata_ptr; *resp = cast(pam_response *)malloc(num_msg * pam_response.sizeof); if (resp == null) return PAM_BUF_ERR; for (int i = 0; i < num_msg; i++) { switch (msg[i].msg_style) { case PAM_PROMPT_ECHO_ON: goto case; case PAM_PROMPT_ECHO_OFF: resp[i].resp = strdup(data.password.toStringz); resp[i].resp_retcode = 0; break; default: resp[i].resp = null; resp[i].resp_retcode = 0; break; } } return PAM_SUCCESS; } } int authenticate_user(string username, string password) { pam_handle_t *pamh = null; int retval = 0; pam_data data = { password }; void *appdata_ptr = &data; pam_conv conv = { cast(conversation*)&conversation_func, appdata_ptr }; retval = pam_start("login", username.toStringz, &conv, &pamh); if (retval != PAM_SUCCESS) { pam_strerror(pamh, retval).to!string.writefln!"pam_start: %s"; return 1; } retval = pam_authenticate(pamh, 0); if (retval != PAM_SUCCESS) { pam_strerror(pamh, retval).to!string.writefln!"Authentication failure: %s"; pam_end(pamh, retval); return 2; } retval = pam_end(pamh, PAM_SUCCESS); if (retval != PAM_SUCCESS) { pam_strerror(pamh, retval).to!string.writefln!"pam_end: %s"; return 3; } return 0; } ``` SDB@79
Wrapper for PAM
I want to try to make access via D to PAM. I'm trying to write basic things. I would like to know how to best transform access to callback functions? For example, so that there is no need to cast to a type and use binding to `extern`, move all this to a library? ```d extern(C): struct pam_message { int msg_style; const(char) *msg; } struct pam_response { char *resp; int resp_retcode; } alias conversation = int function(int num_msg, const pam_message **msg, pam_response **resp, void *appdata_ptr); struct pam_conv { conversation *conv; void *appdata_ptr; } struct pam_handle; alias pam_handle_t = pam_handle; const (char) *pam_strerror(pam_handle_t *pamh, int errnum); int pam_start(const(char) *service_name, const(char) *user, const pam_conv *pam_conversation, pam_handle_t **pamh); int pam_authenticate(pam_handle_t *pamh, int flags); int pam_end(pam_handle_t *pamh, int pam_status); ``` Below is the code that implements basic simple authentication. Is it possible to move `conversation_func` into a shell so as not to use type casting? What is the best way to implement this? ```d struct pam_data { string password; } extern(C) { int conversation_func(int num_msg, const pam_message **msg, pam_response **resp, void *appdata_ptr) { pam_data *data = cast(pam_data*)appdata_ptr; *resp = cast(pam_response *)malloc(num_msg * pam_response.sizeof); if (*resp == null) { return PAM_BUF_ERR; } for (int i = 0; i < num_msg; i++) { switch (msg[i].msg_style) { case PAM_PROMPT_ECHO_ON: case PAM_PROMPT_ECHO_OFF: (*resp)[i].resp = strdup(data.password.toStringz); (*resp)[i].resp_retcode = 0; break; default: (*resp)[i].resp = null; (*resp)[i].resp_retcode = 0; break; } } return PAM_SUCCESS; } } int authenticate_user(string username, string password) { pam_handle_t *pamh = null; int retval = 0; pam_data data = { password }; void *appdata_ptr = &data; pam_conv conv = { cast(conversation*)&conversation_func, appdata_ptr }; retval = pam_start("login", username.toStringz, &conv, &pamh); if (retval != PAM_SUCCESS) { writefln("pam_start: %s", pam_strerror(pamh, retval).to!string); return 1; } retval = pam_authenticate(pamh, 0); if (retval != PAM_SUCCESS) { writefln("Authentication failure: %s", pam_strerror(pamh, retval).to!string); pam_end(pamh, retval); return 2; } retval = pam_end(pamh, PAM_SUCCESS); if (retval != PAM_SUCCESS) { writefln("pam_end: %s", pam_strerror(pamh, retval).to!string); return 3; } return 0; } int main(string[] args) { string username = args[1]; string password = args[2]; int result = authenticate_user(username, password); if (result == 0) { writeln("Authentication succeeded!"); } else { writefln("Authentication failed with code: %d", result); } return EXIT_SUCCESS; } ```
Re: Hello dears, where I can deploy my vibe-d project? Someone know any hosting?
On Thursday, 3 October 2024 at 08:51:12 UTC, Danic wrote: I want to know where publish mi D web Look for Adam D. Ruppe on D IRC Channel, he used to deploy some D web apps, he may help you. Matheus.
Re: Hello dears, where I can deploy my vibe-d project? Someone know any hosting?
On Thursday, 3 October 2024 at 08:51:12 UTC, Danic wrote: I want to know where publish mi D web You didn't say what platform you were comfortable operating. For Linux, I've often used Debian on a Linode nano instance. $5/month, and with an efficient app, by the time you outgrow it, you can afford one of their $10/month or higher VPS instance upgrades. Andy
Re: Hello dears, where I can deploy my vibe-d project? Someone know any hosting?
On Thursday, 3 October 2024 at 08:51:12 UTC, Danic wrote: I want to know where publish mi D web You can try Railway or Heroku for example. Or if you like Azure you could host it there as well. I've used Azure before and it's quite easy imo.
Re: Hello dears, where I can deploy my vibe-d project? Someone know any hosting?
On Thursday, 3 October 2024 at 08:51:12 UTC, Danic wrote: I want to know where publish mi D web I think any hosting that supports binary deployment
Genuine copy of an element from an associative array
This is my (feeble) source code, for testing purposes only: uint64 sod_decompose(const uint64 n, const uint64 mod, const ref uint64[] primes, const ref uint64[uint64][uint64] factorials) { auto result = factorials[n]; for (uint64 k = 2; k < n - 1; k++) { auto backup = factorials[n]; tuple("1", backup).writeln; foreach (p, e; factorials[k]) { backup[p] -= e; } tuple("2", backup).writeln; foreach (p, e; factorials[n-k]) { backup[p] -= e; } tuple("3", backup).writeln; } return 0; } uint64 is equivalent to ulong. Upon compilation I get this error: Error: cannot modify `const` expression `backup[p]` which concerns these two lines: backup[p] -= e; Without the const statement in the function declaration the source array will be modified which is definitely not desirable. Could anybody point me to a way how to make a straight copy without meddling with the source array? Thank you!
Re: Templates considered impressive
On Tuesday, 1 October 2024 at 17:30:20 UTC, H. S. Teoh wrote: On Tue, Oct 01, 2024 at 04:30:27PM +, Salih Dincer wrote: Please add this to your MyCon structure: ```d alias value this; // assert(num1 == 3.14); ``` And test it like this too, I think it's awesome! [...] IMO it's not a good idea to recommend the use of `alias this`. It's a neat trick that solves the short-term problem... You may be right about the alias. Let's go a little further and put the convertToHex() function between the template and the struct: ```d template MyCon(T, string str = "0") { MyCon convert = str; struct MyCon { T value; //alias value this; this(R)(R data) { import std.conv : to; value = data.to!T; } mixin DownRange; } enum _input = str; string convertToHex() { import std.string : format; return _input.format!"%-(%02X%)"; } } import std.stdio; void main() { mixin MyCon!(double, "3.141") piNumber; piNumber.convertToHex().write(": "); piNumber.convert.writeln; auto iNumber = MyCon!double("0.123"); piNumber.convertToHex().write(": "); iNumber.value.writeln; // mixin MyCon!(int, "123") testError; mixin myStatement!(int, "Hello"); assert(_value == 42); // no error mixin myStatement!(double, "D!"); // assert(_value == 42); } template myStatement(T, string value = "") { auto doIt() { T.stringof.writeln(": ", value); return 42; } auto _value = doIt(); } template DownRange() { auto empty() => value <= 0; auto front() => value; auto popFront() => --value; } struct S { int value; mixin DownRange; } ``` I also added another template called DownRange (InputRange functions) inside a template. Since the structures of this mixin are static codes, unfortunately everything looks like const and cannot be changed. Please play around in the [playground](https://run.dlang.io/). I tried to show many things in the code above. Here is the output of the code: ```d /* 332E313431: [3.141, 2.141, 1.141, 0.141] 332E313431: 0.123 int: Hello double: D! */ ``` Please note iNumber, not piNumber. SDB@79
Re: Templates considered impressive
On Tue, Oct 01, 2024 at 04:30:27PM +, Salih Dincer via Digitalmars-d-learn wrote: [...] > > ``` > Please add this to your MyCon structure: > ```d > alias value this; > // assert(num1 == 3.14); > ``` > And test it like this too, I think it's awesome! [...] IMO it's not a good idea to recommend the use of `alias this`. It's a neat trick that solves the short-term problem, but in the long term it actually becomes a maintenance burden. I would recommend instead avoiding such tricks that save a bit of typing in the short-term but causes problems down the road. (I used to love using `alias this`, but over time have become convinced that it's not worth it. It makes code needlessly obscure and reduces understandability.) T -- The trouble with TCP jokes is that it's like hearing the same joke over and over.
Re: Templates considered impressive
On Tuesday, 1 October 2024 at 16:18:17 UTC, Salih Dincer wrote: ```d // ... struct MyCon { string input; T value; this(string data) { // ... } // ... } } ``` Please add this to your MyCon structure: ```d alias value this; // assert(num1 == 3.14); ``` And test it like this too, I think it's awesome! SDB@79
Re: Templates considered impressive
On Tuesday, 1 October 2024 at 01:00:08 UTC, Andy Valencia wrote: ... A conversion like: auto d = atoi!double("123.456"); is about 4k of code. Nice! Congratulations on your initiative. D is very flexible with templates, especially with the mixin templates. For example, you might like this one: ```d template MyCon (T, string str = "0") { MyCon init = str; struct MyCon { string input; T value; this(string data) { import std.conv : to; value = data.to!T; input = data; } string toString() => input; string convertToHex() { import std.string : format; return input.format!"%-(%02X%)"; } } } import std.stdio; void main() { //mixin MyCon!int;/* mixin MyCon!int zero; // There is an invisible object here: init (struct MyCon) zero.init.writeln; //* 0 */ // Here is a new object: MyCon!double num1 = "3.14"; num1.writeln; // 3.14 assert(num1.value == 3.14); // and a convenience function... :) num1.convertToHex.writeln; assert(num1.convertToHex == "332E3134"); } ``` SDB@79
Re: Templates considered impressive
On Tuesday, 1 October 2024 at 11:45:35 UTC, monkyyy wrote: On Tuesday, 1 October 2024 at 05:44:16 UTC, H. S. Teoh wrote: why spend the time and effort when you could have just done: ``` import std.conv; theres a bunch of relivent tradeoffs and phoboes doesnt make a good set of them To be fair, although Phobos sometimes has shockingly large code expansion for modest functions, in this case "123.456".to!double comes to 27k, which seems quite reasonable, even to this old 1802/6502/8080/z80/PDP-11 coder. Thanks for the pointers to the numerous ways std.conv can be used! Andy
Re: Templates considered impressive
On Tuesday, 1 October 2024 at 05:44:16 UTC, H. S. Teoh wrote: why spend the time and effort when you could have just done: ``` import std.conv; theres a bunch of relivent tradeoffs and phoboes doesnt make a good set of them
Re: Templates considered impressive
On Tue, Oct 01, 2024 at 01:00:08AM +, Andy Valencia via Digitalmars-d-learn wrote: > I had an old atoi() I wrote when I was getting started with D. You know, > fixed type, string in, int output. Today for fun I templated the type: > > T atoi(T)(string s) [...] It's all good and fun to try out how awesome D template programming, but why spend the time and effort when you could have just done: ``` import std.conv; string input = ...; int i = input.to!int; uint i = input.to!uint; short s = input.to!short; ushort us = input.to!ushort; float f = input.to!float; double d = input.to!double; ``` std.conv.to also automatically converts string to enum, handle narrowing int conversions (by inserting runtime checks), alias itself away when the target type implicitly converts from the source type (useful for generic code to eliminate redundant conversions when you don't know the input types), etc.. ``` int i = 1234; byte b = i.to!byte; // throws at runtime short s = i.to!short; // OK, range check passes enum E { a=10, b=20 } E e = "a".to!E; // returns E.a string str = "abc"; string ss = str.to!string; // same as ss = str; char[] ca = "abc"; ss = ca.to!string; // same as ss = ca.dup; ``` Basically, unless you're one of those GC-phobes, std.conv.to is literally your one-stop shop for all your type conversion needs. You can even extend it to work for your own custom types by defining the requisite ctors and opCast overloads. This is D, not C++, you shouldn't need to write your own version of std.conv.to unless you have a *very* good reason to. T -- Those who don't understand D are condemned to reinvent it, poorly. -- Daniel N
Re: Adapting foreign iterators to D ranges
On Thursday, 25 April 2024 at 03:18:36 UTC, cc wrote: On Wednesday, 24 April 2024 at 05:08:25 UTC, Salih Dincer wrote: Yes, `opApply()` works! You just need to use `do while()` instead of `while()` because it skips the first item. It depends on the type of structure being consumed, if it provides "next" as a direct pointer then yeah you would need to consume the item first before iterating to the next in line. However some APIs provide an opaque iterator type where you call a "next" method to get the first element, IIRC Lua does something like this. I've noticed a strange behavior in the Range structure that consumes the List class! If we use foreach(), we should take a backup as we're used to, or use the rewind() function as I did below. These days, I've started to delve deeper into the opApply() feature. I wanted to fix this mistake I made in the past. ```d struct Range { private List list; int opApply(scope int delegate(Node* t) dg) { while(auto current = list.Next) { if (auto r = dg(current)) return r; } list.rewind(); return 0; } } ``` Also, due to the nature of linked lists, we cannot print the number 1 added at the beginning with foreach(). Therefore, when creating the List class, it may be wise to create it without giving any parameters and start adding elements from 1. You might also be interested in this topic about opApply: https://forum.dlang.org/thread/jxzqsxasierzokgcy...@forum.dlang.org SDB@79
Re: What exactly the --allinst compiler flag does.
Thank You! I just did a test, I did not used the --allinst flag for the first time since 4-5 years. It was a superstition since that, because back then it fixed something. Now to my surprise the test build was successful :D 80KLOC, 20 modules -> 20 obj files, and the full compiling time went from 120 sec down to 107 sec. The exe started without any problems. Hopefully my other project will run too. So from now on I will only use --allinst again if I get linker errors in the future.
Re: Best practices for class instance variables as parameters
On Sat, Sep 28, 2024 at 06:16:55PM +, Ian via Digitalmars-d-learn wrote: > Hi, > > I'm coming from C and some C++ so the way D stores class instance > variables is new to me. If I'm not mistaken the basic unadorned > instance variable is like a "hidden" pointer. So, when passing class > instance variables to a function, what would be the point of passing a > pointer or ref? Passing a pointer or ref to a class variable allows the callee to modify the reference (e.g., make it point to a different instance of the class). Passing a class instance by value passes a reference to it, so the callee can still modify the instance, but they cannot change the caller's reference to it. [...] > Now I'm unsure. When I pass a class instance to a function by value, > I'm not creating a copy of the instance, am I? No, because classes are by-reference types. T -- In theory, software is implemented according to the design that has been carefully worked out beforehand. In practice, design documents are written after the fact to describe the sorry mess that has gone on before.
Re: Best practices for class instance variables as parameters
On Saturday, 28 September 2024 at 18:16:55 UTC, Ian wrote: Hi, I'm coming from C and some C++ so the way D stores class instance variables is new to me. If I'm not mistaken the basic unadorned instance variable is like a "hidden" pointer. So, when passing class instance variables to a function, what would be the point of passing a pointer or ref? An instance of a class is, of course, an object. The instance's variables can be int's or float's or struct's. Values. The instance has storage right there to hold the value. An instance can also reference another class instance. Then, underneath, that's a pointer. I think I answered myself, in that they'd would be pointers or references to the variable that holds the... hidden pointer to the class instance. I think I see you assuming that how an instance variable treats values is different from how a local variable or a struct field would treat a value. My experience is they're all the same. The important difference between struct and class instance is that structs want to be values, and you have to go to extra trouble to work with pointers thereof. Instances want to be references, and you have to go to trouble (shallow or deep copy, presumably) if you want to get a value copy. But all this applies equally to instance variables and a struct's fields. Now I'm unsure. When I pass a class instance to a function by value, I'm not creating a copy of the instance, am I? No you aren't. (Now let the much deeper Dlang minds sweep in and correct me.)
Best practices for class instance variables as parameters
Hi, I'm coming from C and some C++ so the way D stores class instance variables is new to me. If I'm not mistaken the basic unadorned instance variable is like a "hidden" pointer. So, when passing class instance variables to a function, what would be the point of passing a pointer or ref? I think I answered myself, in that they'd would be pointers or references to the variable that holds the... hidden pointer to the class instance. Now I'm unsure. When I pass a class instance to a function by value, I'm not creating a copy of the instance, am I? Thanks, Ian
Re: What exactly the --allinst compiler flag does.
On Saturday, 28 September 2024 at 12:20:43 UTC, realhet wrote: Hi, I have some statements in my mind about --allinst, but I'm not sure they are correct or not. 1. Normally the compiler analyzes the full code with all the modules, and it only compiles code for template things that are used in the given code. 2. It is not needed for compiling the code with a single compiler instance, but is required for projects that are compiled in parallel by using multiple compiler instances. Please someone tell me that these statements are valid or I know this wrong. (These are just my speculations, feelings, I didn't find documentation on this.) Speaking of speculation... "-allinst" disable an internal system of speculation that is: "this instance is already emitted so dont do it again". Over the years it has appeared that the speculation does not always work as it should. The classic symptom of that is when people encounter linker errors related to missing symbols. "-allinst" is the number one workaround. When activated, it's likely that things get emitted more than once, but at least, speculation bugs are gone. You may ask "but then there should be other linker errors about double definition ?". No, those syms has to be emitted as "weak" symbols, so the linker ignore duplicated definitions.
What exactly the --allinst compiler flag does.
Hi, I have some statements in my mind about --allinst, but I'm not sure they are correct or not. 1. Normally the compiler analyzes the full code with all the modules, and it only compiles code for template things that are used in the given code. 2. It is not needed for compiling the code with a single compiler instance, but is required for projects that are compiled in parallel by using multiple compiler instances. Please someone tell me that these statements are valid or I know this wrong. (These are just my speculations, feelings, I didn't find documentation on this.)
Re: need help to redefine packed c struct in d
On Saturday, 28 September 2024 at 08:35:39 UTC, Johan wrote: On Saturday, 28 September 2024 at 07:54:40 UTC, Dakota wrote: ```c struct __attribute__((packed)) type1 { uint32_tu32; uint8_t u8; uint16_tu16a; uint16_tu16b; uint8_t u8a; uint8_t arr[14]; }; ``` the struct size in C is 24: I try `pragma(packed)` and `align(1):`, the d size always is 25. how to fix this? Put the `align(1):` inside the struct definition. https://d.godbolt.org/z/qqsK1ro9v -Johan thanks, it work.
Re: need help to redefine packed c struct in d
On Saturday, 28 September 2024 at 07:54:40 UTC, Dakota wrote: ```c struct __attribute__((packed)) type1 { uint32_tu32; uint8_t u8; uint16_tu16a; uint16_tu16b; uint8_t u8a; uint8_t arr[14]; }; ``` the struct size in C is 24: I try `pragma(packed)` and `align(1):`, the d size always is 25. how to fix this? Put the `align(1):` inside the struct definition. https://d.godbolt.org/z/qqsK1ro9v -Johan
Perfect: using foreach with more...
😁 Try the 2nd usage, D is a very flexible language; moves towards perfection! ```d struct Sarma { int i; // mixin DownRange; } struct Foo(T) { int[] array; // 1. USAGE auto opApply(scope int delegate(T) dg) { foreach (ref e; array) { auto result = dg(T(e)); } return 0; } auto opApply(scope // 2. USAGE int delegate(size_t, int, ref int) dg) { int count; foreach (i, ref e; array) { e *= 15; ++count; auto result = dg(i, count, e); } return 0; } } import std.stdio; void main() { auto foo = Foo!Sarma( [2, 4, 6] ); foreach (Sarma e; foo) { e.write(" "); } writeln; foreach (i, s, ref e; foo) { s.writef!"counter = %s, "; i.writeln(": ", e++); } foo.array.writeln; } template DownRange() { bool empty() { return i <= 0; } auto front() { return i; } void popFront() { --i; } } ``` It may be explained in specific documentation (on 12.11.11). https://dlang.org/spec/statement.html#foreach_over_arrays SDB@79
Re: Integer precision of function return types
On Friday, 27 September 2024 at 20:28:21 UTC, H. S. Teoh wrote: ... The reason for (2) is that in UFCS chains, the only thing you really only care about is what kind of range it is that you're dealing with, and maybe the element type. What exactly the container type is, is unimportant, and in fact, stating it explicitly is detrimental to maintenance because the library that gave you that type may change the concrete type in the future while retaining the same range and element type. So by naming an explicit type for the range, you introduce a potential needless breakage in your code when you next upgrade the library. Instead, use `auto` to let the compiler figure out what the concrete type is, as long as it conforms to the expected range semantics and has a compatible element type, your code will continue to work as before. ... Once my range didn't work because I used **auto** instead of **bool** in the standard InputRange functions (I think it had something to do with **length()** too...). As I said, I'm not sure, it could also be **size_t length()**. So there are subtle cases where we should use auto, I wish I could show you but I can't think of any. SDB@79
Re: Integer precision of function return types
Jonathan M Davis via Digitalmars-d-learn wrote: Well, I don't think that auto is a particularly controversial topic among D programmers... Thank you Jonathan for that very detailed response. This thread can end now unless others really feel the need to comment. I got two outstanding responses and now have a much better understanding of why and when to use auto.
Re: Integer precision of function return types
H. S. Teoh via Digitalmars-d-learn wrote: In idiomatic D, you'd use `auto` when either (1) you don't care what the type is, you just want whatever value you get to be shoved into a variable, or (2) you *shouldn't* care what the type is, because your code shouldn't be depending on it, e.g., when you're using Voldemort types std.algorithm-style. Thank you! That was a very helpful response.
Re: Integer precision of function return types
On Friday, September 27, 2024 2:13:45 PM MDT thinkunix via Digitalmars-d-learn wrote: > monkyyy via Digitalmars-d-learn wrote: > > On Friday, 27 September 2024 at 04:23:32 UTC, thinkunix wrote: > >> What about using 'auto' as the return type? > >> I tried it and it seemed to work OK. > >> > >> Wondering if there are any good reasons to use auto, > >> or bad reasons why not to use auto here? > > > > You have started a style debate that will last a week, great work > > That was not my intent. It was an honest question. I'm here to learn > and not looking to start debates or for attitude. > > I've seen a lot of "use auto everywhere" especially in C++ and was > wondering where the D community stands on it's use. Is it generally > favored or not? > > Personally, I think auto makes understanding code harder for humans. > But in this example, it seemed like auto was a good fit. Well, I don't think that auto is a particularly controversial topic among D programmers, but there's no question that in at least some cases, it becomes a question of preference and style. auto is used heavily in D, and for some kinds of code, it has to be. In particular, range-based code routinely returns "Voldemort" types (types which you can't name) from a function. You care that it's a range (so that needs to be clear from the documentation), but you're not supposed to know or care what the actual type is. Before we had that, the signatures for a lot of range-based functions (e.g. most of std.algorithm) were actually pretty terrible to read and understand, because the explicit types were so long and messy (since it's very common for ranges to wrap one another, and they're usually templated). In a lot of those situations, you really only care about the API of the type and not what the exact type is. So, auto simplifies the code considerably and makes it easier to understand. auto is also pretty critical in generic code in general, because it allows you to not worry about the exact type you're dealing with. You just need to worry about which kinds of operations work with that particular type. So, variables get declared as auto all the time in typical D code. A lot of D programmers will only use the type explicitly with variables if they want to force a particular type or if they think that it makes that code easier to understand. auto can also make code more maintainable in that when refactoring code, the type will update automatically, so if it changes, you don't have to change it all over the place. On the flip side though, it does make it harder to know what types you're dealing with, which can sometimes make it harder to read and maintain code. So, when auto isn't actually needed, there's always going to be some debate about whether it's better to use auto or not, and that's subjective enough that you're really going to have to decide on your own what works for you. Also, for better or worse, because the function has to be compiled to determine the actual return type (so it won't work with function prototypes like in .di file), function attributes are inferred for auto return functions just like they are for templated functions, so some D programmers will make functions auto just to get the attribute inference. I would guess that as a general rule, most folks prefer explicit types in function signatures where auto isn't needed simply because it's self-documenting at that point. So, I would think that most D programmers would use an explicit type with the function being discussed in this thread, but auto will certainly work just fine. Without any explicit casts within the function, because doing math on char or ubyte results in int, the result is going to be int (as opposed to uint like in the original post). So, if that works for what the function is intended for, and the documentation is clear about what's being returned, then it's not a problem. However, in this particular case, it's arguably better to return ubyte than int or uint. That's because the result will always fit within a ubyte, and if you don't return a ubyte, the caller is going to have to cast to ubyte to do something like assign the value to a ubyte. So, simply returning auto as-is arguably isn't desirable. That being said, you can still use auto if you want to. Because the math results in int, casts to ubyte will be required regardless of whether the return type in the signature is ubyte or auto, but you could choose to use auto and have the result be ubyte thanks to the casts. Ultimately though, I would argue that in this case, auto just makes the code harder to understand. The documentation can easily say that the return type is ubyte in spite of it saying auto, but it's just as easy to ty
Re: Integer precision of function return types
On Thursday, September 26, 2024 12:53:12 AM MDT Per Nordlöw via Digitalmars-d- learn wrote: > Should a function like > > ```d > uint parseHex(in char ch) pure nothrow @safe @nogc { > switch (ch) { > case '0': .. case '9': > return ch - '0'; > case 'a': .. case 'f': > return 10 + ch - 'a'; > case 'A': .. case 'F': > return 10 + ch - 'A'; > default: > assert(0, "Non-hexadecimal character"); > } > } > ``` > > instead return an ubyte? I would argue that ubyte would be better, because it's guaranteed to fit into a ubyte, but if it returns uint, then anyone who wants to assign it to a ubyte will need to cast it, whereas you can just do the casts right here (which could mean a lot less casting if this function is used much). Not only that, but you'd be doing the casts in the code that controls the result, so if something ever changes that makes it so that the type needs to change (e.g. you make it operate on dchar instead of char), you won't end up with callers casting to ubyte when the result then doesn't actually fit into a ubyte - whereas if parseHex's function signature changes from returning ubyte to returning ushort or uint or whatnot, then the change would be caught at compile time with any code that assigned the result to a ubyte. Now, I'm guessing that it wouldn't ever make sense to change this particular function in a way that the return type needed to change, and returning uint should ultimately work just fine, but I think that restricting the surface area where narrowing casts are likely to happen will ultimately reduce the risk of bugs, and I think that it's pretty clear that there will be less casting overall if the casting is done here instead of at the call site unless the function is barely ever used. - Jonathan M Davis
Re: Integer precision of function return types
On Fri, Sep 27, 2024 at 04:13:45PM -0400, thinkunix via Digitalmars-d-learn wrote: [...] > I've seen a lot of "use auto everywhere" especially in C++ and was > wondering where the D community stands on it's use. Is it generally > favored or not? > > Personally, I think auto makes understanding code harder for humans. > But in this example, it seemed like auto was a good fit. In idiomatic D, you'd use `auto` when either (1) you don't care what the type is, you just want whatever value you get to be shoved into a variable, or (2) you *shouldn't* care what the type is, because your code shouldn't be depending on it, e.g., when you're using Voldemort types std.algorithm-style. The reason for (2) is that in UFCS chains, the only thing you really only care about is what kind of range it is that you're dealing with, and maybe the element type. What exactly the container type is, is unimportant, and in fact, stating it explicitly is detrimental to maintenance because the library that gave you that type may change the concrete type in the future while retaining the same range and element type. So by naming an explicit type for the range, you introduce a potential needless breakage in your code when you next upgrade the library. Instead, use `auto` to let the compiler figure out what the concrete type is, as long as it conforms to the expected range semantics and has a compatible element type, your code will continue to work as before. This applies not only to library upgrades, but also to code maintenance, e.g., if you decide to reshuffle the elements of a UFCS chain to fix a bug or introduce a new feature. If explicit types were always used, every such change would entail finding out and updating the type of every component in the chain -- for long chains, this quickly becomes onerous and unmaintainable. Instead, use `auto` to let the compiler figure it all out for you, and make your code independent of the concrete type so that you can simply move things around just by cutting and pasting, and you don't have to worry about updating every single referenced type. T -- How do you solve any equation? Multiply both sides by zero.
Re: Integer precision of function return types
monkyyy via Digitalmars-d-learn wrote: On Friday, 27 September 2024 at 04:23:32 UTC, thinkunix wrote: What about using 'auto' as the return type? I tried it and it seemed to work OK. Wondering if there are any good reasons to use auto, or bad reasons why not to use auto here? You have started a style debate that will last a week, great work That was not my intent. It was an honest question. I'm here to learn and not looking to start debates or for attitude. I've seen a lot of "use auto everywhere" especially in C++ and was wondering where the D community stands on it's use. Is it generally favored or not? Personally, I think auto makes understanding code harder for humans. But in this example, it seemed like auto was a good fit.
Re: Integer precision of function return types
On Friday, 27 September 2024 at 04:23:32 UTC, thinkunix wrote: What about using 'auto' as the return type? I tried it and it seemed to work OK. Wondering if there are any good reasons to use auto, or bad reasons why not to use auto here? You have started a style debate that will last a week, great work Auto is fantastic and everyone should use it more
Re: Integer precision of function return types
Per Nordlöw via Digitalmars-d-learn wrote: Should a function like ```d uint parseHex(in char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return ch - '0'; case 'a': .. case 'f': return 10 + ch - 'a'; case 'A': .. case 'F': return 10 + ch - 'A'; default: assert(0, "Non-hexadecimal character"); } } ``` instead return an ubyte? What about using 'auto' as the return type? I tried it and it seemed to work OK. Wondering if there are any good reasons to use auto, or bad reasons why not to use auto here?
Re: Integer precision of function return types
On Thursday, 26 September 2024 at 06:53:12 UTC, Per Nordlöw wrote: Should a function like ```d uint parseHex(in char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return ch - '0'; case 'a': .. case 'f': return 10 + ch - 'a'; case 'A': .. case 'F': return 10 + ch - 'A'; default: assert(0, "Non-hexadecimal character"); } } ``` instead return an ubyte? ```d ubyte parseHex(immutable char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return (ch - '0') & 0x0F; case 'a': .. case 'f': return (10 + ch - 'a') & 0x0F; case 'A': .. case 'F': return (10 + ch - 'A') & 0x0F; default: assert(0, "Non-hexadecimal character"); } } ``` I’d say yes, use `ubyte`. I also did two things: - `(…) & 0x0F` to enable value-range propagation. Essentially, the compiler understands that the result of `&` will only ever be the minimum of the operands and one operand is `0x0F` which fits in a `ubyte`, therefore the expression implicitly converts. Always use implicit conversions when they avoid using `cast`. With `cast`, in general, you can do bad things. The compiler only allows safe casts implicitly, even in `@system` code. Your code is marked `@safe`, but this is general advice. - I removed `in` from the parameter and used `immutable`. The `in` storage class means `const` as of now, but with the `-preview=in` and `-preview=dip1000` switches combined, it also means `scope` and `scope` means something to DIP1000, which can become dangerous on `@system` code. Do not use `in` unless you know why exactly you’re using it. Also, for what it’s worth, you could use an `in` and `out` contract.
Re: Integer precision of function return types
On Thursday, 26 September 2024 at 06:53:12 UTC, Per Nordlöw wrote: Should a function like ```d uint parseHex(in char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return ch - '0'; case 'a': .. case 'f': return 10 + ch - 'a'; case 'A': .. case 'F': return 10 + ch - 'A'; default: assert(0, "Non-hexadecimal character"); } } ``` instead return an ubyte? When I use standard library facilities, I try to use ubyte; for example: (See "toggle comment" in the section...) ```d void parseFromHexString(R)(out R hex, const(char)[] str) { import std.algorithm : map, copy; import std.conv : to; import std.range : front, chunks; alias T = typeof(hex.front); str.chunks(T.sizeof * 2) .map!(bin => bin .to!T(16)) .copy(hex[]); } import std.stdio; void main() { enum hex = "48656C6C6F2044202620576F726C6421"; enum size = hex.length / 2; auto sample = imported!"std.conv".hexString!hex; sample.writeln; // Hello D & World! enum hexStr = x"48656C6C6F2044202620576F726C6421"; hexStr.writeln; // Hello D & World! assert(is(typeof(hexStr) == string)); immutable int[] intStr = x"48656C6C6F2044202620576F726C6421"; intStr.writeln; // [1214606444, 1864385568, 639653743, 1919706145] int[size] buf; buf.parseFromHexString(hex); buf.writeln; //char[size] buff; /* ubyte[size] buff;/* please toggle comment with above */ buff.parseFromHexString("BADEDE"); buff.writeln; ``` But when I try to do something with my own functions, I have control and I do what I want. You can also use char below, ubyte is not a problem either: ```d auto toHexDigit(char value) { if(value > 9) value += 7; return '0' + value; } auto toHexString(R)(R str) { string result; char a, b; foreach(char c; str) { a = c / 16; b = c % 16; result ~= a.toHexDigit; result ~= b.toHexDigit; } return result; } void main() { assert(sample.toHexString == hex); } ``` SDB@79
Re: Integer precision of function return types
On Thursday, 26 September 2024 at 06:53:12 UTC, Per Nordlöw wrote: Should a function like ```d uint parseHex(in char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return ch - '0'; case 'a': .. case 'f': return 10 + ch - 'a'; case 'A': .. case 'F': return 10 + ch - 'A'; default: assert(0, "Non-hexadecimal character"); } } ``` instead return an ubyte? I have no conclusive answer: - From an ABI PoV that does not matter, it's AL vs EAX , i.e same "parent" register. - From a self-documenting PoV I'd use ubyte. But then you hit the problem of promotion of `ch - ...` and you have to cast each of them.
Re: Integer precision of function return types
On Thursday, 26 September 2024 at 06:53:12 UTC, Per Nordlöw wrote: Should a function like ```d uint parseHex(in char ch) pure nothrow @safe @nogc { switch (ch) { case '0': .. case '9': return ch - '0'; case 'a': .. case 'f': return 10 + ch - 'a'; case 'A': .. case 'F': return 10 + ch - 'A'; default: assert(0, "Non-hexadecimal character"); } } ``` instead return an ubyte? It will only matter if its stored; stack or the very probable inlining optimizations should just be as simple as possible so you dont confuse the optimizer
Re: mod of negative number
On 9/23/24 21:52, Craig Dillabaugh wrote: Why does the following program: \ import std.stdio; int main(string[] args) { uint Q = 7681; writeln("Val = ", -1 % Q); return 0; } \ Print Val = 5568 Was hoping for 1. I assume it is an integer promotion issue, but I am unsure how to resolve. I tried replacing the Q with to!int(Q) but this gave me -1, which is closer but not right either. Yes, what this does is to promote `-1` to `uint.max` and the result you are getting is `uint.max % 7686`. `-1 % 7686` does not work because division rounds towards zero, so the result of modulo may be negative. In general `a%b` will give you a value between `-abs(b)+1` and `abs(b)-1`, matching the sign of `a` (and ignoring the sign of `b`). You can use something like `auto r=a%b; if(r<0) r+=abs(b);` or `auto r=(a%b+b)%b;`, depending an your needs (note that those two are not the same for negative `b`, but they match for positive `b`). This implementation is equivalent to `(a%b+b)%b`, if you want to avoid the second modulo and the compiler is not smart enough: ```d int floormod(int a,int b){ bool sign=(a<0)^(b<0); auto r=a%b; if(sign&&r!=0) r+=b; return r; } ``` The interpretation of this is to compute the remainder for a division that rounds to negative infinity. Sometimes one might also want `a%0 = a`, but this is a special case that has to be checked as the language will give you a division by zero error.
Split by top level comma
I *strongly* believe the answer is not reasonable using phoboes tools; but Im going to leave it as an open question before I get started on something from scratch. Given well compliant phoboes-style ranges and a `ref string or retro!string` that starts with '(',')','[',']','{','}', modify that string so that you a) find the matching pair, b) return a list of indexs for where the top level commas are "(foo([1,2]),bar!"\","foobar" => "(foo([1,2]),bar!"\","",[12] retro("abc[1,2,3,4,"❤️❤️❤️❤️","\","]") => "[1,2,3,4,"❤️❤️❤️❤️","\","]", [2,4,6,8,35]
Re: mod of negative number
On Monday, 23 September 2024 at 19:52:02 UTC, Craig Dillabaugh wrote: Why does the following program: \ import std.stdio; int main(string[] args) { uint Q = 7681; writeln("Val = ", -1 % Q); return 0; } \ Print Val = 5568 Was hoping for 1. I assume it is an integer promotion issue, but I am unsure how to resolve. I tried replacing the Q with to!int(Q) but this gave me -1, which is closer but not right either. Check section "In Programming languages" - https://en.wikipedia.org/wiki/Modulo There are different operations (remainder and modulus) and operators (modulo) which could be combined in a different ways
Re: mod of negative number
On Monday, 23 September 2024 at 20:02:25 UTC, Craig Dillabaugh wrote: On Monday, 23 September 2024 at 19:52:02 UTC, Craig Dillabaugh wrote: Why does the following program: snip Opps, sorry. I was expecting 7680 (not -1 or 5568). After a bit of research I see this is the same behavior as C, so I guess that explains the result.
Re: mod of negative number
On Monday, September 23, 2024 1:52:02 PM MDT Craig Dillabaugh via Digitalmars- d-learn wrote: > Why does the following program: > > \ > import std.stdio; > > int main(string[] args) { > uint Q = 7681; > writeln("Val = ", -1 % Q); > return 0; > } > \ > > Print > Val = 5568 > > > Was hoping for 1. > > I assume it is an integer promotion issue, but I am unsure how to > resolve. I tried replacing the Q with to!int(Q) but this gave me > -1, which is closer but not right either. Well, this is what the spec says: https://dlang.org/spec/expression.html#division - Jonathan M Davis
Re: mod of negative number
On Monday, 23 September 2024 at 19:52:02 UTC, Craig Dillabaugh wrote: Why does the following program: \ import std.stdio; int main(string[] args) { uint Q = 7681; writeln("Val = ", -1 % Q); return 0; } \ Print Val = 5568 Was hoping for 1. I assume it is an integer promotion issue, but I am unsure how to resolve. I tried replacing the Q with to!int(Q) but this gave me -1, which is closer but not right either. Opps, sorry. I was expecting 7680 (not -1 or 5568).
Re: need help to work around float union non-zero init
On Friday, 20 September 2024 at 16:21:10 UTC, Nick Treleaven wrote: On Friday, 20 September 2024 at 09:38:54 UTC, Dakota wrote: Thanks to Dennis for the workaround. Thanks your all for the tips, void solution fix me problem.
Re: Easy way for FFI
On 23/09/2024 10:13 AM, Maximilian Naderer wrote: I want to create a .h file from my D modules so you’re saying this should be also possible ? There is support in the compiler, but its not really mature. https://dlang.org/dmd-windows.html#switch-HC[
Re: Easy way for FFI
Hello Richard, Thank you for the info. I thought this goes the other way around. Using a header file and converting it to a .di file. I want to create a .h file from my D modules so you’re saying this should be also possible ?
Re: Easy way for FFI
There are a number of solutions for C bindings creation. Try ImportC its built into the compiler. You can use the .di generator to emit a D file for further use and manual cleanup. https://dlang.org/spec/importc.html It does depend upon the system toolchain, so you'll want MSVC installed if you use Windows.
Easy way for FFI
Hello, so what are my / our best options to create an automatic C foreign function interface. I would like to create such interface / header file from a D module with public functions, structs which are declared with extern(C) D code module leo extern(C) void test() { } Expectation: // header file void leo_test(void);
Re: Gtkd questions
On Sunday, 22 September 2024 at 15:44:17 UTC, Ian wrote: Ron Tarrant for gtkcoding.com by the way!) Is there a place where I can ask specific Gtkd questions? I came across some For many years this has been the main place to ask GtkD-related questions: https://forum.gtkd.org/groups/GtkD/
Gtkd questions
Hi, I have started using Gtkd for my first D app. (Many thanks to Ron Tarrant for gtkcoding.com by the way!) Is there a place where I can ask specific Gtkd questions? I came across some post at some point mentioning they may have another forum but I don't remember it now. Cheers, Ian
Re: How to escape control characters?
On Thursday, 19 September 2024 at 14:30:08 UTC, Gerardo Cahn wrote: On Wednesday, 24 August 2022 at 08:12:33 UTC, Salih Dincer wrote: On Tuesday, 23 August 2022 at 23:17:21 UTC, Salih Dincer wrote: ... Actually, both structures could be combined: ```d struct EscapedString { string[1] str; this(string str) @nogc pure nothrow @safe { ...(rest clipped) ``` Thanks to all. I am using the code listed here. I can't but feel like Salieri with Mozart: I know enough D to appreciate this thread, but not enough to create this on my own... This must be a metaphor, from the past... I would like to thank you for saying "hello" to the silence. Thanks to you, I have just developed the missing parts of the code. I am sure that if the silent majority criticized such codes, the field would be beautiful. I hadn't thought about UTF codes before, they seem to work. What do you think? ```d import std.stdio; void main() { enum str = r"\tHello\xfeD\r\nProgramming\0\nWorld!\b\f"; auto u = str.unescaped(); auto e = u.escaped(); assert(e == str); u.unescaped.writeln; } auto escaped(string str) { import std.algorithm : map; import std.conv : to, toChars; import std.string : format; return str.map!(chr => () { auto code = chr.to!ulong; if (code >= 0x7f) { return code.toChars!(16, char) .format!"\\x%-(%c%)"; } switch (code) { case '\0': return `\0`; case '\b': return `\b`; case '\f': return `\f`; case '\t': return `\t`; case '\n': return `\n`; case '\r': return `\r`; case '"': return `\"`; case '\'': return `\'`; case '\\': return `\\`; //case ' ': return `\s`; default: return chr.to!string; } }()).format!"%-(%s%)"; } string unescaped(string str) { import std.format : fs = FormatSpec; import std.format : uv = unformatValue; fs!char f; auto s = `["` ~ str ~ `"]`; return uv!(string[])(s, f)[0]; } ``` SDB@79
Re: Poor Carlos does not manage to find where to eat
On Saturday, 21 September 2024 at 05:00:51 UTC, user1234 wrote: On Saturday, 21 September 2024 at 04:29:15 UTC, user1234 wrote: ```d module m; [...] Beside the childish example... D could use a system of "constraint matching score" to help Carlos. Three AndAndExps verified should have a better score than two and finally determine the selection. Template if constraints are binary, there’s no way to keep a ‘score’. If you want a new syntax for that, you can make a post in DIP ideas. Otherwise, the bools would have to keep track of ‘how many times a chained logical statement evaluated to true’ which is completely nonsensical.
Re: Poor Carlos does not manage to find where to eat
On Saturday, 21 September 2024 at 04:29:15 UTC, user1234 wrote: ```d module m; [...] Beside the childish example... D could use a system of "constraint matching score" to help Carlos. Three AndAndExps verified should have a better score than two and finally determine the selection.
Re: need help to work around float union non-zero init
On Friday, 20 September 2024 at 09:38:54 UTC, Dakota wrote: I need my struct defined as `isZeroInit`, so can I can import them as `di` file. (this also reduce build size) But I find this problem with float inside union: ```d struct test_t { union { int i32; float f32; } } static assert(__traits(isZeroInit, test_t) ); ``` ```sh Error: static assert: `__traits(isZeroInit, test_t)` is false ``` I consider this is compiler bug Fix: https://github.com/dlang/dmd/pull/16858 (it may take years to get fixed), so I am here to ask any way to workaround this problem? Write `= void` for each field with non-zero init: ``` union { int i32; float f32 = void; } ``` Thanks to Dennis for the workaround.
Re: need help to work around float union non-zero init
On Friday, 20 September 2024 at 09:38:54 UTC, Dakota wrote: I need my struct defined as `isZeroInit`, so can I can import them as `di` file. (this also reduce build size) But I find this problem with float inside union: ```d struct test_t { union { int i32; float f32; } } static assert(__traits(isZeroInit, test_t) ); ``` ```sh Error: static assert: `__traits(isZeroInit, test_t)` is false ``` I consider this is compiler bug (it may take years to get fixed), so I am here to ask any way to workaround this problem? ```d union somevalue{ int i32; float f32; } struct test_t{ somevalue a=void; } static assert(__traits(isZeroInit, test_t)); unittest{ test_t foo; assert(foo.a.i32==0); } ``` this version compiles, but you probably need to provide more details
Re: How to escape control characters?
On Thursday, 19 September 2024 at 14:30:08 UTC, Gerardo Cahn wrote: I am using the code listed here. It should be left to posterity that the code presented in this thread cannot properly escape ``` "A\xfeZ" ``` ``` BV's escape: cast(char) 0x41, cast(char) 0xFE, cast(char) 0x5A steve's: cast(char) 0x41, cast(char) 0xFE, cast(char) 0x5A ``` nor ("and possibly unicode ones too,", cy March 31, 2016) ``` "A\u00fcZ" ``` ``` BV's escape: AüZ steve's: AüZ ```
Re: need help to work around float union non-zero init
On Friday, 20 September 2024 at 09:38:54 UTC, Dakota wrote: I consider this is compiler bug (it may take years to get fixed) I've sent issues for compiler bugs and had them fixed within the next release—about month, not years. Also yes, this seems to be a compiler bug; unless there's some special case missing from the spec.
need help to work around float union non-zero init
I need my struct defined as `isZeroInit`, so can I can import them as `di` file. (this also reduce build size) But I find this problem with float inside union: ```d struct test_t { union { int i32; float f32; } } static assert(__traits(isZeroInit, test_t) ); ``` ```sh Error: static assert: `__traits(isZeroInit, test_t)` is false ``` I consider this is compiler bug (it may take years to get fixed), so I am here to ask any way to workaround this problem?
Re: How to escape control characters?
On Wednesday, 24 August 2022 at 08:12:33 UTC, Salih Dincer wrote: On Tuesday, 23 August 2022 at 23:17:21 UTC, Salih Dincer wrote: ... Actually, both structures could be combined: ```d struct EscapedString { string[1] str; this(string str) @nogc pure nothrow @safe { ...(rest clipped) ``` SDB@79 Thanks to all. I am using the code listed here. I can't but feel like Salieri with Mozart: I know enough D to appreciate this thread, but not enough to create this on my own...
Using C header libs with importC
https://forum.dlang.org/post/qpmqvhipfyyyehvoe...@forum.dlang.org On Monday, 8 January 2024 at 23:00:02 UTC, Dennis wrote: On Monday, 8 January 2024 at 21:56:10 UTC, Renato wrote: but I tried exactly that! Which gives a seg fault. Looks like there's a bug with the -H switch: https://issues.dlang.org/show_bug.cgi?id=24326 But that shouldn't be necessary, you should just be able to import the c file. I also tried just importing this little C file, but then no symbols from the h file are found at all. Kind of interesting, as if I just write the code using the library in the C file itself, that works fine. That's weird, I'll see if I can reproduce this. Did you manage to reproduce the bug?
Re: vibe-d linker error: undefined reference to deimos openssl
On Saturday, 14 September 2024 at 12:31:01 UTC, Steven Schveighoffer wrote: On Tuesday, 10 September 2024 at 20:41:12 UTC, Curtis Spencer wrote: I'm attempting to upgrade the vibe-d dependencies of a project. The project compiles fine using `dub`, but the linker fails with: … I'm at a loss for how to fix this linker error. Any help would be appreciated. You may have to specify the OpenSSL version with vibe-stream:tls https://vibed.org/docs#http-https -Steve Thanks. I added the following to my dub.sdl file: ``` dependency "vibe-stream:tls" version="~>1.0" subConfiguration "vibe-stream:tls" "openssl-3.0" ``` but I am still getting essentially the same error: ``` /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x70): undefined reference to `_D6deimos7openssl3bio12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x78): undefined reference to `_D6deimos7openssl3err12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x80): undefined reference to `_D6deimos7openssl8opensslv12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x88): undefined reference to `_D6deimos7openssl4rand12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x90): undefined reference to `_D6deimos7openssl3ssl12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0x98): undefined reference to `_D6deimos7openssl5stack12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-stream-1.1.0/vibe-stream/tls/.dub/build/openssl-3.0-debug-linux.posix-x86_64-dmd_v2.101.2-FEA5B9042BC39B78C28FD73CFFA319B61AF4FDBEB7F2781D40C450C1C5A40CC0/libvibe-stream_tls.a(openssl.o):(.data.rel.ro+0xa0): undefined reference to `_D6deimos7openssl6x509v312__ModuleInfoZ' collect2: error: ld returned 1 exit status Error: linker exited with status 1 ``` Also, should I be using `vibe-d:stream` or `vibe-d:tls` in my dub.sdl file? I'm a little confused because both sub-projects are listed [here](https://code.dlang.org/packages/vibe-d), but `vibe-tls` isn't in the project structure a little further down like `vibe-stream` is.
Re: vibe-d linker error: undefined reference to deimos openssl
On Tuesday, 10 September 2024 at 20:41:12 UTC, Curtis Spencer wrote: I'm attempting to upgrade the vibe-d dependencies of a project. The project compiles fine using `dub`, but the linker fails with: … I'm at a loss for how to fix this linker error. Any help would be appreciated. You may have to specify the OpenSSL version with vibe-stream:tls https://vibed.org/docs#http-https -Steve
Re: assert
On Thursday, 12 September 2024 at 22:34:04 UTC, user1234 wrote: On Wednesday, 11 September 2024 at 10:08:29 UTC, ryuukk_ wrote: On Wednesday, 11 September 2024 at 09:14:39 UTC, Nick Treleaven wrote: On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: [...] I again apologies for being wrong and i apologies again for trying to improve things, i didn't meant to do that, i now may leave again Oh no please stay, your unrecognisable passive aggressive style is so useful. To put it more gently, ryuukk--and following the generally congenial and informative flavor of communications here--you may not realize that your messages have an abrasive feel to them. It really does make a difference to be polite and even respectful when people seek to help you by answering your questions. Showing gratitude makes it much more likely that these valuable contributors stay around and answer newbie questions in the future. Andy
Re: assert
On Wednesday, 11 September 2024 at 10:08:29 UTC, ryuukk_ wrote: On Wednesday, 11 September 2024 at 09:14:39 UTC, Nick Treleaven wrote: On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: [...] I again apologies for being wrong and i apologies again for trying to improve things, i didn't meant to do that, i now may leave again Oh no please stay, your unrecognisable passive aggressive style is so useful.
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Wednesday, 11 September 2024 at 22:06:54 UTC, WB wrote: Honestly, D, does not really need it, and most of solutions (like above) do have one or few limitations and drawbacks. Some will be acceptable in some projects, some not. There is plenty of stuff in language and library already, adding small things like that are not really the best thing. There is plenty of very successful languages, that do not offer this (Go, C++, Python 3.5 and earlier, Lua, older JavaScript, etc) and just adding it will not make D automatically more successful. I feel there is too much already in D and standard library, and things are added to quickly and eagerly, and years later we end up in a mess that cannot be solved (because of compatibility). Yes, I agree; what I see is a very complicated Phobos2. Because it has become like this over time and submodules have been developed to eliminate the confusion. For example, there are things in std.math that we do not use often, a very basic algorithm like gcd() is expected to be written in std.numeric or the factorial() function by you. In short, Phobos3 will adapt better to the language for beginners if it is written systematically from the beginning; std.math should be reorganized from scratch. SDB@79
Re: assert
On Wednesday, 11 September 2024 at 04:01:53 UTC, f wrote: i mean , is this a bug? This is not a bug. The problem is due to a misunderstanding of the -release parameter. The following related topic opened by Steven and the answers given by Walter are really valuable: https://forum.dlang.org/thread/pkeasakdbugctqdye...@forum.dlang.org SDB@79
Re: assert
On Wednesday, 11 September 2024 at 16:40:05 UTC, Bradley Chatha wrote: On Wednesday, 11 September 2024 at 12:17:02 UTC, Fox wrote: I don't care about whether it's a bug or not, I just want to learn What illegal instructions did this "assert(false);" code create? Fortunately Godbolt supports D, so it's easy to see that it generates `ud2` on x86(_64): https://godbolt.org/z/4zq67boMW This is great, thanks.
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Wednesday, 11 September 2024 at 22:06:54 UTC, WB wrote: I feel there is too much already in D and standard library, and things are added to quickly and eagerly, and years later we end up in a mess that cannot be solved (because of compatibility). this isnt autodecoding, cant be, your oping in debuging code and is for temp stuff
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Wednesday, 11 September 2024 at 19:44:54 UTC, Salih Dincer wrote: It looks clean and understandable. What is not understandable is that it has not been included in std.stdio for over 10 years. I know, string interpolation has just been integrated, but why hasn't something like this been developed in 10 years that would have no side effects and would attract the attention of beginners? SDB@79 Honestly, D, does not really need it, and most of solutions (like above) do have one or few limitations and drawbacks. Some will be acceptable in some projects, some not. There is plenty of stuff in language and library already, adding small things like that are not really the best thing. There is plenty of very successful languages, that do not offer this (Go, C++, Python 3.5 and earlier, Lua, older JavaScript, etc) and just adding it will not make D automatically more successful. I feel there is too much already in D and standard library, and things are added to quickly and eagerly, and years later we end up in a mess that cannot be solved (because of compatibility). Interpolation strings (added this year) are ok and pretty decent, and well tough in terms of what one can do with them. We still do not know if it is a good or bad design, but we will see. Interpolation string are way more powerful, and cleaner, so it is good half solution like my mixin echo code was not used as a general solution. If you want to use something, just put it in your own project, and it will work to your liking. It does not need to be in a standard library.
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Wednesday, 11 September 2024 at 18:29:39 UTC, WB wrote: This code is about 13 years old, but still works. (It is functional and works, but I never it used more than what is in this repo). But now that we have interpolation sequences in the language, it would be way easier, cleaner and more powerful to use them. ```d assert(echo2("T $i, b, ${i-2}") == "writefln(\"T \", i, \", b, \", (i-2));\n"); ``` It looks clean and understandable. What is not understandable is that it has not been included in std.stdio for over 10 years. I know, string interpolation has just been integrated, but why hasn't something like this been developed in 10 years that would have no side effects and would attract the attention of beginners? SDB@79
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Sunday, 8 September 2024 at 22:01:10 UTC, WraithGlade wrote: Specifically, I want a way to create a print command that behaves like `@show` from Julia lang or `dump` from (if my memory is correct) Nim. Yes. https://github.com/baryluk/echo/blob/master/echo.d#L205-L209 ```d mixin(echo("echo test: i=$i j=$j Escaping: \\$j, Complicated i+j=${i+j}, End of tests.")); ``` There are other ways of doing similar (using mixing templates for example), but the machinery would be very similar. This code is about 13 years old, but still works. (It is functional and works, but I never it used more than what is in this repo). But now that we have interpolation sequences in the language, it would be way easier, cleaner and more powerful to use them. I have my custom Linux IO library, that utilizes this, and you can do thing like this: ```d Println(i"Ala ma $(ShortHex(123+foo*bar)) $(&m3) $(y.ptr) maybe"); ``` (with zero memory allocations or excessive memory copies).
Re: assert
On Wednesday, 11 September 2024 at 12:17:02 UTC, Fox wrote: I don't care about whether it's a bug or not, I just want to learn What illegal instructions did this "assert(false);" code create? Fortunately Godbolt supports D, so it's easy to see that it generates `ud2` on x86(_64): https://godbolt.org/z/4zq67boMW
Re: assert
I don't care about whether it's a bug or not, I just want to learn What illegal instructions did this "assert(false);" code create?
Re: assert
On Wednesday, 11 September 2024 at 10:08:29 UTC, ryuukk_ wrote: On Wednesday, 11 September 2024 at 09:14:39 UTC, Nick Treleaven wrote: On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: It is a bug, don't claim it is not, the compiler gives the wrong information, wich lead to a confused user You don't want confused users, you want compiler say what's up, if i type assert, it should assert, end of the story The behaviour is by design, it is not a bug, it is documented in the spec: https://dlang.org/spec/expression.html#assert-ct Oh right, "illegal instruction" is what users should read in order to "fix" their code I again apologies for being wrong and i apologies again for trying to improve things, i didn't meant to do that, i now may leave again You can say that the error message is weird with -release, but it's not a bug.
Re: assert
On Wednesday, 11 September 2024 at 09:14:39 UTC, Nick Treleaven wrote: On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: It is a bug, don't claim it is not, the compiler gives the wrong information, wich lead to a confused user You don't want confused users, you want compiler say what's up, if i type assert, it should assert, end of the story The behaviour is by design, it is not a bug, it is documented in the spec: https://dlang.org/spec/expression.html#assert-ct Oh right, "illegal instruction" is what users should read in order to "fix" their code I again apologies for being wrong and i apologies again for trying to improve things, i didn't meant to do that, i now may leave again
Re: assert
On Wednesday, 11 September 2024 at 08:08:45 UTC, ryuukk_ wrote: It is a bug, don't claim it is not, the compiler gives the wrong information, wich lead to a confused user You don't want confused users, you want compiler say what's up, if i type assert, it should assert, end of the story The behaviour is by design, it is not a bug, it is documented in the spec: https://dlang.org/spec/expression.html#assert-ct
Re: assert
On Tuesday, September 10, 2024 10:01:53 PM MDT f via Digitalmars-d-learn wrote: > i mean , is this a bug? No, it's not a bug. Assertions with an expression that is known to be false at compile time are treated as special. They are always left in the generated code so that they will kill your program if you ever hit that line of code. So, assertions which actually need to be validated at runtime will be compiled out with -release, but assert(false) is always there, and with -release, instead of throwing an AssertError, it immediately terminates the program. One common use case for this would be something like auto foo(int i) nothrow { try { ... } catch(Exception) { assert(false, "It should be impossible for this code to throw."); } } where you have code that you know will never throw given the input that you're giving it, but it's not nothrow, because it could throw under other circumstances. And so in order to call that code within a nothrow function, you wrap it in a try-catch block, and then just in case you screwed up, and it does somehow throw, the assertion is triggered even with -release, and your program is terminated instead of continuing in an invalid state. - Jonathan M Davis
Re: assert
i mean , is this a bug?
assert
void main() { assert(false); } dmd -release a.d dmd version 2.109.1 debian bookworm x64 illegal instruction thanks
vibe-d linker error: undefined reference to deimos openssl
I'm attempting to upgrade the vibe-d dependencies of a project. The project compiles fine using `dub`, but the linker fails with: ``` /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x70): undefined reference to `_D6deimos7openssl3bio12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x78): undefined reference to `_D6deimos7openssl3err12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x80): undefined reference to `_D6deimos7openssl8opensslv12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x88): undefined reference to `_D6deimos7openssl4rand12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x90): undefined reference to `_D6deimos7openssl3ssl12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0x98): undefined reference to `_D6deimos7openssl5stack12__ModuleInfoZ' /usr/bin/ld: ../../.dub/packages/vibe-d-0.9.8/vibe-d/tls/.dub/build/openssl-debug-linux.posix-x86_64-dmd_v2.101.2-BCC9E2A9CB402B67930FAFFBF7360088035232BADBED8A5363A1A4DE1DBD7D7C/libvibe-d_tls.a(openssl.o):(.data.rel.ro+0xa0): undefined reference to `_D6deimos7openssl6x509v312__ModuleInfoZ' collect2: error: ld returned 1 exit status Error: linker exited with status 1 ``` Here's version info: ``` $ dub --version DUB version 1.30.0, built on Jan 1 2023 $ dmd --version DMD64 D Compiler v2.101.2 Copyright (C) 1999-2022 by The D Language Foundation, All Rights Reserved written by Walter Bright $ openssl version OpenSSL 3.0.13 30 Jan 2024 (Library: OpenSSL 3.0.13 30 Jan 2024) ``` And my dub dependencies are: ``` dependency "vibe-core" version="~>2.9.0" dependency "vibe-d:http" version="~>0.9.8" dependency "vibe-d:data" version="~>0.9.8" dependency "openssl" version="~>3.3.3" ``` I'm running Ubuntu 24.04 and have libssl-dev installed. ``` $ cat /etc/os-release PRETTY_NAME="Ubuntu 24.04.1 LTS" NAME="Ubuntu" VERSION_ID="24.04" VERSION="24.04.1 LTS (Noble Numbat)" VERSION_CODENAME=noble ID=ubuntu ID_LIKE=debian HOME_URL="https://www.ubuntu.com/"; SUPPORT_URL="https://help.ubuntu.com/"; BUG_REPORT_URL="https://bugs.launchpad.net/ubuntu/"; PRIVACY_POLICY_URL="https://www.ubuntu.com/legal/terms-and-policies/privacy-policy"; UBUNTU_CODENAME=noble LOGO=ubuntu-logo $ apt list --installed | grep libssl libssl-dev/noble-updates,noble-security,now 3.0.13-0ubuntu3.4 amd64 [installed] libssl3t64/noble-updates,noble-security,now 3.0.13-0ubuntu3.4 amd64 [installed,automatic] ``` I'm at a loss for how to fix this linker error. Any help would be appreciated.
Re: Can the send function send an array?
OK, It works, thanks. // dlang tries to use the type system to make one be clear about what data is shared between potentially concurrent threads. // You need that data to be "shared" before you can send it between threads. // Andy import std.concurrency; import std.stdio; void main(){ int N=10; shared int[] arr1=new int[N]; for(int i; i
Re: Can the send function send an array?
On Tuesday, 10 September 2024 at 13:14:05 UTC, Fox wrote: // I am learning how to send and receive data. The following is my intention, but it cannot be compiled. // aliases to mutable thread-local data not allowed, what does it mean? thank you. dlang tries to use the type system to make one be clear about what data is shared between potentially concurrent threads. You need that data to be "shared" before you can send it between threads. Andy
Can the send function send an array?
// I am learning how to send and receive data. The following is my intention, but it cannot be compiled. // aliases to mutable thread-local data not allowed, what does it mean? thank you. I am learning how to send and receive. The following is my intention, but it cannot be compiled. Report import std.concurrency; import std.stdio; import std.exception; void main(){ int N=5; int[] arr1= new int[N]; for(int i; i
Re: Problem with assertThrown
On Tuesday, 10 September 2024 at 01:04:15 UTC, Jonathan M Davis wrote: When I run it locally, assertThrown passes as expected for test case 5, and the same happens on run.dlang.io, so nothing in my specific setup is making it pass when it normally wouldn't. So, unless you verified that your example failed (and since you forgot to include that enum, I suspect you didn't), I would guess that whatever your problem is went away when you reduced the code to provide the example for your question. I would note however, that the message for the AssertError that you provided did not come from assertThrown, since while assertThrown does take the file and line number from the caller, its message starts with "assertThrown failed:", whereas your error message was the generic message that you get from an assertion failure. So, whatever is going wrong in your code, assertThrown is not determining that your code didn't throw and then throwing an AssertError. It looks like an assertion on line #283 of whatever code you actually ran (which is clearly longer than the example you provided, since it's not that long) is failing. - Jonathan M Davis Ah! *(forehead slap)* Thank you! It was actually an assert in the immediately following unittest block failing (which I hadn't added a message to). I should have tried my reduced version before posting. Thanks, Kookman
Re: Problem with assertThrown
On Monday, September 9, 2024 6:40:07 PM MDT kookman via Digitalmars-d-learn wrote: > On Tuesday, 10 September 2024 at 00:27:43 UTC, Jonathan M Davis > > wrote: > > On Monday, September 9, 2024 5:46:18 PM MDT kookman via > > > > Digitalmars-d-learn wrote: > >> It seems like assertThrown works as expected for case 4, but > >> mysteriously not working for case 5 - despite the code under > >> test raising the same exception. Am I missing something stupid > >> here? > > > > At a glance, it looks like the part of case 5 which explicitly > > catches the Exception and the part that uses assertThrown > > should behave the same, but your example doesn't actually > > compile (you didn't include a definition for base32Alphabet), > > so it's not actually possible to reproduce your problem. > > > > - Jonathan M Davis > > Thanks Jonathan. Sorry I missed the excerpt for base32Alphabet - > included below: > > ``` > enum base32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; > ``` When I run it locally, assertThrown passes as expected for test case 5, and the same happens on run.dlang.io, so nothing in my specific setup is making it pass when it normally wouldn't. So, unless you verified that your example failed (and since you forgot to include that enum, I suspect you didn't), I would guess that whatever your problem is went away when you reduced the code to provide the example for your question. I would note however, that the message for the AssertError that you provided did not come from assertThrown, since while assertThrown does take the file and line number from the caller, its message starts with "assertThrown failed:", whereas your error message was the generic message that you get from an assertion failure. So, whatever is going wrong in your code, assertThrown is not determining that your code didn't throw and then throwing an AssertError. It looks like an assertion on line #283 of whatever code you actually ran (which is clearly longer than the example you provided, since it's not that long) is failing. - Jonathan M Davis
Re: Problem with assertThrown
On Tuesday, 10 September 2024 at 00:27:43 UTC, Jonathan M Davis wrote: On Monday, September 9, 2024 5:46:18 PM MDT kookman via Digitalmars-d-learn wrote: It seems like assertThrown works as expected for case 4, but mysteriously not working for case 5 - despite the code under test raising the same exception. Am I missing something stupid here? At a glance, it looks like the part of case 5 which explicitly catches the Exception and the part that uses assertThrown should behave the same, but your example doesn't actually compile (you didn't include a definition for base32Alphabet), so it's not actually possible to reproduce your problem. - Jonathan M Davis Thanks Jonathan. Sorry I missed the excerpt for base32Alphabet - included below: ``` enum base32Alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"; ```
Re: Problem with assertThrown
On Monday, September 9, 2024 5:46:18 PM MDT kookman via Digitalmars-d-learn wrote: > It seems like assertThrown works as expected for case 4, but > mysteriously not working for case 5 - despite the code under test > raising the same exception. Am I missing something stupid here? At a glance, it looks like the part of case 5 which explicitly catches the Exception and the part that uses assertThrown should behave the same, but your example doesn't actually compile (you didn't include a definition for base32Alphabet), so it's not actually possible to reproduce your problem. - Jonathan M Davis
Problem with assertThrown
I'm having trouble understanding why the assertThrown in unit test 5 is not behaving in the code below: ``` ubyte[] decodeBase32(string encoded) { import std.string: indexOf, stripRight; // Remove padding if present encoded = encoded.stripRight("="); ubyte[] result; size_t bitBuffer = 0; int bitBufferLen = 0; foreach (char c; encoded) { auto index = base32Alphabet.indexOf(c); if (index == -1) throw new Exception("Invalid character in base32 string"); bitBuffer = (bitBuffer << 5) | index; bitBufferLen += 5; while (bitBufferLen >= 8) { bitBufferLen -= 8; result ~= cast(ubyte)((bitBuffer >> bitBufferLen) & 0xFF); } } return result; } unittest { import std.algorithm.comparison: equal; import std.string: representation; import std.stdio: writeln; writeln("Testing new implementation:"); // Test case 1: Basic "Hello world" example string encoded = "JBSWY3DPEB3W64TMMQ=="; auto expected = "Hello world".representation; ubyte[] result = decodeBase32(encoded); assert(result.equal(expected), "Test case 1 failed: 'Hello World' decoding"); // Test case 2: Empty string should return an empty array writeln("Test case 2: Empty string should return an empty array"); encoded = ""; expected = []; result = decodeBase32(encoded); assert(result == expected, "Test case 2 failed: Empty string decoding"); // Test case 3: "foobar" in Base32 writeln("Test case 3: 'foobar' in Base32"); encoded = "MZXW6YTBOI=="; expected = [102, 111, 111, 98, 97, 114]; // "foobar" result = decodeBase32(encoded); assert(result == expected, "Test case 3 failed: 'foobar' decoding"); import std.exception: assertThrown; // Test case 4: Test with padding in the middle (invalid) writeln("Test case 4: Test with padding in the middle (invalid)"); assertThrown(decodeBase32("JBSWY=3DPEB=="), "Test case 4 failed: Invalid input with padding in the middle should throw"); // Test case 5: Invalid character in input string writeln("Test case 5: Invalid character in input string"); // '@' is not a valid Base32 character try { result = decodeBase32("JBSWY3DP@B3W64TMMQ"); } catch (Exception e) { writeln("case 5 passed really..., exception msg was: ", e.msg); } // for some reason the below fails, giving an assert error (ie, no exception thrown) assertThrown(decodeBase32("JBSWY3DP@B3W64TMMQ"), "Test case 5 failed: Invalid character should throw an exception"); } ``` When I compile with unit tests on, I get this output: ``` Testing new implementation: Test case 2: Empty string should return an empty array Test case 3: 'foobar' in Base32 Test case 4: Test with padding in the middle (invalid) Test case 5: Invalid character in input string case 5 passed really..., exception msg was: Invalid character in base32 string core.exception.AssertError@src/encoding.d(283): Assertion failure ``` It seems like assertThrown works as expected for case 4, but mysteriously not working for case 5 - despite the code under test raising the same exception. Am I missing something stupid here?
Re: Is it possible to use templates to implement something like the `@show` macro from the Julia programming langauge in D?
On Monday, 9 September 2024 at 20:52:09 UTC, WraithGlade wrote: In any case, this version seems more brittle than the others at least After all, you will need it in 2 ways: 1. to learn, 2. to test. After testing, you can disable it with just the version parameter while compiling. It is even possible to turn it on/off by embedding ```// version = logOn; in the code and removing the comment feature. For this, embed VERSION(logOn) in the relevant lines... SDB@79