summaryrefslogtreecommitdiff
path: root/src/bytearray-internal/Data/ByteArray.hs
blob: 3d2a0d105fbc241ce6299c4a14636e2eb347ee2a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
module Data.ByteArray (
    ByteArray(..),
    ByteArrayAccess(..),

    ScrubbedBytes,

    take,
    convert,
) where

import Prelude hiding (length, take)

import Control.Exception

import Data.Bits
import Data.ByteString (ByteString)
import Data.ByteString qualified as BS
import Data.ByteString.Internal qualified as BSI
import Data.ByteString.Unsafe qualified as BS
import Data.List (foldl')

import Foreign.ForeignPtr
import Foreign.Marshal.Alloc
import Foreign.Marshal.Utils
import Foreign.Ptr

import System.IO.Unsafe


class ByteArrayAccess ba where
    length :: ba -> Int
    withByteArray :: ba -> (Ptr p -> IO a) -> IO a

class (Eq ba, Ord ba, Monoid ba, ByteArrayAccess ba) => ByteArray ba where
    allocRet :: Int -> (Ptr p -> IO a) -> IO ( a, ba )


instance ByteArrayAccess BS.ByteString where
    length = BS.length
    withByteArray bs f = BS.unsafeUseAsCString bs (f . castPtr)

instance ByteArray BS.ByteString where
    allocRet len f = do
        fptr <- BSI.mallocByteString len
        x <- withForeignPtr fptr $ f . castPtr
        return ( x, BSI.fromForeignPtr fptr 0 len )


newtype ScrubbedBytes = ScrubbedBytes ByteString
    deriving (Ord, ByteArrayAccess)

instance Eq ScrubbedBytes where
    ScrubbedBytes a == ScrubbedBytes b =
        BS.length a == BS.length b && foldl' (.|.) 0 (BS.zipWith xor a b) == 0

instance Semigroup ScrubbedBytes where
    a <> b = unsafePerformIO $ fmap snd $ allocRet (la + lb) $ \dst -> do
        withByteArray a $ \src -> copyBytes dst src la
        withByteArray b $ \src -> copyBytes (dst `plusPtr` la) src lb
      where
        la = length a
        lb = length b

instance Monoid ScrubbedBytes where
    mempty = ScrubbedBytes BS.empty

instance ByteArray ScrubbedBytes where
    allocRet len f = mask $ \restore -> do
        ptr <- mallocBytes len
        let scrubAndFree = fillBytes ptr 0 len >> free ptr
        x <- restore (f $ castPtr ptr) `onException` scrubAndFree
        ( x, ) . ScrubbedBytes <$> BS.unsafePackCStringFinalizer ptr len scrubAndFree


take :: Int -> ScrubbedBytes -> ScrubbedBytes
take n (ScrubbedBytes bs) = ScrubbedBytes (BS.take n bs)

convert :: (ByteArrayAccess bin, ByteArray bout) => bin -> bout
convert ba = snd $ unsafePerformIO $ allocRet len $ \dst -> do
    withByteArray ba $ \src -> copyBytes dst src len
  where
    len = length ba