sum 2 arrays of general int type - Mailing list pgsql-general

From Leonardo Francalanci
Subject sum 2 arrays of general int type
Date
Msg-id 416E801A.1060605@simtel.ie
Whole thread Raw
List pgsql-general
I wrote a function to sum arrays.
It works, but I had to cast the data pointer to int64 (because my arrays
are 'int8[]'):

int64* ptr1 = ARR_DATA_PTR(v1);

What if I want to write a more general function that adds values of 2
arrays of every int type? How could I do it?

Here is the function (if you find any errors tell me...):

PG_FUNCTION_INFO_V1(array_sum);

Datum
array_add(PG_FUNCTION_ARGS)
{
    Oid    element_type;
    ArrayType  *result, *v1, *v2;
    char       *dat1,  *dat2;
    int ndatabytes, ndims1, ndims2;



    v1 = PG_GETARG_ARRAYTYPE_P(0);
    v2 = PG_GETARG_ARRAYTYPE_P(1);
    ndims1 = ARR_NDIM(v1);
    ndims2 = ARR_NDIM(v2);
    dat1 = ARR_DATA_PTR(v1);
    dat2 = ARR_DATA_PTR(v2);
    int dim1 = ARR_DIMS(v1)[0];
    int dim2 = ARR_DIMS(v2)[0];
    int *lbs = ARR_LBOUND(v1);
    ndatabytes = ARR_SIZE(v1) - ARR_OVERHEAD(ndims1);


    int nbytes = ndatabytes + ARR_OVERHEAD(ndims1);

    result = (ArrayType *) palloc(nbytes);
    element_type = ARR_ELEMTYPE(v1);
    result->size = ARR_SIZE(v1);//nbytes;
    result->ndim = ARR_NDIM(v1);
    result->flags = 0;
    result->elemtype = element_type;
    memcpy(ARR_DIMS(result), &dim1, sizeof(int));
    memcpy(ARR_LBOUND(result), lbs, sizeof(int));
    int64* ptr = ARR_DATA_PTR(result);
    int64* ptr1 = ARR_DATA_PTR(v1);
    int64* ptr2 = ARR_DATA_PTR(v2);
    int i = 0;
    for (; i < dim1; i++)
    {
        ptr[i]=ptr1[i]+ptr2[i];
    }

    PG_RETURN_ARRAYTYPE_P(result);
}

pgsql-general by date:

Previous
From: Rodrigo Carvalhaes
Date:
Subject: IMPORT FROM CTREE to POSTGRESQL
Next
From: Michael Fuhr
Date:
Subject: Re: solaris and ps