Bryan O'Sullivan avatar Bryan O'Sullivan committed 7ecced0

Speed up scan by a few percent more.

Comments (0)

Files changed (1)


 import Data.Monoid (Monoid(..))
 import Data.Word (Word8)
 import Foreign.ForeignPtr (withForeignPtr)
-import Foreign.Ptr (castPtr, plusPtr)
-import Foreign.Storable (Storable(peek, sizeOf), peekByteOff)
+import Foreign.Ptr (castPtr, minusPtr, plusPtr)
+import Foreign.Storable (Storable(peek, sizeOf))
 import Prelude hiding (getChar, take, takeWhile)
 import System.IO.Unsafe (unsafePerformIO)
 import qualified Data.ByteString as B8
 takeLazyByteString :: Parser L.ByteString
 takeLazyByteString = L.fromChunks `fmap` takeRest
+data T s = T {-# UNPACK #-} !Int s
 -- | A stateful scanner.  The predicate consumes and transforms a
 -- state argument, and each transformed state is passed to successive
 -- invocations of the predicate on each byte of the input until one
   go acc s1 = do
     let scanner (B.PS fp off len) =
-          withForeignPtr fp $ \ptr -> do
-            let inner !i !s | i == off+len = done (i-off) s
-                            | otherwise = do
-                                        w <- peekByteOff ptr i
-                                        case p s w of
-                                          Just s' -> inner (i+1) s'
-                                          Nothing -> done (i-off) s
-                done !i !s = return (B.PS fp off i, B.PS fp (off+i) (len-i),s)
-            inner off s1
-    (h,t,s') <- (unsafePerformIO . scanner) <$> get
+          withForeignPtr fp $ \ptr0 -> do
+            let start = ptr0 `plusPtr` off
+                end   = start `plusPtr` len
+                inner ptr !s
+                  | ptr < end = do
+                    w <- peek ptr
+                    case p s w of
+                      Just s' -> inner (ptr `plusPtr` 1) s'
+                      _       -> done (ptr `minusPtr` start) s
+                  | otherwise = done (ptr `minusPtr` start) s
+                done !i !s = return (T i s)
+            inner start s1
+    bs <- get
+    let T i s' = unsafePerformIO $ scanner bs
+        h = B.unsafeTake i bs
+        t = B.unsafeDrop i bs
     put t
     if B.null t
       then do
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.