Re: MD5 hash on a file and rawRead
On Wed, 09 Feb 2011 23:01:47 -0500, Andrej Mitrovic wrote: I'm trying to use the std.md5.sum method. It takes as an argument a digest to output the hash to, and the second argument is plain data. So I'm trying to read an entire file at once. I thought about using rawRead, but I get a runtime exception: auto filename = rC:\file.dat; File file; try { file = File(filename, r); } catch (ErrnoException exc) { return; } ubyte[] buffer; file.rawRead(buffer); error: stdio.d:rawRead must take a non-empty buffer There are no size methods for the File structure (why?). There's a getSize function but it's in std.file, and I can't use it because: auto filename = rC:\file.dat; File file; try { file = File(filename, r); } catch (ErrnoException exc) { return; } ubyte[] buffer = new ubyte[](getSize(filename)); ubyte[16] digest; file.rawRead(buffer); std.md5.sum(digest, buffer); Error: cannot implicitly convert expression (getSize(cast(const(char[]))this._libFileName)) of type ulong to uint I can use the buffered version fine: auto filename = rC:\file.dat; File file; try { file = File(filename, r); } catch (ErrnoException exc) { return; } ubyte[16] digest; MD5_CTX context; context.start(); foreach (ubyte[] buffer; file.byChunk(4096 * 1024)) { context.update(buffer); } context.finish(digest); writefln(MD5 (%s) = %s, filename, digestToString(digest)); But I'd prefer to write simpler code and use rawRead to read the entire file at once. I'm reading really small files, so rawRead should be fine. To read an entire file at once, you should use std.file.read(), or std.file.readText() if it's an UTF encoded text file. Also, why do we have file handling in two different modules? I'd expect to find all file handling ops in std.file, not scattered around Phobos. Let me know if I'm doing something obviously stupid. :) There are actually three modules for file handling, but I think they are nicely separated: - std.file handles files as isolated units, i.e. it reads, writes and manipulates entire files. - std.path manipulates file/directory names as strings, and performs no disk I/O. - std.stdio is for more advanced file I/O, as it lets you open files and manipulate them through the File handle. (This includes reading, writing, seeking, etc.) Hope this clears things up. :) -Lars
How to web programming with D2?
I am trying to write the web framework(but not to write, to gain experience.). Maybe the framework can has got a MVC desing pattern. But first, the D2 is not has got for the web library and I am decided write to library for web. I am writed a function for post and get methods. (I am not tried to functions. But I think, they are works.) POST: https://github.com/canalpay/turna/blob/master/library/post.d GET : https://github.com/canalpay/turna/blob/master/library/get.d Environment variables are easy to write for the function. But How to write a cookie and session? I looked at the codes of tango. However, don't understand.(I'm new to d programming language.)
Re: How to web programming with D2?
On Thu, 10 Feb 2011 04:29:21 -0500, canalpay wrote: I am trying to write the web framework(but not to write, to gain experience.). Maybe the framework can has got a MVC desing pattern. But first, the D2 is not has got for the web library and I am decided write to library for web. I am writed a function for post and get methods. (I am not tried to functions. But I think, they are works.) POST: https://github.com/canalpay/turna/blob/master/library/post.d GET : https://github.com/canalpay/turna/blob/master/library/get.d Environment variables are easy to write for the function. But How to write a cookie and session? I looked at the codes of tango. However, don't understand.(I'm new to d programming language.) Adam D. Ruppe does a lot of web development in D, and he has created a fairly extensive web-dev library. http://arsdnet.net/dcode/ For cookie/session handling, cgi.d is probably the place to look. -Lars
Dynamic and Static Casting
Greetings All I have learnt that D has only one casting operator and that is 'cast'. The same operator assumes different functionality depending on the context in which it he being used. Now I have a situation where I have to downcast an object and I am sure of the objects type and thereby I am sure that the downcast would only be successful. To make the operation faster, in C++ I could have used static_cast operator, thus giving the RTTI a skip. Would this be possible in D? Can I force a static_cast which downcasting? Regards - Cherry
Re: Dynamic and Static Casting
d coder: I have learnt that D has only one casting operator and that is 'cast'. The same operator assumes different functionality depending on the context in which it he being used. Walter likes this design, I presume he thinks it's simpler. Now I have a situation where I have to downcast an object and I am sure of the objects type and thereby I am sure that the downcast would only be successful. To make the operation faster, in C++ I could have used static_cast operator, thus giving the RTTI a skip. Would this be possible in D? Can I force a static_cast which downcasting? There is no direct support for it because it's considered bad, so this is usually not done in D, it's for special situations only: class Foo {} class Bar : Foo {} Bar test1() { Foo f = new Foo; Bar b = cast(Bar)f; return b; } Bar test2() { Foo f = new Foo; Bar b = cast(Bar)cast(void*)f; return b; } void main() {} DMD 2.051, -O -release -inline: _D4test5test1FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Bar7__ClassZ mov ECX,offset FLAT:_D4test3Foo7__ClassZ pushEAX pushECX callnear ptr __d_newclass add ESP,4 pushEAX callnear ptr __d_dynamic_cast add ESP,8 pop ECX ret _D4test5test2FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Foo7__ClassZ pushEAX callnear ptr __d_newclass add ESP,4 pop ECX ret Bye, bearophile
Re: Dynamic and Static Casting
On Thu, 10 Feb 2011 11:54:02 +, Lars T. Kyllingstad wrote: On Thu, 10 Feb 2011 16:44:12 +0530, d coder wrote: Greetings All I have learnt that D has only one casting operator and that is 'cast'. The same operator assumes different functionality depending on the context in which it he being used. Now I have a situation where I have to downcast an object and I am sure of the objects type and thereby I am sure that the downcast would only be successful. To make the operation faster, in C++ I could have used static_cast operator, thus giving the RTTI a skip. Would this be possible in D? Can I force a static_cast which downcasting? Here's one solution. [...] Ok, bearophile's solution is better, because it has fewer casts. I forgot you can cast to void*. So here's an improved version, with some template constraints to make sure it's only used for class types: T staticCast(T, U)(U obj) if (is(T == class) is(U == class)) { return cast(T) cast(void*) obj; } -Lars
Re: Invoke garbage collector?
On 02/09/2011 10:15 PM, Steven Schveighoffer wrote: On Wed, 09 Feb 2011 15:58:13 -0500, bearophile bearophileh...@lycos.com wrote: Sean Eskapp: so is there a way to invoke a GC cleanup in some way? http://www.digitalmars.com/d/2.0/phobos/core_memory.html#minimize This attempts to minimize memory, it does not run a collection cycle (I don't think anyways). To invoke the GC collector, use: http://www.digitalmars.com/d/2.0/phobos/core_memory.html#collect -Steve But won't this blindly run a GC cycle? What if all I want is a given thingy's mem to be released, isn't it overkill to call GC.collect? Denis -- _ vita es estrany spir.wikidot.com
Re: Dynamic and Static Casting
Lars T. Kyllingstad: Ok, bearophile's solution is better, because it has fewer casts. And your solution was better because it's inside a function :-) I forgot you can cast to void*. So here's an improved version, with some template constraints to make sure it's only used for class types: T staticCast(T, U)(U obj) if (is(T == class) is(U == class)) { return cast(T) cast(void*) obj; } And what about: import std.stdio, std.traits, std.typetuple; /// C++ static_cast for just down-casting T staticDownCast(T, F)(F from) if (is(F == class) is(T == class) staticIndexOf!(F, BaseClassesTuple!T) != -1) in { assert((from is null) || cast(T)from !is null); } body { return cast(T)cast(void*)from; } class Foo {} class Bar : Foo {} class Spam {} Bar test1() { Foo f = new Foo; Bar b = cast(Bar)f; return b; } Bar test2() { Foo f = new Foo; Bar b = staticDownCast!Bar(f); return b; } void main() { Spam s = new Spam; Bar b = staticDownCast!Bar(s); // error } /* _D4test5test1FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Bar7__ClassZ mov ECX,offset FLAT:_D4test3Foo7__ClassZ pushEAX pushECX callnear ptr __d_newclass add ESP,4 pushEAX callnear ptr __d_dynamic_cast add ESP,8 pop ECX ret _D4test5test2FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Foo7__ClassZ pushEAX callnear ptr __d_newclass add ESP,4 pop ECX ret */ Is a pair of similar staticDownCast(), staticUpCast() fit for Phobos? Bye, bearophile
opIn_r not detected
Hello, Implicite deref of struct pointers on member access works fine for data, methods, even special methods with language semantics like opEquals (see example below). But I cannot have 'in' work with method opIn_r. I get: Error: rvalue of in expression must be an associative array, not S* What do I have wrong? Or is it a bug: the compiler does not even search the struct for opIn_r? But then, why does it do it for opEquals? Denis struct S { int i; void show() { writeln(i); } const bool opEquals (ref const(S) s) { writeln(==); return (i == s.i); } bool opIn_r (int j) { return (i==j); } } unittest { S* sp = (S(1)); writeln(sp.i); sp.show(); S s2 = S(1); writeln(sp == s2); writeln(1 in sp); } -- _ vita es estrany spir.wikidot.com
Re: Dynamic and Static Casting
Thanks Lars and Bearophile, I will give it a try. I understand that static downcasting is dangerous. But there are places where efficiency is paramount and you are sure that the casting is safe. So I wholeheartedly second your proposal to have the stuff in phobos. Regards - Cherry
Re: Invoke garbage collector?
On Thu, 10 Feb 2011 07:34:53 -0500, spir denis.s...@gmail.com wrote: On 02/09/2011 10:15 PM, Steven Schveighoffer wrote: On Wed, 09 Feb 2011 15:58:13 -0500, bearophile bearophileh...@lycos.com wrote: Sean Eskapp: so is there a way to invoke a GC cleanup in some way? http://www.digitalmars.com/d/2.0/phobos/core_memory.html#minimize This attempts to minimize memory, it does not run a collection cycle (I don't think anyways). To invoke the GC collector, use: http://www.digitalmars.com/d/2.0/phobos/core_memory.html#collect -Steve But won't this blindly run a GC cycle? What if all I want is a given thingy's mem to be released, isn't it overkill to call GC.collect? Then you can free it via: http://www.digitalmars.com/d/2.0/phobos/core_memory.html#free The OP's question was how do I run the garbage collector. -Steve
Re: Dynamic and Static Casting
On Thu, 10 Feb 2011 08:02:08 -0500, d coder dlang.co...@gmail.com wrote: Thanks Lars and Bearophile, I will give it a try. I understand that static downcasting is dangerous. But there are places where efficiency is paramount and you are sure that the casting is safe. So I wholeheartedly second your proposal to have the stuff in phobos. Be aware that blindly casting interfaces is not a good idea. An interface pointer is offset into the object and the cast *must* be dynamic. Casting objects from one class to another should be reliable, however. -Steve
Re: Template for function or delegate (nothing else)
On 02/09/2011 11:05 PM, Steven Schveighoffer wrote: On Wed, 09 Feb 2011 16:41:25 -0500, useo u...@start.bg wrote: == Auszug aus bearophile (bearophileh...@lycos.com)'s Artikel useo: I just have a problem with my variables. For example... my class/template just looks like: class Example(T) if (is(T == delegate) || is(T == function)) { T callback; void setCallback(T cb) { callback = cb; } } This means that I need variables like Example!(void function ()) myVariable. But is there any possibility to use variables like Example myVariable? D is not the SML language, templates are just placeholders. If you don't instantiate a template, you have only a symbol. Example is only assignable to an alias (and in past, to a typedef): alias Example Foo; The template declaration only defines the type of a callback and perhaps one method-declaration nothing else. I already tried Example!(void*) because delegates and functions are void pointers but I always get an error. I hope there is any way to do this. I don't yet understand what you are trying to do. Other notes: - What if your T is a functor (a callable class/struct/union instance that defined opCall)? - sizeof of a function pointer is 1 CPU word, while a delegate is 2 CPU words (and a delegate clojure has stuff on the heap too, sometimes). Bye, bearophile Idea is the following: class Example(T) if (is(T == delegate) || is(T == function)) { T callback; void setCallback(T cb) { callback = cb; } void opCall() { callback(); } } other file: import example; private { Example variable; } void setExampleVariable(Example ex) { variable = ex; } void callCurrentExampleVariable() { variable(); } I don't think you want templates. What you want is a tagged union (and a struct is MUCH better suited for this): // untested! struct Example { private { bool isDelegate; union { void function() fn; void delegate() dg; } } void setCallback(void function() f) { this.fn = f; isDelegate = false;} void setCallback(void delegate() d) { this.dg = d; isDelegate = true;} void opCall() { if(isDelegate) dg(); else fn(); } } Waow, very nice solution. I really question the function/delegate distinction (mostly artificial, imo) that invents issues necessiting workarounds like that. What does it mean, what does it bring? Right, there is one pointer less for funcs. This save 4 or 8 bytes, so to say, nothing; who develops apps with arrays of billions of funcs? There are written in source ;-) Even then, if this saving of apointer was of any relevance, then it should be an implementation detail that does not leak into artificial semantic diff, creating issues on the programmer side. What do you think? Denis -- _ vita es estrany spir.wikidot.com
Re: opIn_r not detected
On Thu, 10 Feb 2011 07:59:06 -0500, spir denis.s...@gmail.com wrote: Hello, Implicite deref of struct pointers on member access works fine for data, methods, even special methods with language semantics like opEquals (see example below). But I cannot have 'in' work with method opIn_r. I get: Error: rvalue of in expression must be an associative array, not S* What do I have wrong? Or is it a bug: the compiler does not even search the struct for opIn_r? But then, why does it do it for opEquals? Denis struct S { int i; void show() { writeln(i); } const bool opEquals (ref const(S) s) { writeln(==); return (i == s.i); } bool opIn_r (int j) { return (i==j); } } unittest { S* sp = (S(1)); writeln(sp.i); sp.show(); S s2 = S(1); writeln(sp == s2); writeln(1 in sp); } There is a bug in the compiler that the message says associative array is required. There is a bugzilla issue somewhere on that... But it does look like it should work, I'd file a separate bugzilla on the opIn_r not working. -Steve
Re: Template for function or delegate (nothing else)
On Thu, 10 Feb 2011 08:39:13 -0500, spir denis.s...@gmail.com wrote: On 02/09/2011 11:05 PM, Steven Schveighoffer wrote: I don't think you want templates. What you want is a tagged union (and a struct is MUCH better suited for this): // untested! struct Example { private { bool isDelegate; union { void function() fn; void delegate() dg; } } void setCallback(void function() f) { this.fn = f; isDelegate = false;} void setCallback(void delegate() d) { this.dg = d; isDelegate = true;} void opCall() { if(isDelegate) dg(); else fn(); } } Waow, very nice solution. I really question the function/delegate distinction (mostly artificial, imo) that invents issues necessiting workarounds like that. What does it mean, what does it bring? A function pointer is compatible with a C function pointer. C does not have delegates, so if you want to do callbacks, you need to use function pointers. There is no way to combine them and keep C compatibility. Right, there is one pointer less for funcs. This save 4 or 8 bytes, so to say, nothing; who develops apps with arrays of billions of funcs? There are written in source ;-) Even then, if this saving of apointer was of any relevance, then it should be an implementation detail that does not leak into artificial semantic diff, creating issues on the programmer side. What do you think? What you want is already implemented. There is a relatively new phobos construct that builds a delegate out of a function pointer. In fact, my code could use it and save the tag: // again, untested! import std.functional : toDelegate; struct Example { private void delegate() dg; void setCallback(void function() f) { this.dg = toDelegate(f); } void setCallback(void delegate() d) { this.dg = d; } void opCall() { dg(); } } Note that toDelegate doesn't appear on the docs because of a doc generation bug... -Steve
Re: Invoke garbage collector?
Sean Eskapp wrote: I'm having an unfortunate DSFML issue, where failing to free objects like Images or Sprites causes exceptions to eventually be thrown. Calling the built-in member dispose() causes access violations, so I assume it's not for programmer use. However, I need the resources to be freed more quickly than the GC is apparently doing (I assume the Images and Sprites are eventually cleaned up), so is there a way to invoke a GC cleanup in some way? I don't think that invoking the garbage collector is a good solution in this case. dispose is indeed defined as protected, so you probably should not call it manually, but then there really should be a public dispose like function. The reason for the crashes when calling dispose manually is simple: dispose calls a c sfml function to release c resources. The destructor calls dispose again, dispose tries to free an invalid pointer - crash. So what should probably be done is to define a private m_disposed member and only call dispose if it hasn't been called before. Try to add this code to the DSFMLObject class in dsfml/system/common.d: - private: bool m_disposed = false; public: final void releaseRessources() //Needs a better name, though { if(m_disposed) return; dispose(); m_disposed = true; } - And change dispose() in the DSFmLObject ~this() to releaseRessources(); (Crashes might still occur if dispose is called directly. In the end, this might need a little more thinking, but that's up to the DSFML authors ;-)) -- Johannes Pfau signature.asc Description: PGP signature
Re: Invoke garbage collector?
Johannes Pfau wrote: Sean Eskapp wrote: I'm having an unfortunate DSFML issue, where failing to free objects like Images or Sprites causes exceptions to eventually be thrown. Calling the built-in member dispose() causes access violations, so I assume it's not for programmer use. However, I need the resources to be freed more quickly than the GC is apparently doing (I assume the Images and Sprites are eventually cleaned up), so is there a way to invoke a GC cleanup in some way? I don't think that invoking the garbage collector is a good solution in this case. dispose is indeed defined as protected, so you probably should not call it manually, but then there really should be a public dispose like function. The reason for the crashes when calling dispose manually is simple: dispose calls a c sfml function to release c resources. The destructor calls dispose again, dispose tries to free an invalid pointer - crash. So what should probably be done is to define a private m_disposed member and only call dispose if it hasn't been called before. Try to add this code to the DSFMLObject class in dsfml/system/common.d: - private: bool m_disposed = false; public: final void releaseRessources() //Needs a better name, though { if(m_disposed || m_preventDelete) return; dispose(); m_disposed = true; } - And change dispose() in the DSFmLObject ~this() to releaseRessources(); (Crashes might still occur if dispose is called directly. In the end, this might need a little more thinking, but that's up to the DSFML authors ;-)) The releaseRessources function should also check for m_preventDelete. Updated in the quote above. -- Johannes Pfau signature.asc Description: PGP signature
Re: Template for function or delegate (nothing else)
I implemented all I wanted and it works perfectly ;). But I'm using the if (is(T == delegate) || is(T == function))- statement in another class/template. class Example(T) if (is(T == delegate) || is(T == function)) { ... } Now, when I declare Example!(void function()) myVar; I always get: Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is(T == function)) Error: Example!(void function()) is used as a type When I declare myVar as Example!(function), I get some other errors. What's wrong with my code?
Re: Template for function or delegate (nothing else)
On Thu, 10 Feb 2011 09:09:03 -0500, useo u...@start.bg wrote: I implemented all I wanted and it works perfectly ;). But I'm using the if (is(T == delegate) || is(T == function))- statement in another class/template. class Example(T) if (is(T == delegate) || is(T == function)) { ... } Now, when I declare Example!(void function()) myVar; I always get: Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is(T == function)) Error: Example!(void function()) is used as a type When I declare myVar as Example!(function), I get some other errors. What's wrong with my code? Please post a full example that creates the error. From that error message, it appears that your code is correct, but I'd have to play with a real example to be sure. -Steve
Re: Template for function or delegate (nothing else)
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel On Thu, 10 Feb 2011 09:09:03 -0500, useo u...@start.bg wrote: I implemented all I wanted and it works perfectly ;). But I'm using the if (is(T == delegate) || is(T == function))- statement in another class/template. class Example(T) if (is(T == delegate) || is(T == function)) { ... } Now, when I declare Example!(void function()) myVar; I always get: Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is(T == function)) Error: Example!(void function()) is used as a type When I declare myVar as Example!(function), I get some other errors. What's wrong with my code? Please post a full example that creates the error. From that error message, it appears that your code is correct, but I'd have to play with a real example to be sure. -Steve I created a complete, new file with the following code: module example; void main(string[] args) { Example!(void function()) myVar; } class Example(T) if (is(T == delegate) || is(T == function)) { } And what I get is: example.d(4): Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is (T == function)) example.d(4): Error: Example!(void function()) is used as a type I'm using the current stable version 2.051.
Re: Template for function or delegate (nothing else)
== Auszug aus useo (u...@start.bg)'s Artikel == Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel On Thu, 10 Feb 2011 09:09:03 -0500, useo u...@start.bg wrote: I implemented all I wanted and it works perfectly ;). But I'm using the if (is(T == delegate) || is(T == function))- statement in another class/template. class Example(T) if (is(T == delegate) || is(T == function)) { ... } Now, when I declare Example!(void function()) myVar; I always get: Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is(T == function)) Error: Example!(void function()) is used as a type When I declare myVar as Example!(function), I get some other errors. What's wrong with my code? Please post a full example that creates the error. From that error message, it appears that your code is correct, but I'd have to play with a real example to be sure. -Steve I created a complete, new file with the following code: module example; void main(string[] args) { Example!(void function()) myVar; } class Example(T) if (is(T == delegate) || is(T == function)) { } And what I get is: example.d(4): Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is (T == function)) example.d(4): Error: Example!(void function()) is used as a type I'm using the current stable version 2.051. I noticed, that this error only occurs when I use function as template-type. When I use Example!(void delegate()) myVar; it compiles without any error. With function - Example!(void function()) myVar; I get the error(s) above.
Re: Template for function or delegate (nothing else)
On Thu, 10 Feb 2011 09:48:14 -0500, useo u...@start.bg wrote: I created a complete, new file with the following code: module example; void main(string[] args) { Example!(void function()) myVar; } class Example(T) if (is(T == delegate) || is(T == function)) { } And what I get is: example.d(4): Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is (T == function)) example.d(4): Error: Example!(void function()) is used as a type I'm using the current stable version 2.051. Found this invalid bug. Apparently, this is expected (!) behavior: http://d.puremagic.com/issues/show_bug.cgi?id=3464 So use this instead: class Example(T) if (is(T == delegate) || is(typeof(*T.init) == function)) Ugly, I know, but I guess that's what we got to work with. -Steve
Re: Template for function or delegate (nothing else)
== Auszug aus Steven Schveighoffer (schvei...@yahoo.com)'s Artikel On Thu, 10 Feb 2011 09:48:14 -0500, useo u...@start.bg wrote: I created a complete, new file with the following code: module example; void main(string[] args) { Example!(void function()) myVar; } class Example(T) if (is(T == delegate) || is(T == function)) { } And what I get is: example.d(4): Error: template instance Example!(void function()) does not match template declaration Example(T) if (is(T == delegate) || is (T == function)) example.d(4): Error: Example!(void function()) is used as a type I'm using the current stable version 2.051. Found this invalid bug. Apparently, this is expected (!) behavior: http://d.puremagic.com/issues/show_bug.cgi?id=3464 So use this instead: class Example(T) if (is(T == delegate) || is(typeof(*T.init) == function)) Ugly, I know, but I guess that's what we got to work with. -Steve Yes, looks a bit unusual but it works, thanks!
Re: Dynamic and Static Casting
On 02/10/2011 01:38 PM, bearophile wrote: Lars T. Kyllingstad: Ok, bearophile's solution is better, because it has fewer casts. And your solution was better because it's inside a function :-) I forgot you can cast to void*. So here's an improved version, with some template constraints to make sure it's only used for class types: T staticCast(T, U)(U obj) if (is(T == class) is(U == class)) { return cast(T) cast(void*) obj; } And what about: import std.stdio, std.traits, std.typetuple; /// C++ static_cast for just down-casting T staticDownCast(T, F)(F from) if (is(F == class) is(T == class) staticIndexOf!(F, BaseClassesTuple!T) != -1) in { assert((from is null) || cast(T)from !is null); } body { return cast(T)cast(void*)from; } class Foo {} class Bar : Foo {} class Spam {} Bar test1() { Foo f = new Foo; Bar b = cast(Bar)f; return b; } Bar test2() { Foo f = new Foo; Bar b = staticDownCast!Bar(f); return b; } void main() { Spam s = new Spam; Bar b = staticDownCast!Bar(s); // error } /* _D4test5test1FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Bar7__ClassZ mov ECX,offset FLAT:_D4test3Foo7__ClassZ pushEAX pushECX callnear ptr __d_newclass add ESP,4 pushEAX callnear ptr __d_dynamic_cast add ESP,8 pop ECX ret _D4test5test2FZC4test3Bar comdat L0: pushEAX mov EAX,offset FLAT:_D4test3Foo7__ClassZ pushEAX callnear ptr __d_newclass add ESP,4 pop ECX ret */ Is a pair of similar staticDownCast(), staticUpCast() fit for Phobos? I think so. Definitely need staticDownCast very often for all functionality in type-hierarchy-generic code where some arguments are known to be of a given subtype. Typically, some func produces a collection of a given supertype (say, Node). It may be stored on a member, or produced on need. Some other func takes such a collection as input; but using this func means we know all or some of the objects are of a given subtype (say AssignmentNode); and indeed, we need the additional members of the subtype. Other case, each Node holds one or more other nodes. In the general case, they can be of any subtype. But when a func takes an AssignmentNode, then it knows its subnodes must be NameNode and ExpressionNode, hey!, ain't it clever? And indeed it'll need to access members specific to their subtypes. But I have never needed upcast in D as of now. What are common use cases? Denis -- _ vita es estrany spir.wikidot.com
Re: MD5 hash on a file and rawRead
On 2/10/11, Lars T. Kyllingstad public@kyllingen.nospamnet wrote: To read an entire file at once, you should use std.file.read(), or std.file.readText() if it's an UTF encoded text file. I missed that method while browsing through the docs. Thanks. There are actually three modules for file handling, but I think they are nicely separated: - std.file handles files as isolated units, i.e. it reads, writes and manipulates entire files. - std.path manipulates file/directory names as strings, and performs no disk I/O. - std.stdio is for more advanced file I/O, as it lets you open files and manipulate them through the File handle. (This includes reading, writing, seeking, etc.) Hope this clears things up. :) -Lars Yeah I know there's 3 modules, I'd still prefer having one module for file manipulation and one for the path string functionality. Right now I have to keep switching between stdio and file's documentation all the time, which is how I've managed to miss the .read method. Thanks again though.
Re: Dynamic and Static Casting
On Thu, 10 Feb 2011 11:38:40 -0500, spir denis.s...@gmail.com wrote: On 02/10/2011 01:38 PM, bearophile wrote: Is a pair of similar staticDownCast(), staticUpCast() fit for Phobos? But I have never needed upcast in D as of now. What are common use cases? Aren't all upcasts static anyways? -Steve
foreach over string enum
Hey guys, I'm trying to iterate over an enumeration which contains strings like the this: enum FileName : string { file1 = file1.ext, file2 = file2.ext } I already found this article: http://lists.puremagic.com/pipermail/ digitalmars-d/2007-July/021920.html but it's an enum which contains integers instead of strings, thus I can't use min- or max-property. Any suggestions - thanks in advance!
Re: Template for function or delegate (nothing else)
On 02/10/2011 02:51 PM, Steven Schveighoffer wrote: On Thu, 10 Feb 2011 08:39:13 -0500, spir denis.s...@gmail.com wrote: On 02/09/2011 11:05 PM, Steven Schveighoffer wrote: I don't think you want templates. What you want is a tagged union (and a struct is MUCH better suited for this): // untested! struct Example { private { bool isDelegate; union { void function() fn; void delegate() dg; } } void setCallback(void function() f) { this.fn = f; isDelegate = false;} void setCallback(void delegate() d) { this.dg = d; isDelegate = true;} void opCall() { if(isDelegate) dg(); else fn(); } } Waow, very nice solution. I really question the function/delegate distinction (mostly artificial, imo) that invents issues necessiting workarounds like that. What does it mean, what does it bring? A function pointer is compatible with a C function pointer. C does not have delegates, so if you want to do callbacks, you need to use function pointers. There is no way to combine them and keep C compatibility. Right, there is one pointer less for funcs. This save 4 or 8 bytes, so to say, nothing; who develops apps with arrays of billions of funcs? There are written in source ;-) Even then, if this saving of apointer was of any relevance, then it should be an implementation detail that does not leak into artificial semantic diff, creating issues on the programmer side. What do you think? What you want is already implemented. There is a relatively new phobos construct that builds a delegate out of a function pointer. In fact, my code could use it and save the tag: // again, untested! import std.functional : toDelegate; struct Example { private void delegate() dg; void setCallback(void function() f) { this.dg = toDelegate(f); } void setCallback(void delegate() d) { this.dg = d; } void opCall() { dg(); } } Note that toDelegate doesn't appear on the docs because of a doc generation bug... Right. I had not thought at the C-compatibility issue. So, let us say the func/dg distinction must remain in the language, on programmer-side, because of that. Then, is there anything that prevent the above cast to be implicit? Then, programmers would only have to define a single interface, using delegate everywhere; and not care about where and how user funcs are defined. (because as you know presently whether a ref'ed func becomes a func pointer or a delegate depends on /where/ it is defined...) Second point. I would like referencing of functions/delegates passed as arguments to be implicite. After all, conceptually, what we pass is a function object. Not a pointer. That the implementation needs to point them is just this, implementation. The '' just pollutes the code meaninglessly; and it's absence creates weird bugs: void f0 ( ) { writeln(1); } void f1 (int i) { writeln(i); } void do0 (void function ( ) f) { f( ); } void do1 (void function (int) f) { f(3); } unittest { // Error: function __trials__.do0 (void function() f) is not callable // using argument types (void) do0(f0); // __trials__.d(46): Error: function __trials__.f1 (int i) is not callable // using argument types () do1(f1); do0(f0); // ok do1(f1); // ok } Error messages are difficult to interpret for a diagnosis, I guess. Note that the first one concerns the caller, while the second one concerns the callee... Implicite referencing would solve that issue /and/ match semantics /and/ be more consistent /and/ make code nicer. About consistency, I mean that functions are already implicitely dereferenced: do1 does not need to call its arg f using (*f)(3); (this version works as well, indeed) denis -- _ vita es estrany spir.wikidot.com
Re: opIn_r not detected
On 02/10/2011 02:39 PM, Steven Schveighoffer wrote: On Thu, 10 Feb 2011 07:59:06 -0500, spir denis.s...@gmail.com wrote: Hello, Implicite deref of struct pointers on member access works fine for data, methods, even special methods with language semantics like opEquals (see example below). But I cannot have 'in' work with method opIn_r. I get: Error: rvalue of in expression must be an associative array, not S* What do I have wrong? Or is it a bug: the compiler does not even search the struct for opIn_r? But then, why does it do it for opEquals? Denis struct S { int i; void show() { writeln(i); } const bool opEquals (ref const(S) s) { writeln(==); return (i == s.i); } bool opIn_r (int j) { return (i==j); } } unittest { S* sp = (S(1)); writeln(sp.i); sp.show(); S s2 = S(1); writeln(sp == s2); writeln(1 in sp); } There is a bug in the compiler that the message says associative array is required. There is a bugzilla issue somewhere on that... But it does look like it should work, I'd file a separate bugzilla on the opIn_r not working. http://d.puremagic.com/issues/show_bug.cgi?id=5558 Content reproduced below; tell me please if the description is (not) ok. Denis == Issue 5558 - opIn_r not detected as method for 'in' in pointed struct In a struct, opIn_r is not detected by the compiler as beeing the method implementing the operator 'in'. Example: struct S { int i; void show() { writeln(i); } const bool opEquals (ref const(S) s) { writeln(==); return (i == s.i); } bool opIn_r (int j) { return (i==j); } } unittest { S* sp = (S(1)); writeln(sp.i); sp.show(); S s2 = S(1); writeln(sp == s2); writeln(1 in s2); // error: writeln(1 in sp); } == Error: rvalue of in expression must be an associative array, not S* This concerns opIn_r on pointed struct only; the other struct members of the structn and the not-pointed one are only here to contrast: * Data members, regular methods and even language methods like opEquals are correctly taken into account on a struct, even via implicite deref. * opIn_r is correctly detected as implementing 'in' on a non-pointed or explicitely dereferenced struct. Thus, the code works fine if one comments out the very last line. Waiting for a fix, the error message should be corrected to eg: Error: right operand of 'in' operation must be an associative array or implement the operator 'in' via method opIn_r -- _ vita es estrany spir.wikidot.com
Re: Template for function or delegate (nothing else)
On Thu, 10 Feb 2011 12:04:28 -0500, spir denis.s...@gmail.com wrote: On 02/10/2011 02:51 PM, Steven Schveighoffer wrote: On Thu, 10 Feb 2011 08:39:13 -0500, spir denis.s...@gmail.com wrote: On 02/09/2011 11:05 PM, Steven Schveighoffer wrote: I don't think you want templates. What you want is a tagged union (and a struct is MUCH better suited for this): // untested! struct Example { private { bool isDelegate; union { void function() fn; void delegate() dg; } } void setCallback(void function() f) { this.fn = f; isDelegate = false;} void setCallback(void delegate() d) { this.dg = d; isDelegate = true;} void opCall() { if(isDelegate) dg(); else fn(); } } Waow, very nice solution. I really question the function/delegate distinction (mostly artificial, imo) that invents issues necessiting workarounds like that. What does it mean, what does it bring? A function pointer is compatible with a C function pointer. C does not have delegates, so if you want to do callbacks, you need to use function pointers. There is no way to combine them and keep C compatibility. Right, there is one pointer less for funcs. This save 4 or 8 bytes, so to say, nothing; who develops apps with arrays of billions of funcs? There are written in source ;-) Even then, if this saving of apointer was of any relevance, then it should be an implementation detail that does not leak into artificial semantic diff, creating issues on the programmer side. What do you think? What you want is already implemented. There is a relatively new phobos construct that builds a delegate out of a function pointer. In fact, my code could use it and save the tag: // again, untested! import std.functional : toDelegate; struct Example { private void delegate() dg; void setCallback(void function() f) { this.dg = toDelegate(f); } void setCallback(void delegate() d) { this.dg = d; } void opCall() { dg(); } } Note that toDelegate doesn't appear on the docs because of a doc generation bug... Right. I had not thought at the C-compatibility issue. So, let us say the func/dg distinction must remain in the language, on programmer-side, because of that. Then, is there anything that prevent the above cast to be implicit? Then, programmers would only have to define a single interface, using delegate everywhere; and not care about where and how user funcs are defined. (because as you know presently whether a ref'ed func becomes a func pointer or a delegate depends on /where/ it is defined...) Second point. I would like referencing of functions/delegates passed as arguments to be implicite. After all, conceptually, what we pass is a function object. Not a pointer. That the implementation needs to point them is just this, implementation. The '' just pollutes the code meaninglessly; This is the way it is in C, and D purposely does not do this to avoid ambiguity (did you want to call the function or get it's address?). and it's absence creates weird bugs: void f0 ( ) { writeln(1); } void f1 (int i) { writeln(i); } void do0 (void function ( ) f) { f( ); } void do1 (void function (int) f) { f(3); } unittest { // Error: function __trials__.do0 (void function() f) is not callable // using argument types (void) do0(f0); // __trials__.d(46): Error: function __trials__.f1 (int i) is not callable // using argument types () do1(f1); do0(f0); // ok do1(f1); // ok } Error messages are difficult to interpret for a diagnosis, I guess. Note that the first one concerns the caller, while the second one concerns the callee... Implicite referencing would solve that issue /and/ match semantics /and/ be more consistent /and/ make code nicer. About consistency, I mean that functions are already implicitely dereferenced: do1 does not need to call its arg f using (*f)(3); (this version works as well, indeed) When properties are properly implemented, I expect this error message to be different. Currently, it thinks you are trying to call the function f0 and pass its result to do0. -Steve
Re: foreach over string enum
Nrgyzer Wrote: Hey guys, I'm trying to iterate over an enumeration which contains strings like the this: enum FileName : string { file1 = file1.ext, file2 = file2.ext } I already found this article: http://lists.puremagic.com/pipermail/ digitalmars-d/2007-July/021920.html but it's an enum which contains integers instead of strings, thus I can't use min- or max-property. Any suggestions - thanks in advance! I'll just be leaving this here, if you need more explanation ask, but maybe you'll understand: import std.stdio; enum FileName : string { file1 = file1.ext, file2 = file2.ext } void main(string args[]) { foreach(a; __traits(allMembers, FileName)) writeln(mixin(FileName. ~ a)); }
Re: foreach over string enum
== Auszug aus Jesse Phillips (jessekphillip...@gmail.com)'s Artikel Nrgyzer Wrote: Hey guys, I'm trying to iterate over an enumeration which contains strings like the this: enum FileName : string { file1 = file1.ext, file2 = file2.ext } I already found this article: http://lists.puremagic.com/ pipermail/ digitalmars-d/2007-July/021920.html but it's an enum which contains integers instead of strings, thus I can't use min- or max- property. Any suggestions - thanks in advance! I'll just be leaving this here, if you need more explanation ask, but maybe you'll understand: import std.stdio; enum FileName : string { file1 = file1.ext, file2 = file2.ext } void main(string args[]) { foreach(a; __traits(allMembers, FileName)) writeln(mixin(FileName. ~ a)); } I've already worked with the mixin-statement, but the __trait is new. As I can see in the documentation, it provides some interesting features. Your solution works great, thanks!
Re: std.concurrency immutable classes...
Michel Fortin napisał: Thanks for doing this. Is it approved by Walter? Depends on what you mean by approved. He commented once on the newsgroup after I posted an earlier version of the patch, saying I should add tests for type deduction and some other stuff. This change his something he attempted to do in the past and failed, I expect him to be skeptical. It would be much easier if he provided the specific case(s) which broke his teeth. Then we'll all know where's the problem. If it's soluble, it'll open the door to tail type modifiers in general, not just in classes. It's a burning issue e.g. with ranges (mostly struct). http://d.puremagic.com/issues/show_bug.cgi?id=5377 Look at the attachment to get a feel of what hoops we'll have to jump through to side-step lack of tail X. I guess he'll review it when he has the time and I hope he'll merge these changes in the mainline. He'll probably want to take his time however, since it can break existing code in some cases; it's basically a change to the language. If you want to show your support, I guess you can vote up the enhancement request in the bugzilla. http://d.puremagic.com/issues/show_bug.cgi?id=5325 Also feel free to compile it, test it, and share your experience. The more tested it is, the more used and appreciated it is, the more exposure it gets, the sooner it gets approved, or so I guess. I'd love to, but I'm putting shreds of my spare time to xml. -- Tomek
Re: std.concurrency immutable classes...
On Thu, 10 Feb 2011 14:45:14 -0500, Tomek Sowiński j...@ask.me wrote: Michel Fortin napisał: Thanks for doing this. Is it approved by Walter? Depends on what you mean by approved. He commented once on the newsgroup after I posted an earlier version of the patch, saying I should add tests for type deduction and some other stuff. This change his something he attempted to do in the past and failed, I expect him to be skeptical. It would be much easier if he provided the specific case(s) which broke his teeth. Then we'll all know where's the problem. If it's soluble, it'll open the door to tail type modifiers in general, not just in classes. It's a burning issue e.g. with ranges (mostly struct). http://d.puremagic.com/issues/show_bug.cgi?id=5377 Look at the attachment to get a feel of what hoops we'll have to jump through to side-step lack of tail X. I've worked through this very same problem (a few months back), thinking that we need a general solution to tail-const. The large issue with tail-const for structs in the general case is that you cannot control the type of 'this'. It's always ref. This might seem like a very inconsequential detail, but I realized that a ref to X does not implicitly convert to a ref to a tail-const X. This violates a rule of two indirections, in which case you are not able to implicitly convert the indirect type, even if the indirect type would implicitly convert outside the reference. A simple example, you cannot convert an int** to a const(int)**. Reason being, then you could change the indirect pointer to point to something that's immutable, and the original int ** now points to immutable data. The same is for tail-const structs, because you go through one ref via 'this' and the other ref via the referring member. What does this all mean? It basically means that you have to define *separate* functions for tail-const and const, and separate functions for tail-immutable and immutable. This is untenable. You might ask why doesn't this problem occur with tail-const arrays?, well because you *don't pass them by ref*. With structs we have no choice. I think what we need is a way to define two different structs as being the tail-const version of the other, with some compiler help, and then we do not need to define a new flavor of const functions. We still need to define these tail-const functions, but it comes in a more understandable form. But importantly, the implicit cast makes a *temporary* copy of the struct, allowing the cast to work. -Steve
Re: foreach over string enum
On 02/10/2011 08:22 PM, Jesse Phillips wrote: Nrgyzer Wrote: Hey guys, I'm trying to iterate over an enumeration which contains strings like the this: enum FileName : string { file1 = file1.ext, file2 = file2.ext } I already found this article: http://lists.puremagic.com/pipermail/ digitalmars-d/2007-July/021920.html but it's an enum which contains integers instead of strings, thus I can't use min- or max-property. Any suggestions - thanks in advance! I'll just be leaving this here, if you need more explanation ask, but maybe you'll understand: import std.stdio; enum FileName : string { file1 = file1.ext, file2 = file2.ext } void main(string args[]) { foreach(a; __traits(allMembers, FileName)) writeln(mixin(FileName. ~ a)); } Why the mixin? Is it (just) to have the output string computed at compile-time? Denis -- _ vita es estrany spir.wikidot.com
Re: foreach over string enum
spir Wrote: On 02/10/2011 08:22 PM, Jesse Phillips wrote: enum FileName : string { file1 = file1.ext, file2 = file2.ext } void main(string args[]) { foreach(a; __traits(allMembers, FileName)) writeln(mixin(FileName. ~ a)); } Why the mixin? Is it (just) to have the output string computed at compile-time? The value of 'a' is the enum field name, not its value. The code will ultimately expand to: void main() { writeln(FileName.file1)); writeln(FileName.file2)); } Which in turn will may have its enum contents expanded to the string value. The mixin is required because it is a named enum and 'a' is a string, not an alias: writeln(FileName.a) doesn't work and nor does: writeln(FileName.mixin(a));
Re: opIn_r not detected
On 02/10/2011 07:43 PM, Stewart Gordon wrote: On 10/02/2011 12:59, spir wrote: Hello, Implicite deref of struct pointers on member access works fine for data, methods, even special methods with language semantics like opEquals (see example below). But I cannot have 'in' work with method opIn_r. I get: Error: rvalue of in expression must be an associative array, not S* What do I have wrong? Or is it a bug: the compiler does not even search the struct for opIn_r? But then, why does it do it for opEquals? snip That got me thinking. It would appear that it auto-dereferences only the left operand. Try adding this to your code and see: writeln(s2 == sp); Works, indeed, but using opEquals on s2, and because s2 is not pointed. Denis -- _ vita es estrany spir.wikidot.com
Re: foreach over string enum
I don't have answers to your other questions. On 02/10/2011 03:25 PM, spir wrote: unittest { auto i = 1; auto s = i; It works if you define s as: enum s = i; writeln(mixin(i)); // compiler happy up to here -- 1 writeln(mixin(s)); // compiler unhappy -- Error: argument to mixin // must be a string, not (s) It now works. Ali
Assert compilation failure with certain message
Is there a way to statically assert compilation of an expression failed *with a certain message*? I want to check my static asserts trip when they should. -- Tomek
Re: Assert compilation failure with certain message
Tomek Sowiñski: Is there a way to statically assert compilation of an expression failed *with a certain message*? I want to check my static asserts trip when they should. I have asked something like this a lot of time ago, but I don't know a way to do it. You are able to statically assert that some code doesn't compile, but I don't know how to assert that a certain message gets produced. You are asking for a specific static catch :-) Bye, bearophile
Re: foreach over string enum
On 02/11/2011 01:02 AM, Ali Çehreli wrote: I don't have answers to your other questions. On 02/10/2011 03:25 PM, spir wrote: unittest { auto i = 1; auto s = i; It works if you define s as: enum s = i; writeln(mixin(i)); // compiler happy up to here -- 1 writeln(mixin(s)); // compiler unhappy -- Error: argument to mixin // must be a string, not (s) It now works. Ali Thank you, Ali. denis -- _ vita es estrany spir.wikidot.com
Re: Assert compilation failure with certain message
On Thursday, February 10, 2011 16:12:01 Tomek Sowiński wrote: Is there a way to statically assert compilation of an expression failed *with a certain message*? I want to check my static asserts trip when they should. You mean like static assert(0, We have a failure, Captain!); If a static assert fails, it's obvious. Compilation fails. Now, if you're trying to assert something like that a particular template instantiation fails, the use static assert(!__traits(compiles, exp)); where exp is the expression being tested. - Jonathan M Davis
Re: Assert compilation failure with certain message
bearophile napisał: Is there a way to statically assert compilation of an expression failed *with a certain message*? I want to check my static asserts trip when they should. I have asked something like this a lot of time ago, but I don't know a way to do it. You are able to statically assert that some code doesn't compile, but I don't know how to assert that a certain message gets produced. You are asking for a specific static catch :-) Static catch, yeah. But I'd be content with traits__(fails, expr, msg) which seems tractable. -- Tomek
Re: Assert compilation failure with certain message
How's this? import std.stdio; import std.conv; void staticAssert(alias exp, string message, string file = __FILE__, int line = __LINE__)() { static if (!exp) { pragma(msg, file ~ :( ~ to!string(line) ~ ) ~ staticAssert: ~ to!string(message)); assert(0); } } void main() { enum x = false; staticAssert!(x, Oh no we failed!); int y; }
Re: Assert compilation failure with certain message
I've managed to screw up the colon placement though, here's a quick fix: import std.stdio; import std.conv; void staticAssert(alias exp, string message, string file = __FILE__, int line = __LINE__)() { static if (!exp) { pragma(msg, file ~ ( ~ to!string(line) ~ ): ~ staticAssert: ~ to!string(message)); assert(0); } } void main() { enum x = false; staticAssert!(x, Oh no we failed!); int y; }
Re: Assert compilation failure with certain message
Tomek S.: Static catch, yeah. But I'd be content with traits__(fails, expr, msg) which seems tractable. Asking for new features in this newsgroup is not so useful. You may add it to bugzilla... Bye, bearophile
Re: foreach over string enum
spir Wrote: But in your example the symbol a does not look like a constant, instead it the loop variable. Do, how does it work? Magic. No really, the best I can tell is that the compiler will try to run the foreach loop at compile-time if there is something in the body that must be evaluated at compile time. The type you are iterating over must be known at compile-time, and just like any such value it is identified by its type and not its contents. So your array literal could in fact be built with a variable, the fact that it is not doesn't matter. I'm not sure if much thought has gone into compile-time-looping, the best way to enforce it is to get a function to run at compile time. I think the rule of when the body needs evaluated at compile-time is what's used, but this also means that when you try to iterate something like __traits or tupleof and don't use a compile-time construct in the body, you don't get an error or the loop executed.
Re: How to web programming with D2?
On 10.02.2011 10:29, canalpay wrote: I am trying to write the web framework(but not to write, to gain experience.). Maybe the framework can has got a MVC desing pattern. But first, the D2 is not has got for the web library and I am decided write to library for web. I am writed a function for post and get methods. (I am not tried to functions. But I think, they are works.) POST: https://github.com/canalpay/turna/blob/master/library/post.d GET : https://github.com/canalpay/turna/blob/master/library/get.d Environment variables are easy to write for the function. But How to write a cookie and session? I looked at the codes of tango. However, don't understand.(I'm new to d programming language.) From your code I assume you're using CGI. To set a cookie you have to set the Set-Cookie header with a string a specific format (see Cookies on Wikipedia link). In CGI the standard output of the program is used as HTTP response and therefore you can set headers by printing them first to stdout. After you're done writing headers (one per line usually) output an empty line. This marks the rest of the output as actual content of the response. So basically your program should output something like this: Content-Type: text/html Set-Cookie: name=value html … /html Depending on how you like to develop the RFCs for CGI and HTTP might come in handy. I sometimes also use Wikipedia to get an overview of the topic. - Cookies on Wikipedia: http://en.wikipedia.org/wiki/HTTP_cookie - HTTP on Wikipedia: http://en.wikipedia.org/wiki/Http - CGI on Wikipedia: http://en.wikipedia.org/wiki/Common_Gateway_Interface - CGI RFC: http://tools.ietf.org/html/rfc3875 - HTTP RFC: http://tools.ietf.org/html/rfc2616 Happy programming Stephan Soller