我正在尝试将一个字节串转换为Word16s列表。下面使用Data.Binary.Get的实现可以工作,但它是代码中的性能瓶颈。这是可以理解的,因为IO总是会很慢,但我想知道是否有更有效的方法来做到这一点。
getImageData' = do
e <- isEmpty
if e then return []
else do
w <- getWord16be
ws <- getImageData'
return $ w : ws
我正在尝试将一个字节串转换为Word16s列表。下面使用Data.Binary.Get的实现可以工作,但它是代码中的性能瓶颈。这是可以理解的,因为IO总是会很慢,但我想知道是否有更有效的方法来做到这一点。
getImageData' = do
e <- isEmpty
if e then return []
else do
w <- getWord16be
ws <- getImageData'
return $ w : ws
{-# language BangPatterns #-}
module Wordy where
import qualified Data.ByteString as BS
import Data.ByteString (ByteString)
import Data.Word (Word16)
import Data.Maybe (fromMaybe)
import Data.Bits (unsafeShiftL)
toDBs :: ByteString -> Maybe [Word16]
toDBs bs0
| odd (BS.length bs0) = Nothing
| otherwise = Just (go bs0)
where
go bs = fromMaybe [] $ do
(b1, bs') <- BS.uncons bs
(b2, bs'') <- BS.uncons bs'
let !res = (fromIntegral b1 `unsafeShiftL` 8) + fromIntegral b2
Just (res : go bs'')