unsafeShift operations for Data.Bits

Bulat Ziganshin bulat.ziganshin at gmail.com
Tue Nov 7 06:56:18 EST 2006


Hello Samuel,

Monday, November 6, 2006, 10:09:18 PM, you wrote:

>> > And use them for the default implementation of rotate, while we are at it.
>>
>> I thought you had a patch to GHC that worked really well?  I think it is
>> much beter idea to fix the inliner rather than exposing unsafe
>> functionality.

well, the whole story:

ghc provides unchecked* low-level operations that does shifts without
any checks. if shift is negative/too large, result value is not
specified (and actually depends on concrete C/cpu implementation)

haskell standard provides shiftL/R operation that had defined
behavior for bad shift values. in order to implement this, ghc checks
shift amount and only then performs actual shift

there are high-performance algorithms that demands highest possible
speed and at the same time make guarantees that shift amount will be
"right". imagine, for example, a bit array implementation

Samuel's patch improves inlining that allows to remove checks BUT only
in the case where shift amount is compile-time known! so, while his
patch is more general, it don't override need in unchecked shift
operations

> It isn't really *unsafe*, exactly. But it might not be purely
> functional. However, it isn't imperative or anything like that. Also,
> for rotate, I needed to change the implementations in the *libraries*
> (it was only the GHC-specific implementations, though). (Also, nobody
> seems to have applied that patch yet for some reason.) And I needed to
> change them to use the raw, unchecked primops.

these unsafe* operations will have the _same_ speed as unboxed
unchecked* ones. so, it's a much better. all the ghc-specific code
will be concentrated in a few simple lines instead of providing lot of
haskell-specific implementations for rather complex rotate* functions

> Oh, that reminds me. Why call them "unsafe"? Why not "unchecked" as
> GHC's primops are called?

it's tradition to call functions that should be used with caution as
unsafe*. there is also unsafeChr, for example. i personally prefer >>#
and <<# names, but don't think that we can do such namespace pollution in
widely used library


-- 
Best regards,
 Bulat                            mailto:Bulat.Ziganshin at gmail.com



More information about the Libraries mailing list