module CPython.Types.Bytes
( Bytes
, bytesType
, toBytes
, fromBytes
, fromObject
, length
, append
) where
import Prelude hiding (length)
import qualified Data.ByteString as B
import qualified Data.ByteString.Unsafe as B
import CPython.Internal
newtype Bytes = Bytes (ForeignPtr Bytes)
instance Object Bytes where
toObject (Bytes x) = SomeObject x
fromForeignPtr = Bytes
instance Concrete Bytes where
concreteType _ = bytesType
bytesType :: Type
bytesType =
unsafePerformIO $
let {res = bytesType'_} in
peekStaticObject res >>= \res' ->
return (res')
toBytes :: B.ByteString -> IO Bytes
toBytes bytes = let
mkBytes = pyBytesFromStringAndSize
in B.unsafeUseAsCStringLen bytes $ \(cstr, len) ->
stealObject =<< mkBytes cstr (fromIntegral len)
fromBytes :: Bytes -> IO B.ByteString
fromBytes py =
alloca $ \bytesPtr ->
alloca $ \lenPtr ->
withObject py $ \pyPtr -> do
pyBytesAsStringAndSize pyPtr bytesPtr lenPtr
>>= checkStatusCode
bytes <- peek bytesPtr
len <- peek lenPtr
B.packCStringLen (bytes, fromIntegral len)
fromObject :: Object self => self -> IO (Bytes)
fromObject a1 =
withObject a1 $ \a1' ->
fromObject'_ a1' >>= \res ->
stealObject res >>= \res' ->
return (res')
length :: Bytes -> IO (Integer)
length a1 =
withObject a1 $ \a1' ->
length'_ a1' >>= \res ->
checkIntReturn res >>= \res' ->
return (res')
append :: Bytes -> Bytes -> IO Bytes
append self next =
alloca $ \tempPtr ->
withObject self $ \selfPtr -> do
incref selfPtr
poke tempPtr selfPtr
withObject next $ \nextPtr -> do
pyBytesConcat tempPtr nextPtr
newSelf <- peek tempPtr
stealObject newSelf
foreign import ccall unsafe "CPython/Types/Bytes.chs.h hscpython_PyBytes_Type"
bytesType'_ :: (Ptr ())
foreign import ccall safe "CPython/Types/Bytes.chs.h PyBytes_FromStringAndSize"
pyBytesFromStringAndSize :: ((Ptr CChar) -> (CInt -> (IO (Ptr ()))))
foreign import ccall safe "CPython/Types/Bytes.chs.h PyBytes_AsStringAndSize"
pyBytesAsStringAndSize :: ((Ptr ()) -> ((Ptr (Ptr CChar)) -> ((Ptr CInt) -> (IO CInt))))
foreign import ccall safe "CPython/Types/Bytes.chs.h PyBytes_FromObject"
fromObject'_ :: ((Ptr ()) -> (IO (Ptr ())))
foreign import ccall safe "CPython/Types/Bytes.chs.h PyBytes_Size"
length'_ :: ((Ptr ()) -> (IO CInt))
foreign import ccall safe "CPython/Types/Bytes.chs.h PyBytes_Concat"
pyBytesConcat :: ((Ptr (Ptr ())) -> ((Ptr ()) -> (IO ())))