Compare commits

..

No commits in common. "505f8e66aff350b74c2cc876ce36fad44e7e9e19" and "6dc02d4d3a1f951a7d07a2a63a4331fd710cc1f0" have entirely different histories.

2 changed files with 22 additions and 50 deletions

View file

@ -1,2 +0,0 @@
haddock-style: single-line
indentation: 2

View file

@ -7,69 +7,43 @@ import Data.ByteString.Char8 qualified as BC
import Data.Text (Text)
import Data.Text.Encoding (encodeUtf8)
import Data.Word (Word32, Word8)
import System.Posix (CMode (..), FileMode)
class Encode a where
encode :: a -> ByteString
encode = BS.drop 4 . encodeWithSize
encodeWithSize :: a -> ByteString
encodeWithSize x =
let s = encode x
l = fromIntegral $ BS.length s
in word32ToByteString l <> s
{-# MINIMAL encode | encodeWithSize #-}
encode :: a -> ByteString
instance Encode ByteString where
encode = id
encode = id
instance Encode Text where
encode = encodeUtf8
encode = encodeUtf8
instance Encode String where
encode = BC.pack
encode = BC.pack
type Byte = Word8
-- | @word32ToBytes@ splits a 32bit word into its 4 byte components.
--
-- >>> word32ToBytes 0xdeadbeef
-- (222,173,190,239)
--
-- >>> word32ToBytes 4
-- (0,0,0,4)
{- | @word32ToBytes@ splits a 32bit word into its 4 byte components.
>>> word32ToBytes 0xdeadbeef
(222,173,190,239)
-}
word32ToBytes :: Word32 -> (Byte, Byte, Byte, Byte)
word32ToBytes word = (a, b, c, d)
where
!a = fromIntegral $ (word .&. 0xff000000) `shift` (-24)
!b = fromIntegral $ (word .&. 0x00ff0000) `shift` (-16)
!c = fromIntegral $ (word .&. 0x0000ff00) `shift` (-8)
!d = fromIntegral $ (word .&. 0x000000ff) `shift` (-0)
where
!a = fromIntegral $ (word .&. 0xff000000) `shift` (-24)
!b = fromIntegral $ (word .&. 0x00ff0000) `shift` (-16)
!c = fromIntegral $ (word .&. 0x0000ff00) `shift` (-8)
!d = fromIntegral $ (word .&. 0x000000ff) `shift` (-0)
-- | @word32ToByteString@ encodes a 32-bit wide word into a bytestring.
--
-- >>> word32ToByteString 0xdeadbeef
-- "\222\173\190\239"
{- | @word32ToByteString@ encodes a 32-bit wide word into a bytestring.
>>> word32ToByteString 0xdeadbeef
"\222\173\190\239"
-}
word32ToByteString :: Word32 -> ByteString
word32ToByteString word =
let (a, b, c, d) = word32ToBytes word
in BS.pack [a, b, c, d]
let (a, b, c, d) = word32ToBytes word
in BS.pack [a, b, c, d]
instance Encode Word32 where
encode = word32ToByteString
encodeWithSize w =
let (a, b, c, d) = word32ToBytes w
in BS.pack
[ 0
, 0
, 0
, 4
, a
, b
, c
, d
]
instance Encode FileMode where
encode (CMode mode) = encode mode
encode = word32ToByteString