Finding unsafe line of code
Hi All, Is there a way to find or test which line of a give code is not safe(possible memory corruption). From, Vino.B
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 08:21:10 UTC, Vino wrote: Hi All, Is there a way to find or test which line of a give code is not safe(possible memory corruption). From, Vino.B That question needs to be refined ;-)
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 09:19:13 UTC, codephantom wrote: On Friday, 29 December 2017 at 08:21:10 UTC, Vino wrote: Hi All, Is there a way to find or test which line of a give code is not safe(possible memory corruption). From, Vino.B That question needs to be refined ;-) Hi, Let me re-frame the question with an example, as the Dsafe the below line of code is considered as unsafe(Pointer arithmetic), so let imagine that we have several similar line of code, how do we find such unsafe line, does the compiler check these unsafe code and complain while compiling a .d program or do we need to pass any compiler arguments to perform these check while compiling the code or do we need to manually perform an analysis of each line of code and correct the same in case if we find any unsafe code. ini[10] a; int* p = &a[0]; for (size_t i=0; i <= 10; i++) p[i] = ...; From, Vino.B
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 09:38:50 UTC, Vino wrote: Let me re-frame the question with an example, as the Dsafe the below line of code is considered as unsafe(Pointer arithmetic), so let imagine that we have several similar line of code, how do we find such unsafe line, does the compiler check these unsafe code and complain while compiling a .d program or do we need to pass any compiler arguments to perform these check while compiling the code or do we need to manually perform an analysis of each line of code and correct the same in case if we find any unsafe code. ini[10] a; int* p = &a[0]; for (size_t i=0; i <= 10; i++) p[i] = ...; From, Vino.B Is this what you're looking for? https://dlang.org/spec/function.html#safe-functions Just annotate your functions with @safe (as @system is the default).
Re: Finding unsafe line of code
On Friday, 29 December 2017 at 10:23:24 UTC, codephantom wrote: On Friday, 29 December 2017 at 09:38:50 UTC, Vino wrote: Let me re-frame the question with an example, as the Dsafe the below line of code is considered as unsafe(Pointer arithmetic), ... ini[10] a; int* p = &a[0]; for (size_t i=0; i <= 10; i++) p[i] = ...; From, Vino.B Is this what you're looking for? https://dlang.org/spec/function.html#safe-functions Just annotate your functions with @safe (as @system is the default). Or if that's not possible, you can add runtime checks with ASan: http://johanengelen.github.io/ldc/2017/12/25/LDC-and-AddressSanitizer.html -Johan
Re: how to localize console and GUI apps in Windows
On Thursday, 28 December 2017 at 18:45:39 UTC, H. S. Teoh wrote: On Thu, Dec 28, 2017 at 05:56:32PM +, Andrei via Digitalmars-d-learn wrote: ... The string / wstring / dstring types in D are intended to be Unicode strings. If you need to use other encodings, you really should be using ubyte[] or const(ubyte)[] or immutable(ubyte)[], instead of string. Thank you Teoh for advise and good example! I was looking towards writing something like that if no decision exists. Still this way of deliberate translations seems to be not the best. It supposes explicit workaround for every ahchoo in Russian and steady converting ubyte[] to string and back around. No formatting gems, no simple and elegant I/O statements or string/char comparisons. This may be endurable if you write an application where Russian is only one of rare options, and what if your whole environment is totally Russian? Or some other nonASCII locale... Many other cultures have same mix of DOS/Window/Unix code pages. The decision to use only Unicode for strings in D language seems excellent just because of this, but the realization turns out to be delusive. Folks in such countries won’t appreciate a language which is elegant only for English-spoken intercommunications. This problem is common for most programming languages and runtimes I know of. The only system which has decided the whole case is .NET I think. The way proposed by zabruk70 below seems more appropriate though more particular too - I feel it suits only console type of applications. Alas, this type of application proved to be buggy too. On Thursday, 28 December 2017 at 22:49:30 UTC, zabruk70 wrote: you can just set console CP to UTF-8: https://github.com/CyberShadow/ae/blob/master/sys/console.d Yes! This seems to be the required, thank you very much! Though it is not suitable for GUI type of a Windows application. Still some testing showed that this way conforms only console output. Simple read/write/compare script listed below works very well until the user enters something Russian. It then prints **empty** response and falls into indefinite loop printing the prompt and then immediately empty response without actually reading it. But I think this is subject for ”Issues” part of this forum. p.s. I’ve found that I may set “Consolas” font for a console window and then you can output properly localized UTF8 strings without any special code in D script managing code pages. Still this does not decide localized input problem: any localized input throws an exception “std.utf.UTFException... Invalid UTF-8 sequence”. The script: import core.sys.windows.windows; import std.stdio; import std.string; int main(string[] args) { const UTF8CP = 65001; UINT oldCP, oldOutputCP; oldCP = GetConsoleCP(); oldOutputCP = GetConsoleOutputCP(); SetConsoleCP(UTF8CP); SetConsoleOutputCP(UTF8CP); writeln("hello world, привет всем!"); bool quit = false; string response; while (!quit) { write("responde something: "); response=readln().strip(); writefln("your response is \"%s\"", response); if (response == "quit") { writeln("good buy then!"); quit = true; } } SetConsoleCP(oldCP); SetConsoleOutputCP(oldOutputCP); return 0; }
Re: how to localize console and GUI apps in Windows
On Friday, 29 December 2017 at 10:35:53 UTC, Andrei wrote: Though it is not suitable for GUI type of a Windows application. AFAIK, Windows GUI have no ANSI/OEM problem. You can use Unicode. For Windows ANSI/OEM problem you can use also https://dlang.org/phobos/std_windows_charset.html
structs inheriting from and implementing interfaces
In C#, structs can inherit from and implement interfaces. using System; interface IPrint { void Print(); } struct MyStruct : IPrint { public void Print() { Console.WriteLine(ToString()); } } public class Program { public static void Main() { MyStruct s = new MyStruct(); s.Print(); } } https://dotnetfiddle.net/lpXR1O But in D it doesn't appear possible. import std.stdio; interface IPrint { void print(); } // Error: base classes are not allowed for struct, did you mean ;? struct MyStruct : IPrint // Error: base classes are not allowed for struct, did you mean ;? { void print() { writeln("MyStruct"); } } void main() { MyStruct s; s.Print(); } https://run.dlang.io/is/j4xwla Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? Thanks for your insight, Mike
Adding Toc for the "longish" spec pages.
It seems to me that some of the language reference/spec pages that are somewhat long, could provide a Toc (Table of contents) which should help users see an overview of what's there and improve the searchability and the navigation of the content. The 'Functions' page has a Toc already.
Re: Adding Toc for the "longish" spec pages.
On Friday, 29 December 2017 at 12:06:12 UTC, tipdbmp wrote: It seems to me that some of the language reference/spec pages that are somewhat long, could provide a Toc (Table of contents) which should help users see an overview of what's there and improve the searchability and the navigation of the content. The 'Functions' page has a Toc already. If you have a suggestion for improving the documentation, please file an issue at https://issues.dlang.org/ Occasionally contributors go fishing for easy issues like that in the issues list and will submit pull requests. Even better, you may want to file a pull request yourself at https://github.com/dlang/dlang.org Mike
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: In C#, structs can inherit from and implement interfaces. using System; interface IPrint { void Print(); } struct MyStruct : IPrint { public void Print() { Console.WriteLine(ToString()); } } public class Program { public static void Main() { MyStruct s = new MyStruct(); s.Print(); } } https://dotnetfiddle.net/lpXR1O But in D it doesn't appear possible. import std.stdio; interface IPrint { void print(); } // Error: base classes are not allowed for struct, did you mean ;? struct MyStruct : IPrint // Error: base classes are not allowed for struct, did you mean ;? { void print() { writeln("MyStruct"); } } void main() { MyStruct s; s.Print(); } https://run.dlang.io/is/j4xwla Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? Thanks for your insight, Mike I think it simply hasn't been implemented, but I am not sure here because you could simply insert a `static assert` in there (and probably have something like `hasInterface!(Interface, YourStruct)`. Similarly multiple `alias this` is a request that often comes up.
Re: structs inheriting from and implementing interfaces
Structs are structs, classes are classes. C++ had the mixed model similar to what you suggested, we got it right and kept it nice and separate. This was done on purpose.
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:11:46 UTC, rikki cattermole wrote: Structs are structs, classes are classes. I'm talking about interfaces, which are neither structs nor classes. C++ had the mixed model similar to what you suggested, we got it right and kept it nice and separate. This was done on purpose. I'm comparing with C#, not C++. And structs implementing interfaces does not blur the two concepts, as C# eloquently demonstrates. Mike
Re: Adding Toc for the "longish" spec pages.
On Friday, 29 December 2017 at 12:13:02 UTC, Mike Franklin wrote: On Friday, 29 December 2017 at 12:06:12 UTC, tipdbmp wrote: It seems to me that some of the language reference/spec pages that are somewhat long, could provide a Toc (Table of contents) which should help users see an overview of what's there and improve the searchability and the navigation of the content. The 'Functions' page has a Toc already. If you have a suggestion for improving the documentation, please file an issue at https://issues.dlang.org/ Occasionally contributors go fishing for easy issues like that in the issues list and will submit pull requests. Even better, you may want to file a pull request yourself at https://github.com/dlang/dlang.org Mike Yes, opening an issue or PR is the best way to move things forward. In this case, this is already on my radar and will happen soon (since a couple of weeks we already got a footer pagination). It's pretty ugly because Ddoc is used for dlang.org which makes trivial stuff like this rather complicated :/
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: In C#, structs can inherit from and implement interfaces. using System; interface IPrint { void Print(); } struct MyStruct : IPrint { public void Print() { Console.WriteLine(ToString()); } } public class Program { public static void Main() { MyStruct s = new MyStruct(); s.Print(); } } https://dotnetfiddle.net/lpXR1O But in D it doesn't appear possible. import std.stdio; interface IPrint { void print(); } // Error: base classes are not allowed for struct, did you mean ;? struct MyStruct : IPrint // Error: base classes are not allowed for struct, did you mean ;? { void print() { writeln("MyStruct"); } } void main() { MyStruct s; s.Print(); } https://run.dlang.io/is/j4xwla Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? Thanks for your insight, Mike The problem is that interfaces are a runtime thing (e.g. you can cast a class to an interface) structs implement compile time interfaces via template duck typing (usually enforced via an if()). you could probably write a wrapper that introspected an interface and enforced that all members were implemented.
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? It's a design decision. Look carefully at structs vs. classes here: https://dlang.org/spec/struct.html There is no virtual methods table (VMT) for structs, no inheritance. Structs have value semantics. A variable with a type of some interface implies it's a pointer, with reference semantics and a VMT.
Re: structs inheriting from and implementing interfaces
On Friday, December 29, 2017 12:18:57 Mike Franklin via Digitalmars-d-learn wrote: > On Friday, 29 December 2017 at 12:11:46 UTC, rikki cattermole > > wrote: > > Structs are structs, classes are classes. > > I'm talking about interfaces, which are neither structs nor > classes. Interfaces are related to classes and not structs. Structs do not have inheritance and do not implement interfaces in any way shape or form. Classes and interfaces are always references, whereas structs never are, and structs do not have virtual functions. Structs are either directly placed where they are (be it on the stack or inside an object that contains them), or they're placed on the heap and accessed via a pointer. As such, in D, structs are fundamentally different from classes or interfaces. If you want a function to accept multiple types of structs or classes which share the same API, then use templates and use the template constraint to restrict what the template accepts. That's what's done with ranges (e.g. with isInputRange and isForwardRange). - Jonathan M Davis
Re: structs inheriting from and implementing interfaces
On Fri, 29 Dec 2017 12:39:25 +, Nicholas Wilson wrote: > On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: > > The problem is that interfaces are a runtime thing (e.g. you can cast a > class to an interface) > structs implement compile time interfaces via template duck typing > (usually enforced via an if()). > you could probably write a wrapper that introspected an interface and > enforced that all members were implemented. I've actually thought about doing this to get rid of a bunch of if qualifiers in my function declarations. `static interface {}` compiles but doesn't [currently] seem to mean anything to the compiler, but could be a hint to the programmer that nothing will directly implement it; it's a compile-time interface. This would provide a more generic way of doing stuff like `isInputRange`, etc.
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: In C#, structs can inherit from and implement interfaces. using System; interface IPrint { void Print(); } struct MyStruct : IPrint { public void Print() { Console.WriteLine(ToString()); } } public class Program { public static void Main() { MyStruct s = new MyStruct(); s.Print(); } } https://dotnetfiddle.net/lpXR1O But in D it doesn't appear possible. import std.stdio; interface IPrint { void print(); } // Error: base classes are not allowed for struct, did you mean ;? struct MyStruct : IPrint // Error: base classes are not allowed for struct, did you mean ;? { void print() { writeln("MyStruct"); } } void main() { MyStruct s; s.Print(); } https://run.dlang.io/is/j4xwla Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? Thanks for your insight, Mike This feature is criticized among the C# community: https://blogs.msdn.microsoft.com/abhinaba/2005/10/05/c-structs-and-interface/ no vtable means for example that you cannot back to something after extracting the interface (with classes you can always get back to Object) as in D, struct should really only be used for a custom type with value semantic.
Re: structs inheriting from and implementing interfaces
On 29/12/2017 12:59 PM, rjframe wrote: On Fri, 29 Dec 2017 12:39:25 +, Nicholas Wilson wrote: On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: The problem is that interfaces are a runtime thing (e.g. you can cast a class to an interface) structs implement compile time interfaces via template duck typing (usually enforced via an if()). you could probably write a wrapper that introspected an interface and enforced that all members were implemented. I've actually thought about doing this to get rid of a bunch of if qualifiers in my function declarations. `static interface {}` compiles but doesn't [currently] seem to mean anything to the compiler, but could be a hint to the programmer that nothing will directly implement it; it's a compile-time interface. This would provide a more generic way of doing stuff like `isInputRange`, etc. Or we could get signatures, which are even better still!
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 13:08:38 UTC, rikki cattermole wrote: On 29/12/2017 12:59 PM, rjframe wrote: On Fri, 29 Dec 2017 12:39:25 +, Nicholas Wilson wrote: On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: The problem is that interfaces are a runtime thing (e.g. you can cast a class to an interface) structs implement compile time interfaces via template duck typing (usually enforced via an if()). you could probably write a wrapper that introspected an interface and enforced that all members were implemented. I've actually thought about doing this to get rid of a bunch of if qualifiers in my function declarations. `static interface {}` compiles but doesn't [currently] seem to mean anything to the compiler, but could be a hint to the programmer that nothing will directly implement it; it's a compile-time interface. This would provide a more generic way of doing stuff like `isInputRange`, etc. Or we could get signatures, which are even better still! I was about to answer that interfaces could be used to define duck types conformity models but this would be a poor and useless addition, indeed, compared to signatures.
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 12:03:59 UTC, Mike Franklin wrote: In C#, structs can inherit from and implement interfaces. Is that simply because it hasn't been implemented or suggested yet for D, or was there a deliberate design decision? Thanks for your insight, Mike I think it's deliberate, structs are just plain dumb value types. If I remember correctly I think Remedy's Binderoo C++ bindings implemented C++ inheritance on top of structs. You might want to look at that. Or you could do C-style "inheritance" and slap some D magic on top of that. Some pseudo code: struct Base { enum SubType subtype; int someBaseField; } struct Child1 { Base base; // Must be first int foo; } struct Child2 { Base base; float bar; } Base b; Child1 c1; Child2 c2; base_doSomething(Base* b); child1_doSomething(Child1* c1); child2_doSomething(Child2* c2); base_doSomething(cast(Base*)&c1); switch(base.subtype) { case Child1: child1_doSomething(cast(Child1*)&b); break; case Child2: child2_doSomething(cast(Child2*)&b); break; } // add some alias this and other d things to smooth things out.
Re: DMD Windows 64bit target - how to setup the environment?
Thank You for fast help! I just reply late because I wanted to try out many things. With Benjamin's list it was indeed easy to set up the environment. I also installed LDC and it worked without problems too. Made some tests about sse vectorization and it turned out that I'm in love with LDC now :D ( https://realhet.wordpress.com/2017/12/29/my-first-impressions-of-64-bit-dlang-compilers/ ) The next thing I wanna test is compiling speed. As you said, DMD is fast enought to let it just compile all the project in one run, because it reuses a lot of data it discovered through the compiling process. However I had a lot of experiences with Delphi which is a really fast one (at least on 32bits, without sse vectorization), and on top of that is uses incremental compilation. Later I got to Qt+MSVC, and noticed that my 40K LOC not-so-big project takes 40 seconds to compile and another 10 to launch in the debugger. At the time when the program started, I already forgot why I started it to debug, lol. So that's why I was happy to find D, an elegant language that compiles fast, (not as fast as Delphi, 'though, but it is really comparable to it). So for development, I made a small incremental build manager thingie: It launches a DMD for each of the modules, that aren't in its cache. For a 6K LOC, 220KB project i was able to test, it works well: When I modify a only high level module, it only takes 3 seconds to launch, not 7 while I build it once with DMD. When the object cache is empty, it takes 6 seconds on all 8 cores, but it has to be done only once. On Delphi I had usually 0.5sec launch times when I changed only a few units, so if I have to choose 7 secs of 3 secs, then it's not even a question. Anyways, Thank You for help again!
Digital mars QT interface?
I would like to know if there is any repository that uses QT to create QT creator-style programs with buttons and combobox cute?
What could this OptLink Error mean?
I was building one example of DLangUi (dub build --build-mode=allAtOnce --build=debuglinker) and it did compile but the linker started to complain. I did notice it seemed to be related to the standard library, so I updated it and DRuntime to the lastest master, rebuilt them and replaced phobos.lib with the result. I also removed the binary and .dub directory from DLangUI to force Dub to rebuild it, which it did. Still the linker complains, but about a different symbol: ..\..\lib\dlangui.lib(colors) Error 42: Symbol Undefined __d_switch_string Does anybody have an idea what could be causing this?
Re: Difference in reduce in std and mir
On Tuesday, 26 December 2017 at 16:12:07 UTC, Seb wrote: On Tuesday, 26 December 2017 at 15:56:19 UTC, Vino wrote: Hi All, What is the difference between std.algorithm.reduce and mir.ndslice.algorithm.reduce. From, Vino.B Mir's reduce works on Slices whereas Phobos's reduce works on Arrays/Ranges. See also: http://docs.algorithm.dlang.io/latest/mir_ndslice_slice.html Mir's reduce works for arrays and ranges too. The difference it that how it works for Slices: it reduces all dimensions of top dimension pack. -- Ilya
Re: how to localize console and GUI apps in Windows
On Fri, Dec 29, 2017 at 10:35:53AM +, Andrei via Digitalmars-d-learn wrote: > On Thursday, 28 December 2017 at 18:45:39 UTC, H. S. Teoh wrote: > > On Thu, Dec 28, 2017 at 05:56:32PM +, Andrei via Digitalmars-d-learn > > wrote: > > ... > > The string / wstring / dstring types in D are intended to be Unicode > > strings. If you need to use other encodings, you really should be > > using ubyte[] or const(ubyte)[] or immutable(ubyte)[], instead of > > string. > > Thank you Teoh for advise and good example! I was looking towards > writing something like that if no decision exists. Still this way of > deliberate translations seems to be not the best. It supposes explicit > workaround for every ahchoo in Russian and steady converting ubyte[] > to string and back around. No formatting gems, no simple and elegant > I/O statements or string/char comparisons. This may be endurable if > you write an application where Russian is only one of rare options, > and what if your whole environment is totally Russian? You mean if your environment uses a non-UTF encoding? If your environment uses UTF, there is no problem. I have code with strings in Russian (and other languages) embedded, and it's no problem because everything is in Unicode, all input and all output. But I understand that in Windows you may not have this luxury. So you have to deal with codepages and what-not. Converting back and forth is not a big problem, and it actually also solves the problem of string comparisons, because std.uni provides utilities for collating strings, etc.. But it only works for Unicode, so you have to convert to Unicode internally anyway. Also, for static strings, it's not hard to make the codepage mapping functions CTFE-able, so you can actually write string literals in a codepage and have the compiler automatically convert it to UTF-8. The other approach, if you don't like the idea of converting codepages all the time, is to explicitly work in ubyte[] for all strings. Or, preferably, create your own string type with ubyte[] representation underneath, and implement your own comparison functions, etc., then use this type for all strings. Better yet, contribute this to code.dlang.org so that others who have the same problem can reuse your code instead of needing to write their own. [...] > p.s. I’ve found that I may set “Consolas” font for a console window > and then you can output properly localized UTF8 strings without any > special code in D script managing code pages. Still this does not > decide localized input problem: any localized input throws an > exception “std.utf.UTFException... Invalid UTF-8 sequence”. Is the exception thrown in readln() or in writeln()? If it's in writeln(), it shouldn't be a big deal, you just have to pass the data returned by readln() to fromKOI8 (or whatever other codepage you're using). If the problem is in readln(), then you probably need to read the input in binary (i.e., as ubyte[]) and convert it manually. Unfortunately, there's no other way around this if you're forced to use codepages. The ideal situation is if you can just use Unicode throughout your environment. But of course, sometimes you have no choice. T -- Heuristics are bug-ridden by definition. If they didn't have bugs, they'd be algorithms.
How do you safely deal with range.front?
Hi, So when I'm dealing with ranges, there're a number of times where I get the front of the returned result of a set of operations, but of course there is no front so you get an runtime access error. In some other languages the concept of "front" or "first" returns a safe referece, or optional value that calling methods on will not crash the program. I'm thinking of maybe making something like safeFront(R)(R r) { return r.empty ? SafeRef!(ElementType!R) : SafeRef(r.front); } Where SafeRef, I think, can provide an overload for opDispatch and just forward the calls to the stored reference of r.front. If the stored reference is null then it can return a SafeRef to the return value of whatever was being dispatched to. Is there another way to go about this? Maybe through naturally using r.front instead of making a r.safeFront alternative? Cheers
Re: structs inheriting from and implementing interfaces
On Friday, 29 December 2017 at 13:08:38 UTC, rikki cattermole wrote: On 29/12/2017 12:59 PM, rjframe wrote: On Fri, 29 Dec 2017 12:39:25 +, Nicholas Wilson wrote: [...] I've actually thought about doing this to get rid of a bunch of if qualifiers in my function declarations. `static interface {}` compiles but doesn't [currently] seem to mean anything to the compiler, but could be a hint to the programmer that nothing will directly implement it; it's a compile-time interface. This would provide a more generic way of doing stuff like `isInputRange`, etc. Or we could get signatures, which are even better still! + for SML style signatures!
Re: How do you safely deal with range.front?
On Friday, 29 December 2017 at 19:38:44 UTC, aliak wrote: Hi, So when I'm dealing with ranges, there're a number of times where I get the front of the returned result of a set of operations, but of course there is no front so you get an runtime access error. [...] Do you know about the proposed `orElse`? https://github.com/dlang/phobos/pull/5154
Re: How do you safely deal with range.front?
On Friday, December 29, 2017 19:38:44 aliak via Digitalmars-d-learn wrote: > Hi, > > So when I'm dealing with ranges, there're a number of times where > I get the front of the returned result of a set of operations, > but of course there is no front so you get an runtime access > error. You don't necessarily get a runtime access error. It is undefined behavior to call front on a range that's empty, and what happens depends entirely on how the range is implemented. In plenty of cases, you'll get really weird stuff happening and no obvious error. It is a bug for any code to call front when empty is true. > In some other languages the concept of "front" or "first" returns > a safe referece, or optional value that calling methods on will > not crash the program. > > I'm thinking of maybe making something like > > safeFront(R)(R r) { >return r.empty ? SafeRef!(ElementType!R) : SafeRef(r.front); > } > > Where SafeRef, I think, can provide an overload for opDispatch > and just forward the calls to the stored reference of r.front. If > the stored reference is null then it can return a SafeRef to the > return value of whatever was being dispatched to. > > Is there another way to go about this? Maybe through naturally > using r.front instead of making a r.safeFront alternative? Well, I don't know what you're really doing in code here, but in general, you'd write your code in a way that it checks empty and simply doesn't try to do anything with front if the range is empty. If you're trying to require that there's a front regardless of whether there is one, that sounds to me like you're just asking for trouble, and if it were me, I'd refactor my code so that that sort of thing wasn't happening. But if you have a use case where that really does make sense, then there are a few options. You could wrap the range in a range that returns a Nullable!(ElementType!R) and return null when there is no front, which would then require the calling code to check whether the Nullable was null rather than checking the range for empty. You could wrap the range in a range that specifically returns some default element when the wrapped range is empty, meaning that the range would then be infinite. You could just use a wrapper function to call front and have it return a Nullable or a default value if the range is empty, but that wouldn't work when passing the range to other functions. You could also do something like an infinite range that simply returns the same value forever no matter how often front gets popped, and then you could use chain to combine your range and that range into a single range that would iterate through your range and then give the same element forever. Regardless, you'll have to be careful of any solution that involves creating an infinite range, since while some algorithms will be fine with it, others will either not compile or result in an infinite loop (e.g. don't use foreach on it). Regardless, if you want to return an element when there isn't one, you're going to have to come up with a value for that. It's not something that's really going to work well generically. The closest would be the init value of the element type, but how much that makes sense depends on the element type and what you're doing. - Jonathan M Davis
Re: How do you safely deal with range.front?
On Friday, 29 December 2017 at 19:38:44 UTC, aliak wrote: So when I'm dealing with ranges, there're a number of times where I get the front of the returned result of a set of operations, but of course there is no front so you get an runtime access error. This could be what you want: auto makeInfinite(Range)(Range ofThis) { import std.range; return ofThis.chain(typeof(ofThis.front).init.repeat); } void main() { import std.stdio, std.range; auto testArray = [2, 3, 4].makeInfinite; foreach(e; testArray.take(5)) e.writeln; readln(); //stops the console from closing immediately; } /+ 2 3 4 0 0 +/ On the other hand, I really do not recommend using ranges that way as a default. Most often you do not want to call front() or popFront() of an empty range in the first place. So if you end up doing so accidently, you want to know it. If it just returned some default value chances would be you never notice you have a bug. That's why front() in debug mode is usually programmed to termitate the program when it's called incorrectly.
Is Nullable supposed to provide Optional semantics?
I've been bitten by trying to use Nullable(T) on class types. Minimal example... import std.typecons : Nullable; void main() { auto o = new Object(); o.toString(); Nullable!Object n = o; o.toString(); n.nullify(); o.toString(); // SegV! } The SEGV is caused by nullify calling object.destroy() on o, invalidating it. This makes Nullable unsafe to use with class types when there may be other references to the optional values in the program. Perhaps I'm not using the correct abstraction. I'm looking for something equivalent to java.util.Optional, or Haskell's Maybe. If Nullable(T) *is* intended to be used like Java Optional, then calling .destroy when clearing the value seems to be going beyond its remit for class types. For those confused as to why you'd want to wrap a Nullable around something that already has nullable semantics, it's mostly about making APIs that explicitly declare their optional return values. See: http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html I also want to use it in template code that works with both value & reference types. Chris.
Re: Is Nullable supposed to provide Optional semantics?
On Friday, 29 December 2017 at 20:52:51 UTC, Chris Paulson-Ellis wrote: I've been bitten by trying to use Nullable(T) on class types. Minimal example... [...] use: n = Nullable!Object.init; //doesn't call destroy instead of: n.nullify();
Re: Is Nullable supposed to provide Optional semantics?
On Friday, 29 December 2017 at 21:34:27 UTC, vit wrote: use: n = Nullable!Object.init; //doesn't call destroy instead of: n.nullify(); Only nullify() can make isNull return true again. I need that semantic.
Re: Is Nullable supposed to provide Optional semantics?
On Friday, 29 December 2017 at 21:43:25 UTC, Chris Paulson-Ellis wrote: Only nullify() can make isNull return true again. I need that semantic. Quick idea without much afterthought: instead of Nullable, use pointer to o?
Re: Is Nullable supposed to provide Optional semantics?
On Friday, 29 December 2017 at 21:43:25 UTC, Chris Paulson-Ellis wrote: On Friday, 29 December 2017 at 21:34:27 UTC, vit wrote: use: n = Nullable!Object.init; //doesn't call destroy instead of: n.nullify(); Only nullify() can make isNull return true again. I need that semantic. import std.typecons : Nullable; auto o = new Object(); Nullable!Object n; assert(n.isNull == true); n = o; assert(n.isNull == false); n = Nullable!Object.init; assert(n.isNull == true); o.toString(); //OK assert(Nullable!Object.init.isNull == true); more: https://forum.dlang.org/thread/jrdedmxnycbqzcpre...@forum.dlang.org?page=1
Slices and Dynamic Arrays
In DLang Tour:Arrays https://tour.dlang.org/tour/en/basics/arrays there is: --- int size = 8; // run-time variable int[] arr = new int[size]; The type of arr is int[], which is a slice. --- In "D Slices" https://dlang.org/d-array-article.html there is: --- int[] a; // a is a slice Based on those two web pages it appears that the name for a dynamic array in D is "slice". That is, anytime you have a dynamic array (even a null reference version) it is called a slice. Is that correct?
Re: Slices and Dynamic Arrays
On Friday, 29 December 2017 at 22:32:01 UTC, Tony wrote: Based on those two web pages it appears that the name for a dynamic array in D is "slice". That is, anytime you have a dynamic array (even a null reference version) it is called a slice. Is that correct? Not exactly, but basically. read this for a bit more info https://dlang.org/d-array-article.html A slice is a bit more general than a dynamic array. You can slice into a static array, or any buffer really. The slice just also acts as a dynamic array and can create one on-demand if you append to it, and also slices are how D represents the underlying dynamic arrays to user code.
Re: Slices and Dynamic Arrays
On Friday, 29 December 2017 at 22:32:01 UTC, Tony wrote: In DLang Tour:Arrays https://tour.dlang.org/tour/en/basics/arrays there is: --- int size = 8; // run-time variable int[] arr = new int[size]; The type of arr is int[], which is a slice. --- In "D Slices" https://dlang.org/d-array-article.html there is: --- int[] a; // a is a slice Based on those two web pages it appears that the name for a dynamic array in D is "slice". That is, anytime you have a dynamic array (even a null reference version) it is called a slice. Is that correct? Not really, cause you can take a "slice" of a linked list (though inefficiently), but a linked list isn't an array. You can also take a "slice" of a stack allocated array.
Re: Slices and Dynamic Arrays
On Friday, December 29, 2017 22:32:01 Tony via Digitalmars-d-learn wrote: > In DLang Tour:Arrays > https://tour.dlang.org/tour/en/basics/arrays > > there is: > --- > int size = 8; // run-time variable > int[] arr = new int[size]; > > The type of arr is int[], which is a slice. > --- > > In "D Slices" > https://dlang.org/d-array-article.html > > there is: > --- > int[] a; // a is a slice > > > Based on those two web pages it appears that the name for a > dynamic array in D is "slice". That is, anytime you > have a dynamic array (even a null reference version) it is called > a slice. Is that correct? No. The term "slice" is a bit overused in D, meaning a variety of things. It doesn't help that some folks dislike the official terminology. In general, a slice is a contiguous group of elements. A slice of memory would be a contiguous block of memory. A dynamic array therefore refers to a slice of memory and could be called a slice, but it's also the case that using the slice operater on a container is called slicing - e.g. rbt[] would give you a range over the container rbt, and that range is a slice of the container, but it's not an array at all. The "D Slices" article is great for explaining how things work but does not use the official terminology. Per the official terminology, T[] is a dynamic array regardless of what memory it refers to. Assuming that it's non-null, it _does_ refer to a slice of memory, and a number of folks follow the article and call T[] a slice and refer to the GC-allocated memory that a T[] usually refers to as the dynamic array, but officially, T[] is the dynamic array, and the memory it refers to has no special name. It's just a block of memory that is usually GC-allocated, but it could be malloced or be a slice of a static array or any other type of memory (since you can create a dynamic array from pointers), and its semantics don't change based on what type of memory backs it. I gather that the author chose to refer to the GC-allocated block of memory as the dynamic array because of how the term dynamic array is sometimes used elsewhere in computer science, but as far as D is concerned, T[] is a dynamic array regardless of what memory it refers to, and personally, I think that focusing on the GC-allocated memory block as being the dynamic array causes confusion when dealing with dynamic arrays that refer to non-GC-allocated memory, since the semantics are identical regardless of what memory backs the array (it's just that if the array does not refer to a slice of GC-allocated memory, the capacity is always 0, guaranteed that appending will reallocate instead of it just being a possibility), but too many folks tend to think of them as being different. A dynamic array that refers to non-GC-allocated memory is really the same thing as one that is GC-allocated except that when you slice non-GC-allocated memory to create a dynamic array, you then need to be aware of how to manage the lifetime of that memory so that no dynamic array refering to it outlives it (just like you'd have to do with a pointer to non-GC-allocated memory). But dynamic arrays never manage their own memory. It's just that the GC does the managing by default and will reallocate the memory backing a dynamic array if an operation can't be done in-place. - Jonathan M Davis
Re: What could this OptLink Error mean?
On Friday, 29 December 2017 at 16:11:20 UTC, Dukc wrote: I was building one example of DLangUi (dub build --build-mode=allAtOnce --build=debuglinker) and it did compile but the linker started to complain. I did notice it seemed to be related to the standard library, so I updated it and DRuntime to the lastest master, rebuilt them and replaced phobos.lib with the result. I also removed the binary and .dub directory from DLangUI to force Dub to rebuild it, which it did. Still the linker complains, but about a different symbol: ..\..\lib\dlangui.lib(colors) Error 42: Symbol Undefined __d_switch_string Does anybody have an idea what could be causing this? The deps have to be rebuild too. Assuming paths and everything is okay (should be the case when you build ~master as indicated in the wiki) just add --force.
Re: why @property cannot be pass as ref ?
On Wednesday, 20 December 2017 at 18:43:21 UTC, Ali Çehreli wrote: Thanks to Mengü for linking to that section. I have to make corrections below. Ali Thanks for explain, Ali And Mengu. What I am try to do is implement a unique data type. (the ownership auto moved into new handle) consider this code: import std.stdio; struct S { @disable this(this); void* socket; this (void* i) { socket = i; } void opAssign()(auto ref S s ){ socket = s.socket ; s.socket = null ; } @nogc @safe ref auto byRef() const pure nothrow return { return this; } } void main() { static __gshared size_t socket; auto lvalue = S(&socket); // pass rvalue into lvalue, working S l2 = void; l2 = lvalue;// pass lvalue into lvalue, working auto l3 = l2.byRef; // pass lvalue into lvalue, not working } I can not assign l2 to l3 because "Error: struct app.S is not copyable because it is annotated with @disable", but it working if I init l3 with void.
Fiber.yield with call scope guard
I am look a method like Fiber.yieldAndThrow, but also call all scopeguard. I am hack Fiber into struct with no throw, try to use it on network project with high performance. I use scopeguard to auto release memory or resource, but when I call Fiber .yieldAndThrow the scopeguard chain will not be call. If there a is some Asm code to jump call scopeguard will solve the problem. the other solution will be try catch use with exception, and the code will not be able to work under BetterC.