From ed492ba62440cdfced0a12e35415d701988a77b7 Mon Sep 17 00:00:00 2001 From: simonmar Date: Tue, 21 Oct 2003 13:24:31 +0000 Subject: [PATCH] [project @ 2003-10-21 13:24:31 by simonmar] Make the GHC implementation of peekCString run in constant stack-space by checking the length of the array first and then working backwards from the end. Interestingly, this version is faster than the original. --- Foreign/C/String.hs | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/Foreign/C/String.hs b/Foreign/C/String.hs index d2d2a29..49d5a2d 100644 --- a/Foreign/C/String.hs +++ b/Foreign/C/String.hs @@ -86,14 +86,14 @@ peekCString :: CString -> IO String #ifndef __GLASGOW_HASKELL__ peekCString cp = do cs <- peekArray0 nUL cp; return (cCharsToChars cs) #else -peekCString cp = loop 0 +peekCString cp = do + l <- lengthArray0 nUL cp + if l <= 0 then return "" else loop "" (l-1) where - loop i = do + loop s i = do xval <- peekElemOff cp i let val = castCCharToChar xval - if (val `seq` (xval == nUL)) then return [] else do - rest <- loop (i+1) - return (val : rest) + val `seq` if i <= 0 then return (val:s) else loop (val:s) (i-1) #endif -- marshal a C string with explicit length into a Haskell string -- 1.7.10.4