utf8Encode :: String -> B.ByteString
utf8Encode = B.pack . concatMap unf . map fromEnum
  where unf x
            | x < 0x80     = [fromIntegral x]
            | x < 0x07ff   = [0xc0 .|. (sh 6 .&. 0x1f), cont 0]
            | x < 0xffff   = [0xe0 .|. (sh 12 .&. 0xf), cont 6, cont 0]
            | otherwise    = [0xf0 .|. (sh 18 .&. 0x7), cont 12, cont 6, cont 0]
          where sh w   = fromIntegral (x `shiftR` w)
                cont w = (sh w `setBit` 7) `clearBit` 6
utf8Encode :: String -> B.ByteString
utf8Encode = B.pack . concatMap unf . map fromEnum
  where unf x
            | x < 0x80     = [fromIntegral x]
            | x < 0x07ff   = [0xc0 .|. (sh 6 .&. 0x1f), cont 0]
            | x < 0xffff   = [0xe0 .|. (sh 12 .&. 0xf), cont 6, cont 0]
            | otherwise    = [0xf0 .|. (sh 18 .&. 0x7), cont 12, cont 6, cont 0]
          where sh w   = fromIntegral (x `shiftR` w)
                cont w = (sh w `setBit` 7) `clearBit` 6
utf8Encode = B.pack . concatMap unf . map fromEnum
  where unf x
            | x < 0x80     = [fromIntegral x]
            | x < 0x07ff   = [0xc0 .|. (sh 6 .&. 0x1f), cont 0]
            | x < 0xffff   = [0xe0 .|. (sh 12 .&. 0xf), cont 6, cont 0]
            | otherwise    = [0xf0 .|. (sh 18 .&. 0x7), cont 12, cont 6, cont 0]
          where sh w   = fromIntegral (x `shiftR` w)
                cont w = (sh w `setBit` 7) `clearBit` 6