module Ecluse.Core.Server.Framing (
frameBytes,
putFrame,
frameComponents,
) where
import Control.Monad.ST (ST)
import Data.ByteString qualified as BS
import Data.ByteString.Builder (Builder, byteString, intDec)
import Data.ByteString.Builder.Extra (smallChunkSize, toLazyByteStringWith, untrimmedStrategy)
import Data.ByteString.Lazy qualified as LBS
import Ecluse.Core.Registry.Json.Scratch (Scratch, putByte, putDecimal)
frameBytes :: ByteString -> Builder
frameBytes :: ByteString -> Builder
frameBytes ByteString
bytes = Int -> Builder
intDec (ByteString -> Int
BS.length ByteString
bytes) Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> Builder
":" Builder -> Builder -> Builder
forall a. Semigroup a => a -> a -> a
<> ByteString -> Builder
byteString ByteString
bytes
putFrame :: Scratch st -> Int -> ST st () -> ST st ()
putFrame :: forall st. Scratch st -> Int -> ST st () -> ST st ()
putFrame Scratch st
scratch Int
len ST st ()
body = Scratch st -> Int -> ST st ()
forall st. Scratch st -> Int -> ST st ()
putDecimal Scratch st
scratch Int
len ST st () -> ST st () -> ST st ()
forall a b. ST st a -> ST st b -> ST st b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> Scratch st -> Word8 -> ST st ()
forall st. Scratch st -> Word8 -> ST st ()
putByte Scratch st
scratch Word8
0x3a ST st () -> ST st () -> ST st ()
forall a b. ST st a -> ST st b -> ST st b
forall (m :: * -> *) a b. Monad m => m a -> m b -> m b
>> ST st ()
body
frameComponents :: [Maybe ByteString] -> ByteString
frameComponents :: [Maybe ByteString] -> ByteString
frameComponents [Maybe ByteString]
components =
LazyByteString -> ByteString
LBS.toStrict (AllocationStrategy -> LazyByteString -> Builder -> LazyByteString
toLazyByteStringWith (Int -> Int -> AllocationStrategy
untrimmedStrategy Int
room Int
smallChunkSize) LazyByteString
LBS.empty Builder
frames)
where
frames :: Builder
frames = (Maybe ByteString -> Builder) -> [Maybe ByteString] -> Builder
forall m a. Monoid m => (a -> m) -> [a] -> m
forall (t :: * -> *) m a.
(Foldable t, Monoid m) =>
(a -> m) -> t a -> m
foldMap (Builder -> (ByteString -> Builder) -> Maybe ByteString -> Builder
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Builder
"-" ByteString -> Builder
frameBytes) [Maybe ByteString]
components
room :: Int
room = [Int] -> Int
forall a (f :: * -> *). (Foldable f, Num a) => f a -> a
sum ((Maybe ByteString -> Int) -> [Maybe ByteString] -> [Int]
forall a b. (a -> b) -> [a] -> [b]
map (Int -> (ByteString -> Int) -> Maybe ByteString -> Int
forall b a. b -> (a -> b) -> Maybe a -> b
maybe Int
4 ((Int -> Int -> Int
forall a. Num a => a -> a -> a
+ Int
21) (Int -> Int) -> (ByteString -> Int) -> ByteString -> Int
forall b c a. (b -> c) -> (a -> b) -> a -> c
. ByteString -> Int
BS.length)) [Maybe ByteString]
components)