packages feed

papa-0.7.0: src/Papa/Internal/Read.hs

{-# LANGUAGE NoImplicitPrelude #-}
{-# OPTIONS_GHC -Wall #-}

-- | The shared parts of the strict and lazy number readers.
module Papa.Internal.Read (
  fits,
  signedWith,
  leading,
) where

import Control.Monad ((>>=))
import Data.Bifunctor (first)
import Data.Bits (Bits, toIntegralSized)
import Data.Bool (Bool (False), bool)
import Data.Char (Char)
import Data.Either (Either (Left, Right))
import Data.Eq ((==))
import Data.Functor (fmap)
import Data.Maybe (Maybe, maybe)
import Data.String (String)
import Prelude (Integer, Integral, negate)

-- | A number read as an 'Integer', at a type that holds it; an error where
-- it does not fit.
fits :: (Integral a, Bits a) => Either String (Integer, t) -> Either String (a, t)
fits r =
  r >>= \(n, rest) -> maybe (Left "number out of range") (\a -> Right (a, rest)) (toIntegralSized n)
{-# INLINE fits #-}

-- | Read an optional @+@ or @-@, then a number, negated after a @-@.
signedWith :: (t -> Maybe (Char, t)) -> (t -> Either String (Integer, t)) -> t -> Either String (Integer, t)
signedWith uncons r t =
  maybe
    (r t)
    ( \(c, t') ->
        bool
          (bool (r t) (r t') (c == '+'))
          (fmap (first negate) (r t'))
          (c == '-')
    )
    (uncons t)
{-# INLINE signedWith #-}

-- | A reader's result, or an error where the text does not start with a
-- character that the reader reads.
leading :: (t -> Maybe (Char, t)) -> (Char -> Bool) -> String -> t -> Either String a -> Either String a
leading uncons p message t r =
  bool (Left message) r (maybe False (\(c, _) -> p c) (uncons t))
{-# INLINE leading #-}