packages feed

futhark-0.24.2: rts/python/memory.py

# Start of memory.py.

import ctypes as ct


def addressOffset(x, offset, bt):
    return ct.cast(ct.addressof(x.contents) + int(offset), ct.POINTER(bt))


def allocateMem(size):
    return ct.cast((ct.c_byte * max(0, size))(), ct.POINTER(ct.c_byte))


# Copy an array if its is not-None.  This is important for treating
# Numpy arrays as flat memory, but has some overhead.
def normaliseArray(x):
    if (x.base is x) or (x.base is None):
        return x
    else:
        return x.copy()


def unwrapArray(x):
    return normaliseArray(x).ctypes.data_as(ct.POINTER(ct.c_byte))


def createArray(x, shape, t):
    # HACK: np.ctypeslib.as_array may fail if the shape contains zeroes,
    # for some reason.
    if any(map(lambda x: x == 0, shape)):
        return np.ndarray(shape, dtype=t)
    else:
        return np.ctypeslib.as_array(x, shape=shape).view(t)


def indexArray(x, offset, bt):
    return addressOffset(x, offset * ct.sizeof(bt), bt)[0]


def writeScalarArray(x, offset, v):
    ct.memmove(
        ct.addressof(x.contents) + int(offset) * ct.sizeof(v),
        ct.addressof(v),
        ct.sizeof(v),
    )


# An opaque Futhark value.
class opaque(object):
    def __init__(self, desc, *payload):
        self.data = payload
        self.desc = desc

    def __repr__(self):
        return "<opaque Futhark value of type {}>".format(self.desc)


# End of memory.py.