Skip to content

Commit

Permalink
Add indexMaybe and synonym to ShortByteString
Browse files Browse the repository at this point in the history
  • Loading branch information
FintanH authored and Cole Miller committed Aug 21, 2020
1 parent f2e918c commit d755b17
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion Data/ByteString/Short.hs
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,7 @@ module Data.ByteString.Short (
unpack,

-- * Other operations
empty, null, length, index,
empty, null, length, index, indexMaybe, (!?),

-- * Low level conversions
-- ** Packing 'Foreign.C.String.CString's and pointers
Expand Down
23 changes: 21 additions & 2 deletions Data/ByteString/Short/Internal.hs
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ module Data.ByteString.Short.Internal (
unpack,

-- * Other operations
empty, null, length, index, unsafeIndex,
empty, null, length, index, indexMaybe, (!?), unsafeIndex,

-- * Low level operations
createFromPtr, copyToPtr,
Expand Down Expand Up @@ -107,7 +107,8 @@ import Prelude ( Eq(..), Ord(..), Ordering(..), Read(..), Show(..)
, String, userError
, Bool(..), (&&), otherwise
, (+), (-), fromIntegral
, return )
, return
, Maybe(..) )


-- | A compact representation of a 'Word8' vector.
Expand Down Expand Up @@ -215,6 +216,24 @@ index sbs i
| i >= 0 && i < length sbs = unsafeIndex sbs i
| otherwise = indexError sbs i

-- | /O(1)/ 'ShortByteString' index, starting from 0, that returns 'Just' if:
--
-- > 0 <= n < length bs
--
-- @since 0.10.10.0
indexMaybe :: ShortByteString -> Int -> Maybe Word8
indexMaybe sbs i
| i >= 0 && i < length sbs = Just $ unsafeIndex sbs i
| otherwise = Nothing

-- | /O(1)/ 'ShortByteString' index, starting from 0, that returns 'Just' if:
--
-- > 0 <= n < length bs
--
-- @since 0.10.10.0
(!?) :: ShortByteString -> Int -> Maybe Word8
(!?) = indexMaybe

unsafeIndex :: ShortByteString -> Int -> Word8
unsafeIndex sbs = indexWord8Array (asBA sbs)

Expand Down

0 comments on commit d755b17

Please sign in to comment.