Creating a "fixed-range int" with opDispatch and/or alias this?
I'm trying to create a type that for all intents and purposes behaves exactly like an int except that it limits its values to be within a certain range [a,b]. Theoretically, I would think this looks something like: struct FixedRangeInt { this(int min, int max, int value=0) { this.min = min; this.max = max; this.value = value; } auto opDispatch(string name, T...)(T args) { auto backup = value; scope (failure) value = backup; auto result = mixin(`value.` ~ name ~ `(args)`); if (value < min || value > max) { throw new Exception("Operation put value out of range"); } return result; } int min; int max; int value; } But that code doesn't work for simple cases, like: FixedRangeInt(0, 100) x; x += 5; It looks like opDispatch doesn't participate in resolution of operator overloads. Is there any way I can achieve my desired result? I know alias this forwards operations like +=, but with alias this I cannot wrap the operation to do the bounds checking. FWIW, the fixed range int part of this question is just an example, I'm mostly just interested in whether this idea is possible without a lot of bloat/duplication.
Re: Unique Enum Members
On Thursday, 5 May 2016 at 12:54:08 UTC, Nordlöw wrote: Is there a way to calculate unique enum members without using sort, such as *not* done in my current implementation: auto uniqueEnumMembers(T)() { import std.traits: EnumMembers; import std.algorithm: sort, uniq; return [EnumMembers!T].sort().uniq; } Preferrably both at compile-time and run-time. Sure, if you can hash the underlying type this should do the trick in linear time: http://melpon.org/wandbox/permlink/Rvq60fv7jOIPuhXz
Re: Observing exceptions in a destructor
Oh well :(. Yeah, it's just for debugging. I want to publish a script that automatically gathers relevant debug information so that my users can just copy paste it all into one place, ready for me to take a look even if I can't repro. One of the primitives in my script is a wrapper around std.process that caches the result, and I wanted to make it so that if the program throws an exception while one of the CacheResult objects is in scope, it dumps its contents out to a pastebin and logs the URL. I ended up manually adding some scope (failure)s at the call sites and putting the relevant code in a member function... but it would have been nice to not need to duplicate the scope (failure)s and have it simply live in the destructor.
Observing exceptions in a destructor
I'd like to be able to know if my destructor is being called because an exception was thrown. Any way to do that? I tried this: http://ideone.com/JbXH2w (Pasted here for convenience): import std.stdio, std.exception; struct Catcher { ~this() { try {} catch (Exception e) { writeln("W!"); throw e; } scope (failure) { writeln("W w!"); } writeln("Destructing..."); } } void main() { scope (failure) writeln("Sensible"); scope (exit) writeln("Always written"); Catcher c1; scope auto c2 = Catcher(); throw new Exception("Foobar"); } Which does not print the "Wooo" lines, but does print all the others.
Re: Why doesn't map!(a => writeln(a)) print anything?
On Saturday, 18 April 2015 at 01:04:24 UTC, Adam D. Ruppe wrote: map evaluates its arguments on demand. Think of it as returning a function that does the work instead of actually doing the work - you still need to call that function, which happens when you loop over it. std.algorithm.each is more appropriate for acting now. Ahhh cool. Thanks!
Why doesn't map!(a => writeln(a)) print anything?
Why can't I print things using the map algorithm? Specifically: http://ideone.com/VLp4Xa
Re: Getting associative array value by reference
Not quite. You'll note that I am creating the elements in the associative array, not just iterating over them; some of them just happen to be duplicates. FWIW: That foreach happens to be over an input stream.
Getting associative array value by reference
I'm presently trying to create the value of a key in an associative array if it does not exist, and then maintain a reference/pointer to the value. This is what I came up with, but it seems really crufty and I feel that there must be a cleaner way: Value[string] assocArray; foreach (...) { auto value = key in assocArray; if (!value) { assocArray[key] = Value(); value = &assocArray[key]; } value.memberA++; value.memberB = "foobar"; } The goal was to avoid writing: Value[string] assocArray; foreach (...) { assocArray[key].memberA++; assocArray[key].memberB = "foobar"; } and save a lookup call, but my solution is both less readable and also performs worse for keys not already in the associative array...
Re: Equivalent of C++ function-scope static initialization
On Monday, 2 March 2015 at 23:07:30 UTC, Ali Çehreli wrote: immutable string bar; shared static this() { bar = painfulToInitialize(); } void foo() { } Clever :). > I don't need the thread-safety that C++ provides in that case, I am not aware of such safety. (?) Is that a newer C++ feature? Ali New as of C++11. All function-scope statics are guaranteed to be initialized in a thread-safe manner. Exactly one thread will initialize the variable the first time the function is called.
Equivalent of C++ function-scope static initialization
I'm looking for the D equivalent of: //C++ void foo() { static string bar = painfulToInitialize(); //Always returns the same value /* A bunch of code */ } I don't need the thread-safety that C++ provides in that case, though it wouldn't hurt. I'm essentially trying to memoize the result of painfulToInitialize() between calls to foo. I could use std.functional.memoize, but that seems like a syntactic burden. Unfortunately, I cannot compute the value at compile time. What's the idiomatic way of doing something like this?
Re: Getting what came *before* the results of a find call
Ahhh right - forgot about that. Thanks!
Re: Getting what came *before* the results of a find call
Not that it's super important, but the link didn't copy well, so here's that: http://www.informit.com/articles/article.aspx?p=1407357&seqNum=12
Getting what came *before* the results of a find call
What's the idiomatic way of getting everything *before* the results of a call to find? assert("hello world".find(" world").what_goes_here??? == "hello"); In an article Andrei wrote a few years ago (http://www.informit.com/articles/article.aspx…) he mentioned a function like this with the name "until", but I can't find it or its replacement in Phobos.
Re: Equivalent of DllMain on OSX?
Loading multiple D shared libraries isn't supported on OS X yet, see these warnings in druntime: https://github.com/D-Programming-Language/druntime/blob/master/src/rt/sections_osx.d#L198 If you only have a single D shared library, I think it's possible, you just may have to tweak dmd/druntime or your build process a bit. I think Martin Nowak or Jacob Carlborg can really answer your questions, as Martin wrote a lot of that code and Jacob seems to follow it closely, whereas I don't use OS X but looked at that code when porting to Android. It would only be a single shared library. Finally got the code publicly available: https://github.com/markisaa/presto-odbc/blob/osxCompile/driver/driver.d#L61 It should compile on OSX with a simple `make clean all` Testing would require installing the iODBC driver manager and pressing the 'Add Driver' button, possibly making a new User DSN, and possibly pressing 'Test'.
Equivalent of DllMain on OSX?
I am presently trying to port a driver I wrote for Windows to OSX. The one thing standing in my way is figuring out how to get the equivalent of DllMain on OSX. I need a place to call Runtime.initialize() and whatnot. Reading the wiki, it seemed like `shared static this()` was the appropriate construct to use, and indeed, when I run the test program from: http://dlang.org/dll-linux.html#dso9 I get the desired results: namely, I see that the `shared static this()` in that test program is called the desired point. When I try the same thing in my driver, it is never executed. Are dylibs on OSX not supported still (I saw some very old threads from 2012 stating as much)? Does it matter that I have multiple modules in the driver? Any help would be appreciated. I shall endeavor to get the modified driver code into a state where I can link it as well.
Re: Getting libcurl for 64 bit Windows
Resolved the issue.
Re: Getting libcurl for 64 bit Windows
Managed to build it successfully I think, but have actually returned to the problem that initially caused me to want to try and build the library in the first place: If I try to build a simple program: import std.stdio; import std.net.curl; void main() { writeln("Hello world"); } The program compiles, but does not print Hello World at runtime... it just stops, and seemingly does nothing. Trying to determine the root cause of that now.
Getting libcurl for 64 bit Windows
I am attempting to make use of std.net.curl and having trouble acquiring libcurl for 64 bit Windows. I need to be able to link with the MSVC linker (which happens to be the default when compiling using dmd with -m64). I've looked on the libcurl website and not found any downloads that look promising. I've tried following the instructions at: http://wiki.dlang.org/Curl_on_Windows#Building_libcurl_64_bit But when I compile the dll with: "dmd main.d -m64 -Llibcurl.dll" I get the linker error: libcurl.dll : fatal error LNK1107: invalid or corrupt file: cannot read at 0x330 Might anyone have an idea as to how to resolve this?
How to free memory of an associative array
How can I free the memory used by an associative array? I need to be able to reuse the same array, but set it to an empty state and free up the memory it used previously. I do not believe that setting the associative array to null is sufficient to free the memory, as it is possible that someone still has a reference to an element inside, and so the garbage collector must be conservative. Thanks in advance!
Re: Using D static library from C
I found that if I told dmd rather than gcc to do the linking that everything just magically worked. In other words: gcc -c cstuff.c dmd -c dstuff.d dmd cstuff.o dstuff.o I presume that dmd would be similarly smart with static libraries.
Re: Linking with C on Windows
Still unresolved, but a thought: I decided to take a step back and try to link with C on Linux first. I found out that if I did the linking step with dmd things worked, but not with gcc. The reason then became apparent: dmd knows to pass druntime and phobos and all of that stuff to the linker. Running on the assumption that this was also my problem on Windows, I ran dmd with -v (verbose) to try and get the linker line it uses for a simple program that just uses some Phobos functions, the line I get is: C:\D\dmd2\windows\bin\link.exe test,nul,,user32+kernel32/noi; Which does not appear to be helpful and seems to indicate that Phobos does not need to be passed to the linker?
Re: Linking with C on Windows
On Thursday, 5 June 2014 at 22:59:48 UTC, bearophile wrote: Mark Isaacson: My attempts to have either the MinGW linker or the Visual Studio linker accept my D .objs have all failed. Try using the dmc compiler for the C code. Bye, bearophile I'd considered that, but in the long term that will not be a viable solution for me. I need to eventually be able to export a dll that can talk with anything. I just figured this would be an easy first stepping stone to that end.
Linking with C on Windows
I'm having a very difficult time figuring out exactly how to do this. I've compiled my D code into a .obj file with dmd, but I don't know what C compiler I should use (or if it makes any difference). I've attempted to use MinGW gcc, which spits out .o files, and Visual Studio, which does... something else. My attempts to have either the MinGW linker or the Visual Studio linker accept my D .objs have all failed. I have tried both extern(C) and extern(Windows) in the D code, and I'm not sure which of them is more appropriate. In any case, this is the code I'm trying to compile: dimpl.d: extern(Windows) int square(int x) { return x^^2; } ciface.c: #include int square(int x); int main() { assert(square(2) == 4); return 0; } I compiled dimpl.d with: dmd -c dimpl.d Not really sure where to go from here, though I'll post back if I figure anything out. I'm more than willing to take whatever answer I get here and add it to appropriate wiki/site pages :) Thanks!
Are tests interruptible/concurrent? Is use of a (thread local) global safe in tests?
I'm having fun running some unittests. I set up a simple homemade mock of std.net.curl's functions that essentially just consists of a global queue that I can add strings to and get back in a predictable order when calling std.net.curl.get/post/etc. I use this mock in a couple of different modules for unit testing, namely the module I have the mock in and one other one. When I run my unit tests, it seems to enqueue all of the responses from both of my unit tests (from different modules) before finishing those tests and removing things from the global queue. This is problematic in that I cannot anticipate the state of the global queue for my tests. Does this sound more like a bug or a "feature". My understanding is that, at least for now, tests are not run concurrently on the latest official dmd release; since my queue is not qualified with shared, things should be thread local anyway. TLDR: Executation of tests A and B is as follows: A pushes to global queue B pushes to global queue B pops on global queue -- program crashes Expected order: A pushes to global queue A pops from global queue B pushes to global queue B pops from global queue Or switch the order in which A and B execute, doesn't really matter.
Re: Looping over all enum values
On Wednesday, 28 May 2014 at 20:20:37 UTC, Adam D. Ruppe wrote: On Wednesday, 28 May 2014 at 20:19:45 UTC, Mark Isaacson wrote: Is there a mechanism that allows you to loop over all of an enum's values? I've wanted to do so a couple times now for CTFE/mixin templates. __traits(allMembers) on the enum can do it or this can help too http://dlang.org/phobos/std_traits.html#EnumMembers Brilliant! Thanks Adam! I actually checked your book before any other sources for this :)
Looping over all enum values
Is there a mechanism that allows you to loop over all of an enum's values? I've wanted to do so a couple times now for CTFE/mixin templates. I was able to loop over the underlying type when my enum was integer-based, but I can't do that if the values are strings (also that solution is quite hacky). Perhaps there's a pattern involving __traits?
Re: Temporary silence output (stdout)
On Saturday, 10 May 2014 at 20:24:50 UTC, MarisaLovesUsAll wrote: Hi! I sometimes got a useless messages in stdout from SDL_Image library, and I want to temporary silence it. How do I do? Consider using either version or debug statements. If you want the messages to be opt-in, debug statements are quite useful: debug(myModule) writeln("Hello world!"); Which will only print when you compile with -debug=myModule If you want more power than that, version statements can be useful. First declare (or don't) a specific version (or several): version = MyVersion; Then conditionally compile code based on that: version(MyVersion) { writeln("Hello World"); } Note that the compiler declares some versions automatically, such as version(unittest) when compiling with --unittest.
Re: Reading a single whitespace-separated word from stdin
An exceptionally generous offer! May take you up on that. Thank you :).
Re: Reading a single whitespace-separated word from stdin
Indeed. However, doing so looks more painful than redefining my goals. Upon further examination it seems that I had more flexibility than I originally estimated. Besides, the real reason I'm implementing this project is just to practice for when I get to write production D code in a week anyway; I'd rather learn the idioms.
Re: Reading a single whitespace-separated word from stdin
Fair enough. I've done stuff like that in the past. I'm trying to implement a university project that was originally designed for C++ style I/O... and so where I'd have otherwise jumped at something like that from the beginning, my hands are slightly tied. Suppose I'll make due/not fully comply with the spec.
Reading a single whitespace-separated word from stdin
I'm trying my hand at reading from standard input and having little luck. In particular, I would like to be able to do the rough equivalent of C++'s: cin >> myString; As opposed to reading the whole line. I attempted to do this with readf: string result; readf(" %s ", &result); However this does not seem to do the trick. If I enter "Hello\n" on the terminal, it keeps waiting for input. By contrast, if I enter "Hello program", it correctly identifies "Hello" as the 'result'. Thus, contrary to what I've been reading, the trailing space seems to only account for space characters, not general whitespace. I presume that I'm missing something obvious, any ideas? Thanks in advance!
Re: Need help with movement from C to D
On Monday, 5 May 2014 at 03:57:54 UTC, Andrey wrote: Guys, could someone help me with suitable template? I have C macro, which calculates the offset of the field in a struct: #define offsetof(type, field) ((long) &((type *)0)->field) A similar D code is, as far as I know, type.field.offsetof Is there an any way to make a corresponding D template? Thank you! Something like: unittest { enum offsetof(string type, string field) = mixin(type ~ "." ~ field ~ ".offsetof"); struct StrToBob { string str; int bob; } writeln(offsetof!("StrToBob", "bob")); } ? If not that then I'm not sure what you're asking for.
Re: C++ std::map equivalent? (An in-order iterable associative container)
Interesting. I clearly have more to learn about Tuple. I think I concur with Dicebot's alterations for self-documentation. Thanks for all of your suggestions gentlemen.
Re: C++ std::map equivalent? (An in-order iterable associative container)
On Sunday, 4 May 2014 at 21:40:04 UTC, bearophile wrote: Mark Isaacson: 2) Create a wrapper struct that contains key and value and whose comparison operator is defined only on the key. This would essentially be doing what the C++ implementation does. Until we have a tree-based associative map, use a tuple for the key-value and define a "less" template argument like q{a.key < b.key} or q{a[0] < b[0]}. Bye, bearophile Got it, no native support. Most unfortunate. I've always been vehemently against losing self-documentation via the std::pair/tuple based solution to the problem. I ended up rolling my own solution that lets you give meaningful names to the wrapper struct's data members: http://pastebin.com/cKLccqFn Thanks.
C++ std::map equivalent? (An in-order iterable associative container)
I'm looking for a means to associate a key with a value and iterate over said container in-order. My natural choice in C++ would be std::map. When I look in std.container, I see that there is a RedBlackTree implementation, however this does not associate a key with a value (it is the equivalent of std::set). My question is essentially what the best/most idiomatic way to represent this is in D? I've contemplated several solutions: 1) Have 2 containers, a RedBlackTree of keys and a D associative array of keys to values. The downside to this approach is that I incur the cost of both key lookups when I iterate (the tree's and the array's). Furthermore, separate containers likely incurs a cache performance hit. 2) Create a wrapper struct that contains key and value and whose comparison operator is defined only on the key. This would essentially be doing what the C++ implementation does. 3) Use an associative array and sort the keys each time I intend to iterate. This is an indue performance cost. I could probably cache the sorted keys in this particular instance reasonably successfully, but this doesn't seem like a general solution. I suppose the reason I'm reluctant to take the 2nd option is that I feel like if this was the correct move there would be a mechanism for this somewhere in phobos (ideally with a better abstraction than C++'s std::map's decision to use std::pair everywhere). Have I missed something? Is the idiomatic solution to just do one of the above depending on the performance tradeoffs? Thanks in advance!
Re: const ref parameters and r-value references
Thanks for the insights! I suppose we'll get a chance to see where things stand at this year's dconf. It's quite interesting that D's concept of r-values seems less developed than C++. Here's hoping that that only results in a better thought out solution.
Re: Postblit not invokable with MyStruct(MyStruct()); ?
What actually fails is the initialization of 'a'. Add another this(A a) { /* Stuff */ } constructor to the 'A' struct, and it will work. And, yes, the missing cpctors are a language problem. artur Thanks. Yeah, I figured I could do that, I was just hoping that I could leverage the postblit. Ultimately my answer to my second question became: "Calling the postblit directly is far too low level, just use std.conv.to instead". to!A(x) did exactly the right thing (without any modification of the original classes I think).
Re: Postblit not invokable with MyStruct(MyStruct()); ?
@bearophile - Unless I'm missing something, alas, no. Neither A nor B is a subtype of the other. In particular, in the real code one is a CartesianVector and the other a PolarVector. For what it's worth, 'foo' is actually opBinary addition. Thanks for the thought though.
Re: Postblit not invokable with MyStruct(MyStruct()); ?
Did some thinking: Realized that the appropriate mechanism to express that A and B are two ways of representing the same thing is to do so via opCast. I had not considered this option carefully initially as I am translating someone else's C++ code to D and hoped that they had used the appropriate representations on the C++ side. I added the appropriate code to permit casting and I was then able to get the desired code-reuse and template constraints. Accordingly, I no longer need an answer to my second question unless someone knows of a more idiomatic way to get the same results.
Postblit not invokable with MyStruct(MyStruct()); ?
I have just discovered that the postblit constructor is not able to be invoked like a "normal" constructor, or, as one would manually do so in C++ with a copy constructor. Accordingly I have a couple questions: 1) What are the various ways to invoke the postblit constructor? I have not tested, but assume that: auto s1 = MyStruct(); auto s2 = s1; Is one such way to invoke it and that: auto s1 = MyStruct; foo(s1); Where foo is defined as: void foo(MyStruct s) {} is another way. Are there others? 2) I ran into this issue while attempting to leverage the postblit for code-reuse. In particular, I have a setup that is similar to: struct A { this(B b) { /* Stuff */ } } struct B { } void foo(T)(T param) { auto a = A(param); /* Stuff */ } unittest { foo(A()); //Fails foo(B()); //Succeeds } The notion being that A and B are 2 ways to represent the same thing, why not convert everything to the A format and proceed from there; I figured the compiler would optimize out the pointless copy when T == A. Alas, as shown in my unittest, foo fails to accept arguments of type A. I suppose my question would be: What is the idiomatic way of accomplishing this form of code reuse in D? I'd prefer to not have to write two versions of foo, even if one is as simple as converting the argument and passing it to the other. I'd also prefer to avoid having some shenangians along the lines of: void foo(T)(T param) { static if (is(T == A)) { auto a = param; } else { auto a = A(param); } } As this would be difficult to express in a template constraint in the function signature.
Re: const ref parameters and r-value references
Auto ref parameters seem to be just what I need. Thanks! I'd still be curious if anyone has additional information regarding the rationale at play (I'm spoiled, reading TDPL and having each decision explained in text).
const ref parameters and r-value references
I'm in the process of learning/practicing D and I noticed something that seems peculiar coming from a C++ background: If I compile and run: void fun(const ref int x) { //Stuff } unittest { fun(5); //Error! Does not compile } I get the specified error in my unit test. I understand that the cause is that I've attempted to bind ref to an r-value, what's curious is that in C++, the compiler realizes that this is a non-issue because of 'const' and just 'makes it work'. Is there a rationale behind why D does not do this? Is there a way to write 'fun' such that it avoids copies but still pledges const-correctness while also allowing r-values to be passed in? Thanks in advance!