packages feed

mldsa-0.1.1.0: src/Endian.hs

-- |
-- Module      : Endian
-- License     : BSD-3-Clause
-- Copyright   : (c) 2026 Olivier Chéron
--
-- Endianness utilities
--
{-# LANGUAGE CPP #-}
module Endian
    ( B.BE, ByteSwap, B.LE, fromLE, toBE, toLE
    ) where

#include "MachDeps.h"

-- Little-endian conversion in `memory` / `ram` is avoided at compile
-- time only for AMD/Intel, here we will short circuit on ARM too
#if (defined(arm_HOST_ARCH) || defined(aarch64_HOST_ARCH)) \
    && !defined(WORDS_BIGENDIAN)
#define MLDSA_FORCE_LITTLE_ENDIAN_ARCH 1
#endif

#ifdef MLDSA_FORCE_LITTLE_ENDIAN_ARCH
import Data.Word
#else
import Data.Memory.Endian (ByteSwap)
#endif

import qualified Data.Memory.Endian as B

#ifdef MLDSA_FORCE_LITTLE_ENDIAN_ARCH
class ByteSwap a where
    byteSwap :: a -> a
instance ByteSwap Word16 where
    byteSwap = byteSwap16
#endif

#ifdef MLDSA_FORCE_LITTLE_ENDIAN_ARCH
fromLE :: B.LE a -> a
fromLE = B.unLE  -- unwrap constructor with no byte swapping
#else
fromLE :: ByteSwap a => B.LE a -> a
fromLE = B.fromLE  -- byte swap if necessary
#endif

#ifdef MLDSA_FORCE_LITTLE_ENDIAN_ARCH
toLE :: a -> B.LE a
toLE = B.LE  -- wrap constructor with no byte swapping
#else
toLE :: ByteSwap a => a -> B.LE a
toLE = B.toLE  -- byte swap if necessary
#endif

toBE :: ByteSwap a => a -> B.BE a
#ifdef MLDSA_FORCE_LITTLE_ENDIAN_ARCH
toBE = B.BE . byteSwap  -- always byte swap
#else
toBE = B.toBE  -- byte swap if necessary
#endif