[Haskell-cafe] dumping ByteArray#

Viktor Dukhovni ietf-dane at dukhovni.org
Sat Mar 29 02:54:45 UTC 2025


On Sat, Mar 29, 2025 at 01:38:18PM +1100, Viktor Dukhovni wrote:
> On Sat, Mar 29, 2025 at 11:25:17AM +0900, Kazu Yamamoto (山本和彦) via Haskell-Cafe wrote:
> 
> > For debugging, I need to dump the inside of `ByteArray#`.
> > Are there any utility functions for this purpose?
> 
> The `SBS` pattern in `Data.ByteString.Short.Internal` wraps up
> a `ByteArray#` as `ShortByteString`.
> 
>     $ ghci
>     GHCi, version 9.8.1: https://www.haskell.org/ghc/  :? for help
>     Loaded GHCi configuration from /home/viktor/.ghc/ghci.conf
>     λ> import Data.ByteString.Short.Internal
>     λ> :info SBS
>     pattern SBS :: GHC.Prim.ByteArray# -> ShortByteString
>             -- Defined in ‘Data.ByteString.Short.Internal’
>     λ>
> 
> What sort of "dump" did you have in mind?  A hexadecimal encoding?
> Something else?

Related combinators I've used at times (so `SBS` is also exported from
"Data.ByteString.Short", withour resort to ".Internal"):

    import qualified Data.Primitive.ByteArray as A
    import qualified Data.ByteString.Short as SB
    import Data.Array.Byte (ByteArray(..), MutableByteArray(..))
    import Data.ByteString.Short (ShortByteString(SBS))

    baToShortByteString :: ByteArray -> ShortByteString
    baToShortByteString (ByteArray ba) = SBS ba

    modifyArray :: MutableByteArray s -> Int -> (Word8 -> Word8) -> ST s ()
    modifyArray marr i f = A.readByteArray marr i >>= A.writeByteArray marr i . f

    sbsToByteArray :: ShortByteString -> ByteArray
    sbsToByteArray (SBS ba) = (ByteArray ba)

    sbsToMutableByteArray :: ShortByteString -> ST s (MutableByteArray s)
    sbsToMutableByteArray sb@(SBS ba) =
        A.thawByteArray (ByteArray ba) 0 (SB.length sb)

-- 
    Viktor.


More information about the Haskell-Cafe mailing list