Skip to content

Instantly share code, notes, and snippets.

@hasufell
Last active July 4, 2022 15:55
Show Gist options
  • Save hasufell/c9614df236bf0a0a78ecf45d52df08b8 to your computer and use it in GitHub Desktop.
Save hasufell/c9614df236bf0a0a78ecf45d52df08b8 to your computer and use it in GitHub Desktop.
foldr' :: (Word8 -> a -> a) -> a -> ShortByteString -> a
foldr' k v = Foldable.foldr' k v . unpack
----
unpack :: ShortByteString -> [Word8]
unpack = unpackBytes
{-# INLINE unpack #-}
unpackBytes :: ShortByteString -> [Word8]
unpackBytes sbs = let ix = length sbs - 1
in List.map (unsafeIndex sbs) [0..ix]
{-# INLINE unpackBytes #-}
foldr' :: (Word8 -> a -> a) -> a -> ShortByteString -> a
foldr' k v = Foldable.foldr' k v . unpack
----
unpack :: ShortByteString -> [Word8]
unpack = unpackBytes
unpackBytes :: ShortByteString -> [Word8]
unpackBytes sbs = unpackAppendBytesLazy sbs []
unpackAppendBytesLazy :: ShortByteString -> [Word8] -> [Word8]
unpackAppendBytesLazy sbs = go 0 (length sbs)
where
sz = 100
go off len ws
| len <= sz = unpackAppendBytesStrict sbs off len ws
| otherwise = unpackAppendBytesStrict sbs off sz remainder
where remainder = go (off+sz) (len-sz) ws
unpackAppendBytesStrict :: ShortByteString -> Int -> Int -> [Word8] -> [Word8]
unpackAppendBytesStrict !sbs off len = go (off-1) (off-1 + len)
where
go !sentinal !i !acc
| i == sentinal = acc
| otherwise = let !w = indexWord8Array (asBA sbs) i
in go sentinal (i-1) (w:acc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment