{-# LANGUAGE CPP #-}

module Network.GRPC.Spec.Util.ByteString (
    ascii
  , strip
  ) where

import Data.ByteString qualified as BS.Strict
import Data.ByteString qualified as Strict (ByteString)
import Data.Char
import Data.Word
import GHC.Stack

ascii :: HasCallStack => Char -> Word8
ascii :: HasCallStack => Char -> Word8
ascii Char
c
  | Int
0 Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
x Bool -> Bool -> Bool
&& Int
x Int -> Int -> Bool
forall a. Ord a => a -> a -> Bool
<= Int
127 = Int -> Word8
forall a b. (Integral a, Num b) => a -> b
fromIntegral Int
x
  | Bool
otherwise          = [Char] -> Word8
forall a. HasCallStack => [Char] -> a
error ([Char] -> Word8) -> [Char] -> Word8
forall a b. (a -> b) -> a -> b
$ [Char]
"ascii: not an ASCII character " [Char] -> [Char] -> [Char]
forall a. [a] -> [a] -> [a]
++ Char -> [Char]
forall a. Show a => a -> [Char]
show Char
c
  where
    x :: Int
    x :: Int
x = Char -> Int
ord Char
c

strip :: Strict.ByteString -> Strict.ByteString
strip :: ByteString -> ByteString
strip =
      (Word8 -> Bool) -> ByteString -> ByteString
BS.Strict.dropWhileEnd Word8 -> Bool
isWhitespace
    (ByteString -> ByteString)
-> (ByteString -> ByteString) -> ByteString -> ByteString
forall b c a. (b -> c) -> (a -> b) -> a -> c
. (Word8 -> Bool) -> ByteString -> ByteString
BS.Strict.dropWhile    Word8 -> Bool
isWhitespace
  where
    isWhitespace :: Word8 -> Bool
    isWhitespace :: Word8 -> Bool
isWhitespace Word8
c = [Bool] -> Bool
forall (t :: * -> *). Foldable t => t Bool -> Bool
or [
          Word8
c Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== HasCallStack => Char -> Word8
Char -> Word8
ascii Char
' '
        , Word8
c Word8 -> Word8 -> Bool
forall a. Eq a => a -> a -> Bool
== HasCallStack => Char -> Word8
Char -> Word8
ascii Char
'\t'
        ]