sum 2 arrays of general int type

From: Leonardo Francalanci <lfrancalanci(at)simtel(dot)ie>
To: postgresql <pgsql-general(at)postgresql(dot)org>
Subject: sum 2 arrays of general int type
Date: 2004-10-14 13:33:14
Message-ID: 416E801A.1060605@simtel.ie
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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);
}

Browse pgsql-general by date

  From Date Subject
Next Message Michael Fuhr 2004-10-14 14:24:19 Re: solaris and ps
Previous Message Rodrigo Carvalhaes 2004-10-14 13:21:42 IMPORT FROM CTREE to POSTGRESQL