Re: How to hash SHA256 from string?
On Sunday, 3 December 2023 at 13:42:53 UTC, zoujiaqing wrote: Use botan so easy: Well, what about: ```D import std.digest.sha; import std.stdio; void main() { string appKey = "1"; appKey.sha256Of.toHexString.writeln; } ``` Not sure if it's really more complicated than Botan 路♂️️
Re: D style - member functions
On Wednesday, 26 April 2023 at 18:24:08 UTC, DLearner wrote: Consider: ``` struct S1 { int A; int B; int foo() { return(A+B); } } struct S2 { int A; int B; } int fnAddS2(S2 X) { return (X.A + X.B); } There are scenarios that won't let you use the second form, e.g. putting your struct under the `with()` statement: ```d with (S1) { auto sum = foo(); // Works correctly } with (S2) { auto sum = foo(); // Error: function foo(S s) is not callable using argument types () } ``` In this case, the first option will be better. But there are no real "best practices" defined AFAIK. However, the second form let you generalize the pattern by using template declaration: ```d int fnAdd(T)(T v) { return (v.A + v.B); // Doesn't matter what type is this if it has both members A and B } s1.fnAdd(); s2.fnAdd(); ```
Re: Returning a reference to be manipulated
On Thursday, 13 April 2023 at 07:05:10 UTC, Chris Katko wrote: I'm trying to figure out how to return a reference to something that may not be a reference type. ```d @safe: struct Stats { float[string] data; ref opIndex(string key) return { // The `require()` takes care of non-existing values, initializing them return data.require(key, 0); } } void main() { import std.stdio; Stats foo; // 1. You can't "capture" a reference, only use it directly foo["tacos"] += 2; // 2. You can use an alternative function-calling form (sometimes replaced by the `with` operator) ((ref float val) => val += 2)(foo["burritos"]); // 3. As a last resort, use pointers or make struct wrappers around them auto x = ["quesadillas"]; *x += 2; writeln(foo); } ```
Re: constant pointer failing to compile
On Thursday, 6 April 2023 at 20:23:29 UTC, Jacob Shtokolov wrote: On Thursday, 6 April 2023 at 00:46:26 UTC, Josh Holtrop wrote: I am trying to port a small C project to D and am getting a Ah, just noticed that other people have already responded! Sorry about that! BTW, your `[0]` C-like pointer will also work in D's version, although it's probably a bit uglier.
Re: constant pointer failing to compile
On Thursday, 6 April 2023 at 00:46:26 UTC, Josh Holtrop wrote: I am trying to port a small C project to D and am getting a compilation error I don't understand. It seems like the compiler is just missing some type hints. Try this: ```d import std.stdio; __gshared immutable ubyte[4] data = [1, 2, 3, 4]; __gshared immutable ubyte* p = data.ptr; int main() { writeln("*p = ", *p); return 0; } ``` Look how I provided the `ubyte[4]` hint to the compiler so it thinks that it's a constant. I'm not sure why this happens, but sometimes the compiler can't deduce static arrays, especially if you're explicitly saying that they're not static (`ubyte[]`).
Re: Convert binary to UUID from LDAP
On Tuesday, 28 March 2023 at 05:05:58 UTC, Alexander Zhirov wrote: `Error: cannot cast expression 'cast(ubyte*)arr' of type 'ubyte*' to 'ubyte[16]'` Here is the working example: ```d import std.stdio; import std.uuid; void main() { ubyte[] arr = [159, 199, 22, 163, 13, 74, 145, 73, 158, 112, 7, 192, 12, 193, 7, 194]; UUID(arr[0 .. 16]).writeln; } ``` You just need to take a slice of your array to guarantee that it has only 16 elements, and thus, pass it to `UUID`.
Re: Why are globals set to tls by default? and why is fast code ugly by default?
On Sunday, 26 March 2023 at 18:07:03 UTC, ryuukk_ wrote: What i do not understand is the reasoning behind choosing tls global by default in D Because the language maintainers decided that they want to emphasize the actor model with no default shared state in the language. This is quite beneficial, BTW, as multiprocessor programming is by no means an easy problem, so the language just pushes you towards the error-free code by default. As for `__gshared`, this is intended only for interfacing with C and other languages where global variables is the default way of doing things. This may seem ugly, but if you write your program completely in D and want to avoid TLS, why don't you avoid globals at all? Just allocate some state on the stack and pass it to your functions as `ref`. This way it will actually be much cleaner and easy to understand and test, because global variables are tempting to be mutated, which makes the program control flow much less transparent.
Re: Implicit type conversion depending on assignment
On Friday, 24 March 2023 at 09:59:47 UTC, Alexander Zhirov wrote: On Friday, 24 March 2023 at 09:46:26 UTC, Jacob Shtokolov wrote: BTW, you can also `alias this` your struct value and then use `std.conv : to` for casting, if you don't need specific casting rules. I don't quite understand what you mean? Could you show me an example? I mean, it would be the same code except that you don't define any `opCast` or other operators for a struct, just alias the value to `this` and use `std.conv : to` directly as follows: ```d struct MyVal { string value; alias value this; } void main() { import std.stdio; import std.conv; auto a = MyVal("100"); auto b = MyVal("11.2"); auto MyInt = a.to!int; auto myFloat = b.to!float; writeln(MyInt, ", ", myFloat); } ```
Re: Implicit type conversion depending on assignment
On Friday, 24 March 2023 at 09:39:00 UTC, Jacob Shtokolov wrote: On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov wrote: Is it possible to convert such records inside the structure to the assigned type? BTW, you can also `alias this` your struct value and then use `std.conv : to` for casting, if you don't need specific casting rules.
Re: Implicit type conversion depending on assignment
On Thursday, 23 March 2023 at 13:38:51 UTC, Alexander Zhirov wrote: Is it possible to convert such records inside the structure to the assigned type? ```d struct MyVal { string value; // Here it would be possible to use an alias to this, but it can only be used 1 time } auto a = MyVal("100"); auto b = MyVal("11.2"); int MyInt = a;// Implicitly convert to target type float myFloat = b;// Implicitly convert to target type ``` Here is another working variation of Ali's code, try it yourself: ```d import std.stdio; import std.conv; struct MyVal { string value; T opCast(T)() { return value.to!T; } } void main() { auto a = MyVal("100"); auto b = MyVal("11.2"); auto MyInt = a.to!int; auto myFloat = b.to!float; writeln(MyInt, ", ", myFloat); } ``` In general, all type casting and parsing stuff usually exist under `std.conv` in the standard library, so you can take advantage of it.
Re: Easy sockets - don't exist yet?
On Saturday, 3 December 2022 at 11:08:53 UTC, Vincent wrote: Unfortunately even TECHNICALLY stream never was a "range"! It's more like "queue of bytes", where you can never be sure you even get these bytes. A stream is exactly a range, a "range of ranges" if more specifically. All network devices work with chunks of data (buffers), either it's 1 byte or 4096 bytes in size. So, such ranges may work either with strings (with "\n" terminator, like `byLine` or your `readLine` example), or a chunk of bytes (like `byChunk`). --- As for your request about "Easy sockets": it seems there is nothing like that available for now in the standard library. Besides, your example with google is oversimplified: for example, there is no simple way to determine the transport layer protocol for a specific domain name and port: ```d auto sock = new ClientSocket("google.com", 80); sock.WriteLine("GET / HTTP/1.0"); ``` You can technically guess between IPv4 and IPv6 by resolving the address via DNS, but you can't guess TCP vs UDP without trying to connect to a host. Moreover, there are other protocols like QUIC, which is built on top of UDP but has different semantics. However, your demand is quite understandable. There is some ongoing work toward these ideas. For example, what would you say about the following interface: ```d auto s = socket("tcp://google.com:80"); s.connect(); s.writeln("Hello world"); s.close(); ``` or, if asynchronous: ```d auto t1 = socket("tcp://google.com:80") .connect() .writeln("GET / HTTP/1.0") .readln((sock, msg) => doSomething()); auto t2 = socket("tcp://duckduckgo.com:80") .connect() .writeln("GET / HTTP/1.0") .readln((sock, msg) => doSomethingElse()); wait(t1, t2); ```
Re: How to store a pointer to class contructor
On Thursday, 24 December 2020 at 10:23:09 UTC, Dmitriy Asondo wrote: Hi! I'm trying to check some js-like features. For example, if I want to store somewhere in array|tuple a list of pointers to classes (app services) how may I do that? Hi, it seems that what you're looking for is Prototype Inheritance, which is not quite common among staticly typed programming languages due to its runtime nature. Please note that the way you've implemented it in JavaScript doesn't take compile-time class constructors into consideration. Just look at how you're passing constructor parameters to your objects. In D, each class may have its own constructor, so the arguments may be totally different. Also, it looks like you're trying to implement some kind of a Service Locator. Could you tell what are you trying to achieve with this code? Are the arguments and the array index received at runtime?
Re: Small program producing binary with large filesize
On Monday, 21 October 2019 at 19:20:04 UTC, Prokop Hapala wrote: What exactly should I specify to make it link dynamcially and produce as small binary as possible (without increasing compilation time) ? Hi! Sorry, just found your response here. In order to force it to link dynamically, add these lines to your `dub.json`: ``` "buildTypes": { "release-shared": { "dflags": ["-link-defaultlib-shared", "-release", "-O3"] } }, "postBuildCommands": [ "strip ./" ] ``` Then build it like that: ``` dub build --build=release-shared --compiler=ldc2 ``` Make sure that you replace under `postBuildCommands` with your own application (binary) name. The thing is that LDC2 links statically by default, so you have to add a few flags to the command line
Distinguish float and integer types from string
Hi, Recently, I was trying to solve some funny coding challenges (https://www.techgig.com). The questions were really simple, but I found it interesting because the website allows to use D. One of the task was to take a string from STDIN and detect its type. There were a few options: Float, Integer, string and "something else" (which, I think, doesn't have any sense under the scope of the task). Anyway, I was struggling to find a built-in function to distinguish float and integer types from a string. I came to the following solution: ``` import std.stdio; import std.range; import std.conv; import std.string; import std.format; immutable msg = "This input is of type %s"; void main() { string type; auto data = stdin.byLine.takeOne.front; if (data.isNumeric) { type = data.indexOf(".") >= 0 ? "Float" : "Integer"; } else { type = "string"; } writeln(msg.format(type)); } ``` But I think that's ugly. The thing is that in PHP, for example, I would do that like this: ``` if (is_integer($data)) { //...do smth } else if (is_float($data)) { //...do smth } else { //...do smth } ``` I tried to use std.conv.to and std.conv.parse, but found that they can't really do this. When I call `data.to!int`, the value of "123.45" will be converted to int! Is there any built-in way to detect these types? Thanks!
Re: opEquals() non-standard return type
On Wednesday, 23 January 2019 at 17:28:37 UTC, H. S. Teoh wrote: The best way to do this is to use a string DSL or a delegate as template argument. For example: auto result = User.filter!q{ User.name == "John" }; or: auto result = User.filter!(u => u.name == "John"); I didn't know about q{} token strings! This looks very cool for implementing different DSLs. Thank you!
Re: opEquals() non-standard return type
On Thursday, 24 January 2019 at 00:47:37 UTC, Ali Çehreli wrote: Yeah, that can't work. Remove the bool-returning one and your code works with the 'alias this' above. Wow, this is an amazing workaround! I didn't think about it in that way. It perfectly solves the issue. Thank you!
Re: opEquals() non-standard return type
On Wednesday, 23 January 2019 at 15:28:02 UTC, Jonathan M Davis wrote: But regardless of the specifics of operator overloading in D, D does not support overloading _any_ functions on the return type. Thanks!
opEquals() non-standard return type
Hi, I'm trying to check whether it's possible to implement Python's SQLAlchemy-like query syntax in D, but I get stuck a bit. Here is a simple example of what I want to achieve: ``` auto result = User.filter(User.id == 10); result = User.filter(User.name == "John"); result = User.filter(User.age > 18); ``` Expressions like `User.id == 10`, `User.age > 18`, etc. should return a struct instead of a bool (let's call it `struct BinaryExpression`). So I'm making the two versions of opEquals: one returns a BinaryExpression, and the second - a boolean value. However, when I want to use the same expression for the `if` operator, the compiler cannot decide what function to call and shows an error: "overloads bool(int b) and BinaryExpr!int(int b) both match argument list for opEquals". I'm wondering, is that possible to declare multiple versions of opEquals() and evaluate them in the different places depending on return type? Here is my test code to check: https://run.dlang.io/is/yTFHWp Gist: https://gist.github.com/run-dlang/67ec42ca73d56d310e8ae765fabede69 Thanks!
Re: Compile time opAssign/@property constraints
On Friday, 4 January 2019 at 14:36:16 UTC, Mike Parker wrote: v is a run-time value, not available at compile time. Sorry about that, looks like if I edit the text in the run.dlang.io editor, the link also gets updated. I was using "void opAssign(T)(T v)" in the initial example, but it seems that I got the idea. So even if I'd write opAssign or @property as a template function, I won't be able to get their arguments at compile time because every template takes different set of arguments: for compile time and for run time. And due to the fact that D is calling opAssign as obj.opAssign(arg) and not as obj.opAssign!(arg)(arg), this is not possible to get the runtime arguments. On Saturday, 5 January 2019 at 01:38:43 UTC, Jonathan M Davis wrote: I suggest that you read https://wiki.dlang.org/User:Quickfur/Compile-time_vs._compile-time IIRC, it's still a work in progress, but it should give you a much clearer idea of how CTFE fits into things. Many thanks for this article! Now I understand it much better. So it seems that the only "true way" is to use the struct invariant feature, but this will work only at run time. It turned out that I just want some compile-time mechanism (static analyzer?) that will validate (solve) all reachable constraints in the program. Then I'd like to reformulate the question: is there any tools or compiler features that are capable of validating asserts at compile time? Thanks!
Re: Compile time opAssign/@property constraints
On Friday, 4 January 2019 at 11:45:24 UTC, Jacob Shtokolov wrote: Here is the simple example: https://run.dlang.io/gist/1a06dd703bea5548ee72b4713a7ce5f6 Sorry, invalid link. Here is a new one: https://run.dlang.io/is/QZ5hLV
Re: Compile time opAssign/@property constraints
On Friday, 4 January 2019 at 11:41:59 UTC, Simen Kjærås wrote: The thing is, compile-time tests like static if and static assert can only test values that are known at compile-time, and are for the most part useful only in templates. Thanks for this answer! That's sad to hear. But, is there anything to do with CTFE? Can it help somehow in such situation?
Re: Compile time opAssign/@property constraints
On Friday, 4 January 2019 at 10:34:07 UTC, Basile.B wrote: Show us some code. Here is the simple example: https://run.dlang.io/gist/1a06dd703bea5548ee72b4713a7ce5f6 The thing I'm trying to do is to make an experimental port (for education purposes) of https://github.com/fthomas/refined library for Scala, which allows to set constraints on basic types like numeric, bool, string, etc. For example, you can force an integer variable to take a range between 0 and 15. And if constraint is not satisfied, you get a compile time error. There is no predicate in my example, but even if I add one (using alias template parameter), it shows the same error. So is that possible in D?
Compile time opAssign/@property constraints
Hi, I'd like to implement some compile time constraints for a struct (though not sure if that's possible). I already tried to place "static assert" or any kind of static condition into a body of @property and opAssign(), but every time it shows the error "variable cannot be read at compile time". Is there any way to catch and validate assignments or struct initialization at compile time? Thanks, Jacob
Re: How to understand context type of a delegate?
On Wednesday, 5 September 2018 at 16:53:42 UTC, NX wrote: Is there a way to know what kind of context a delegate has either in compile time or runtime? Also is there any way to check whether a pointer legitimately points to an Object instance? No and no. I was fighting this problem in std.signals but found only one way to fix that without breaking backwards compatibility: we can use core.memory.GC class in order to check whether the object was allocated by GC (GC.addrOf). If it was, we need to retain the delegate context pointer to prevent accidental deallocation of this class by GC. And if the object is not managed by GC, it means that the delegate's context is a simple anonymous function, struct function, or manually allocated delegate's heap (there are few more cases though). In this case we just allow the user to manage this object manually. So if he decides to deallocate the entity behind the context pointer, he should be ready for a segmentation fault if he didn't remove an object from listeners before deallocation. The main reason why std.signals allows only objects to be used as a delegate context is that every object is tracked by D runtime (by the so-called Monitor object) and even in the case of manual deallocation (if you're using the std.experimental.allocator), you will be notified about object destruction if you were subscribed to this event. This makes the implementation extremely safe, but the author of the original library didn't finish his work properly. So std.signals now is a good candidate for replacement. I'm working on the fix and will create a pull request soon. Not sure if it will be accepted, but this module definitely needs to be replaced. If you want to join me in this work, I can share additional details about the situation around std.signals in general. If you don't want to spend your time on this, check this module: https://github.com/buggins/dlangui/blob/master/src/dlangui/core/signals.d - it's a part of the DlangUI project which already contains most of the things you may need.
Re: Is there a simple way to check if value is null for every case?
On Monday, 27 August 2018 at 14:11:32 UTC, SG wrote: On Monday, 27 August 2018 at 13:02:28 UTC, rikki cattermole wrote: So Nullable in D and C# is basically the same except C#'s has language support. Shouldn't it be in the standard library? I think it's worth it to create a feature request in Phobos for that. Or at least make a bug report. Such inconsistencies must be handled by a standard library, not manually, I believe.
Re: Small program producing binary with large filesize
On Tuesday, 31 July 2018 at 15:19:19 UTC, Dan Barbarito wrote: Hi all, I am starting to write a command line tool. Hi! First, Vibe.d will increase your binary size because it contains a lot of unnecessary things inside it. So instead of using the entire vibe.d library, you may point dub to specific vibe.d parts, like `vibe.d:core`, `vibe.d:http` etc. If you put the whole vibe.d framework as a dub dependency and use it like `import vibe;` the things like mongodb drivers, email libraries, redis driver etc. will be linked to your binary as well, even if you don't need them. Second, you need to compile your code in the release mode to cut all debug information out of it. Also, you can try to use the `strip` command line tool to cut all export symbols if your binary is an executable file, not a library. This will reduce the size. In some cases a lot. The third thing is already mentioned: by default, the DMD compiler builds and links the code statically. In other words, your binary contains parts of the DRuntime and the Phobos libraries (those parts that you've used in your program). This thing helps to distribute compiled binaries without external dependencies (except libc and libpthread), because your binary is already contains all needed stuff. If you're not happy with it, you can try to use the LDC compiler, which uses the dynamic linking by default. Your binary will be really tiny, but in order to execute it, you'll need to have the libdruntime.so and libphobos.so installed in your system. This may add additional issues if you plan to distribute your program. Sadly, we still don't have the D runtime libraries installed in all popular OSes. Currently only the libc has this privilege I hope the situation will change in the future.
Re: Dlangui customize app icon on dock or menu bar
On Wednesday, 25 July 2018 at 09:42:00 UTC, Ivo wrote: I'm a macOs user and I need to build a application with a GUI. Not sure if the author of the DLangUI is visiting this forum so often to be able to answer. If you won't get an answer in the next few days, I would recommend to make an issue in the DLangUI repo: https://github.com/buggins/dlangui
Re: High memory usage in vibe.d application
On Sunday, 1 July 2018 at 05:20:17 UTC, Anton Fediushin wrote: Now I tried it and indeed, it's vibe.d's fault. I'm not quite sure what causes it and if this problem is known, I'll look into that later and open an issue if it doesn't exist already. Yes, please do this when you have time. That would be really helpful for further vibe.d improvement. I remember a pretty old (and closed) bug of HTTP client here: https://github.com/vibe-d/vibe.d/issues/1321 So it might be somehow related to this one. Probably something wrong with HTTP client or TLS/SSL related logic. You example code is very good and I was able to reproduce the same issue with the latest stable compiler, so I hope the guys will find the problem. Thanks!
Re: High memory usage in vibe.d application
On Friday, 29 June 2018 at 17:40:07 UTC, Anton Fediushin wrote: So, long story short: - Usage of Mallocator instead of theAllocator made it a little bit better - VibeManualMemoryManagement had no (or little) effect - Manually calling GC.collect had no (or little) effect You could try to call GC.minimize in pair with GC.collect: ``` GC.collect(); GC.minimize(); ``` to return all freed memory back to the OS. Not sure that the leakage of this type is possible because if you're running your program on 64bit Linux the probability of it is very low. AFAIK the GC is launched every (almost) time you allocate the memory, and if it finds "dead" pointers, it definitely must clean them out. Vibe.d may also leak. Have you tried to run the same code without Vibe.d, say, using https://github.com/ikod/dlang-requests as an HTTP client? Also, have you tried to change vibe.d's event loop engine, like libevent or libasync?
Re: Can't start application on heroku
On Saturday, 16 June 2018 at 01:24:04 UTC, crimaniak wrote: Hi all! The first try to host application on Heroku provider. The application is started and starts to listen in 3 seconds on the port, provided by heroku-buildpack-d. But the server doesn't detect listening and stops the application. On the local machine, the application works as expected. What can be the problem here? [...] Probably you could try to change your listening address from 127.0.0.1 to 0.0.0.0