-- | Module for converting raw input data to SBytes
--
--   TODO: See if we can clean up the type conversion here
module Data.Tensort.Utils.Convert (rawToBytes) where

import Data.Tensort.Utils.Split (splitEvery)
import Data.Tensort.Utils.Types
  ( Bit,
    Byte,
    Record,
    SBytes (SBytesBit, SBytesRec),
    Sortable (..),
    TensortProps (..),
    fromSortBit,
    fromSortRec,
  )

-- | Convert a list of Bits to a list of Bytes of given bytesize, sorting
--   each byte with the given subalgorithm.

-- | ==== __Examples__
--   >>> import Data.Tensort.Subalgorithms.Bubblesort (bubblesort)
--   >>> import Data.Tensort.Utils.MkTsProps (mkTsProps)
--   >>> rawBitsToBytes (mkTsProps 4 bubblesort) [5,1,3,7,8,2,4,6]
--   [[2,4,6,8],[1,3,5,7]]
rawToBytes :: TensortProps -> Sortable -> SBytes
rawToBytes :: TensortProps -> Sortable -> SBytes
rawToBytes TensortProps
tsProps (SortBit [Bit]
xs) = [[Bit]] -> SBytes
SBytesBit (TensortProps -> [Bit] -> [[Bit]]
rawBitsToBytes TensortProps
tsProps [Bit]
xs)
rawToBytes TensortProps
tsProps (SortRec [Record]
xs) = [[Record]] -> SBytes
SBytesRec (TensortProps -> [Record] -> [[Record]]
rawRecsToBytes TensortProps
tsProps [Record]
xs)

rawBitsToBytes :: TensortProps -> [Bit] -> [Byte]
rawBitsToBytes :: TensortProps -> [Bit] -> [[Bit]]
rawBitsToBytes TensortProps
tsProps [Bit]
bits = ([Bit] -> [[Bit]] -> [[Bit]]) -> [[Bit]] -> [[Bit]] -> [[Bit]]
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr [Bit] -> [[Bit]] -> [[Bit]]
acc [] (Bit -> [Bit] -> [[Bit]]
forall a. Bit -> [a] -> [[a]]
splitEvery (TensortProps -> Bit
bytesize TensortProps
tsProps) [Bit]
bits)
  where
    acc :: [Bit] -> [Byte] -> [Byte]
    acc :: [Bit] -> [[Bit]] -> [[Bit]]
acc [Bit]
byte [[Bit]]
bytes =
      [[Bit]]
bytes [[Bit]] -> [[Bit]] -> [[Bit]]
forall a. [a] -> [a] -> [a]
++ [Sortable -> [Bit]
fromSortBit (TensortProps -> SortAlg
subAlgorithm TensortProps
tsProps ([Bit] -> Sortable
SortBit [Bit]
byte))]

rawRecsToBytes :: TensortProps -> [Record] -> [[Record]]
rawRecsToBytes :: TensortProps -> [Record] -> [[Record]]
rawRecsToBytes TensortProps
tsProps [Record]
recs = ([Record] -> [[Record]] -> [[Record]])
-> [[Record]] -> [[Record]] -> [[Record]]
forall a b. (a -> b -> b) -> b -> [a] -> b
forall (t :: * -> *) a b.
Foldable t =>
(a -> b -> b) -> b -> t a -> b
foldr [Record] -> [[Record]] -> [[Record]]
acc [] (Bit -> [Record] -> [[Record]]
forall a. Bit -> [a] -> [[a]]
splitEvery (TensortProps -> Bit
bytesize TensortProps
tsProps) [Record]
recs)
  where
    acc :: [Record] -> [[Record]] -> [[Record]]
    acc :: [Record] -> [[Record]] -> [[Record]]
acc [Record]
rbyte [[Record]]
rbytes =
      [[Record]]
rbytes [[Record]] -> [[Record]] -> [[Record]]
forall a. [a] -> [a] -> [a]
++ [Sortable -> [Record]
fromSortRec (TensortProps -> SortAlg
subAlgorithm TensortProps
tsProps ([Record] -> Sortable
SortRec [Record]
rbyte))]