BerkeleyDBXML-0.5: Database/Berkeley/Util.hs
module Database.Berkeley.Util
where
import Data.List
import Data.ByteString (ByteString)
import qualified Data.ByteString.Internal as BSI
import Foreign.ForeignPtr
import Foreign.Ptr
import Data.Word
locate :: (Eq a) => [a] -> [a] -> Maybe Int
locate needle haystack = locate_ needle haystack 0 where
locate_ _ [] _ = Nothing
locate_ needle haystack idx =
if isPrefixOf needle haystack
then Just idx
else locate_ needle (tail haystack) (idx+1)
maybeRead :: Read a => String -> Maybe a
maybeRead s = case reads s of
[(x, "")] -> Just x
_ -> Nothing
toDelim :: String -> Int -> [Char] -> String
toDelim line idx delims = takeWhile (flip notElem delims) (drop idx line)
extract :: String -> String -> [Char] -> Maybe String
extract tag line delims =
case locate tag line of
Just idx -> Just $ toDelim line (idx+(length tag)) delims
_ -> Nothing
withByteString :: ByteString -> (Ptr Word8 -> Int -> IO a) -> IO a
withByteString bs code = do
let (fp, fp_offset, length) = BSI.toForeignPtr bs
withForeignPtr fp $ \c_fp ->
code (c_fp `plusPtr` fp_offset) length