Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Peek: Benchmark Ptr-Length-Offset instead of Ptr-Ptr #60

Open
Mathnerd314 opened this issue Jul 8, 2016 · 0 comments
Open

Peek: Benchmark Ptr-Length-Offset instead of Ptr-Ptr #60

Mathnerd314 opened this issue Jul 8, 2016 · 0 comments

Comments

@Mathnerd314
Copy link

Mathnerd314 commented Jul 8, 2016

If the type of Peek was

type Offset = Int
type Length = Int
newtype Peek = Peek { runPeek :: forall byte. Ptr byte -> Length -> IO (Offset, a) }

then most pointer subtractions and additions could be avoided; for example:

peekStorableTy ty = Peek $ \ptr blen ->
    let needed = sizeOf (undefined :: a)
     in do
        when (needed > blen) $
            tooManyBytes needed blen ty
        x <- Storable.peek (castPtr ptr)
        return (needed, x)

peekToPlainForeignPtr ty len =
    Peek $ \sourcePtr sourceLen -> do
        when (len > sourceLen) $
            tooManyBytes len sourceLen ty
        fp <- BS.mallocByteString len
        withForeignPtr fp $ \targetPtr ->
            BS.memcpy targetPtr (castPtr sourcePtr) len
        return (len, castForeignPtr fp)

They would move into the Peek monad:

    pure x = Peek (\_ _ -> return (0, x))
    Peek x >>= f = Peek $ \ptr blen -> do
        (off, x') <- x ptr blen
        runPeek (f x') (ptr `plusPtr` off) (blen - off)

The performance of the two Peek types should be close. But I thought I should ask before setting up the benchmark, in case this approach has already been considered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants