Skip to content

Commit

Permalink
Merge pull request #28 from jprider63/master
Browse files Browse the repository at this point in the history
Wraps bad character sets
  • Loading branch information
elliottt committed Jan 7, 2015
2 parents e53e30a + eab8218 commit ecb449f
Showing 1 changed file with 13 additions and 1 deletion.
14 changes: 13 additions & 1 deletion src/Data/Serialize.hs
Expand Up @@ -255,6 +255,14 @@ instance (Serialize a,Integral a) => Serialize (R.Ratio a) where

------------------------------------------------------------------------

-- Safely wrap `chr` to avoid exceptions.
-- `chr` source: http://hackage.haskell.org/package/base-4.7.0.2/docs/src/GHC-Char.html#chr
chrEither :: Int -> Either String Char
chrEither i
| i <= 0x10FFFF = Right (chr i) -- Or: C# (chr# i#)
| otherwise =
Left ("bad argument: " ++ show i)

-- Char is serialised as UTF-8
instance Serialize Char where
put a | c <= 0x7f = put (fromIntegral c :: Word8)
Expand Down Expand Up @@ -296,7 +304,11 @@ instance Serialize Char where
z <- liftM (xor 0x80) getByte
return (z .|. shiftL6 (y .|. shiftL6
(x .|. shiftL6 (xor 0xf0 w))))
return $! chr r
case chrEither r of
Right r' ->
return $! r'
Left err ->
fail err

------------------------------------------------------------------------
-- Instances for the first few tuples
Expand Down

0 comments on commit ecb449f

Please sign in to comment.