RE: Safe use of unsafeCoerce?

2004-04-26 Thread Simon Marlow
On 24 April 2004 17:38, Duncan Coutts wrote:

 All,
 
 I'm after advice on whether the following example is a safe use of
 unsafeCoerce, and if it is safe, if it's worth it.
 
 In summary, if the following is ok:
 
 castFooToBar :: Ptr Foo - Ptr Bar
 castFooToBar = castPtr
 
 then is the following ok?
 
 newtype Foo' = Foo' (Ptr Foo)
 newtype Bar' = Bar' (Ptr Bar)
 
 castFooToBar' :: Foo' - Bar'
 castFooToBar' = unsafeCoerce

If the runtime representation of Foo' and Bar' is the same, then this is
safe.  In this case the runtime representation is the same, so you're
ok.

However, it might not always be a good idea, because the compiler's
optimiser gets a bit stuck when it sees an unsafeCoerce.  I'd like to be
a bit more specific, but I'm not sure I can remember the specific
example.  On the other hand, Happy makes extensive use of unsafeCoerce
in its generated code (when you use -c), so in some cases the benefits
can definitely outweigh the costs.

 Here's the context/motivation:
[ snip ]
 toGObject   :: GObjectClass o = o - GObject
 toGObject = unsafeCoerce
 
 fromGObject :: GObjectClass o = GObject - o
 fromGObject = unsafeCoerce
 
 So, the point is we can remove entirely the class dictionary that
 otherwise has to be carried round for every object and the upcasting 
 downcasting functions no longer need to do slow dictionary lookups
 when all they are really doing is casting C pointers.
 
 So is it a) safe? b) kosher?

I think so.

On the other hand, you might want to look at using the trick that
wxHaskell uses for encoding the widget hierarchy, which also has zero
runtime cost.

Cheers,
Simon
___
Glasgow-haskell-users mailing list
[EMAIL PROTECTED]
http://www.haskell.org/mailman/listinfo/glasgow-haskell-users


Re: Safe use of unsafeCoerce?

2004-04-26 Thread Duncan Coutts
On Mon, 2004-04-26 at 15:42, Alastair Reid wrote:
  I'm after advice on whether the following example is a safe use of
  unsafeCoerce, and if it is safe, if it's worth it.
 
 It looks like it is safe but it feels like using a sledgehammer to crack a 
 nut ... in the presence of small children/ curious animals/ two left thumbs/ 
 etc. so you have to take great care that none of them are near the nut each 
 time you pull that sledgehammer out.
 
 Given the function castFooToBar (which you tell us is safe), there's a number 
 of obvious typesafe ways of writing this code, why not do so?  [I accept that 
 there could be some reasons I just didn't see you mention any.]

In the context of the Gtk class hierarchy, we do currently have a type
safe way of doing it (wrapBar.castForiegnPtr.unwrapFoo), but I'm trying
to eliminate the class dictionary overhead.

I'm open to other suggestions.

Duncan

___
Glasgow-haskell-users mailing list
[EMAIL PROTECTED]
http://www.haskell.org/mailman/listinfo/glasgow-haskell-users