1
1
module Data.HexString ( HexString
2
2
, hexString
3
+ , hexString'
3
4
, fromBinary
5
+ , fromBinary'
4
6
, toBinary
5
7
, fromBytes
8
+ , fromBytes'
6
9
, toBytes
7
10
, toText ) where
8
11
@@ -27,33 +30,51 @@ data HexString =
27
30
deriving ( Show , Eq , Ord )
28
31
29
32
instance FromJSON HexString where
30
- parseJSON = withText " HexString" $ pure . hexString . TE. encodeUtf8
33
+ parseJSON = withText " HexString" $ toParser . TE. encodeUtf8
34
+ where
35
+ toParser input = case hexString' input of
36
+ (Just value) -> pure value
37
+ Nothing -> fail (" Not a valid hex string: " ++ show input)
31
38
32
39
instance ToJSON HexString where
33
40
toJSON = String . toText
34
41
35
42
-- | Smart constructor which validates that all the text are actually
36
43
-- hexadecimal characters.
37
- hexString :: BS. ByteString -> HexString
38
- hexString bs =
44
+ hexString' :: BS. ByteString -> Maybe HexString
45
+ hexString' bs =
39
46
let isValidHex :: Word8 -> Bool
40
47
isValidHex c
41
48
| (48 <= c) && (c < 58 ) = True
42
49
| (97 <= c) && (c < 103 ) = True
43
50
| otherwise = False
44
-
45
51
in if BS. all isValidHex bs
46
- then HexString bs
47
- else error (" Not a valid hex string: " ++ show bs)
52
+ then Just (HexString bs)
53
+ else Nothing
54
+
55
+ hexString :: BS. ByteString -> HexString
56
+ hexString bs = case hexString' bs of
57
+ Just hex -> hex
58
+ Nothing -> error (" Not a valid hex string: " ++ show bs)
59
+
60
+ -- | Converts a 'B.Binary' to a 'Maybe HexString' value
61
+ fromBinary' :: B. Binary a => a -> Maybe HexString
62
+ fromBinary' = hexString' . BS16. encode . BSL. toStrict . B. encode
48
63
49
64
-- | Converts a 'B.Binary' to a 'HexString' value
50
- fromBinary :: B. Binary a => a -> HexString
65
+ fromBinary :: B. Binary a => a -> HexString
51
66
fromBinary = hexString . BS16. encode . BSL. toStrict . B. encode
52
67
53
68
-- | Converts a 'HexString' to a 'B.Binary' value
54
69
toBinary :: B. Binary a => HexString -> a
55
70
toBinary (HexString bs) = B. decode . BSL. fromStrict . fst . BS16. decode $ bs
56
71
72
+ -- | Reads a 'BS.ByteString' as raw bytes and converts to hex representation. We
73
+ -- cannot use the instance Binary of 'BS.ByteString' because it provides
74
+ -- a leading length, which is not what we want when dealing with raw bytes.
75
+ fromBytes' :: BS. ByteString -> Maybe HexString
76
+ fromBytes' = hexString' . BS16. encode
77
+
57
78
-- | Reads a 'BS.ByteString' as raw bytes and converts to hex representation. We
58
79
-- cannot use the instance Binary of 'BS.ByteString' because it provides
59
80
-- a leading length, which is not what we want when dealing with raw bytes.
0 commit comments