Easy transition between lazy and strict ByteString
I need to work with strict and lazy ByteStrings because this requirement is dictated by the choice of libraries (some combinations of happstack, base64, sha256, hexpat, etc.). After some dancing with "fromStrict" and the like, I ended up with this:
import qualified Data.ByteString.Char8 as S
import qualified Data.ByteString.Lazy.Char8 as L
class BString s where
lazy :: s -> L.ByteString
strict :: s -> S.ByteString
pack :: String -> s
text :: T.Text -> s
instance BString L.ByteString where
lazy = id
strict = S.concat . L.toChunks
pack = L.pack
text = L.fromStrict . TE.encodeUtf8
instance BString S.ByteString where
lazy = L.fromStrict
strict = id
pack = S.pack
text = TE.encodeUtf8
so I just put "lazy" when the library function in hand requires a lazy byte string or "strict" in the case of the strict version. This works great, although it requires a random transformation, but it feels like I invented the bicycle here.
So the question is, is there a better (shorter, statically typed, more efficient) alternative to such code? Is there a library trying to unify lazy / strict handling? Or maybe I was doing the wrong thing and she considered it bad practice (you shouldn't switch between lazy and strict or whatever)?
Thank.
source to share
I would write an adaptation layer between your application and these libraries to do all the transformations needed. Create a responsive layer to use your preferred application data types as inputs and outputs for these functions.
Once you have selected modules, the library function signatures will never change. That is, you know which string will trigger the base64 encode call, will return (of your choice of the module.) So if you need to combine two library functions, you know exactly what conversions need to be done to make them match.
source to share