Skip to content

Commit f559846

Browse files
committed
Fix longstanding error in contrib/intarray's int[] & int[] operator.
The array intersection code would give wrong results if the first entry of the correct output array would be "1". (I think only this value could be at risk, since the previous word would always be a lower-bound entry with that fixed value.) Problem spotted by Julien Rouhaud, initial patch by Guillaume Lelarge, cosmetic improvements by me.
1 parent ebc37d6 commit f559846

File tree

3 files changed

+16
-6
lines changed

3 files changed

+16
-6
lines changed

contrib/intarray/_int_tool.c

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -146,7 +146,8 @@ inner_int_inter(ArrayType *a, ArrayType *b)
146146
*db,
147147
*dr;
148148
int i,
149-
j;
149+
j,
150+
k;
150151

151152
CHECKARRVALID(a);
152153
CHECKARRVALID(b);
@@ -161,27 +162,29 @@ inner_int_inter(ArrayType *a, ArrayType *b)
161162
r = new_intArrayType(Min(na, nb));
162163
dr = ARRPTR(r);
163164

164-
i = j = 0;
165+
i = j = k = 0;
165166
while (i < na && j < nb)
167+
{
166168
if (da[i] < db[j])
167169
i++;
168170
else if (da[i] == db[j])
169171
{
170-
if (i + j == 0 || (i + j > 0 && *(dr - 1) != db[j]))
171-
*dr++ = db[j];
172+
if (k == 0 || dr[k - 1] != db[j])
173+
dr[k++] = db[j];
172174
i++;
173175
j++;
174176
}
175177
else
176178
j++;
179+
}
177180

178-
if ((dr - ARRPTR(r)) == 0)
181+
if (k == 0)
179182
{
180183
pfree(r);
181184
return new_intArrayType(0);
182185
}
183186
else
184-
return resize_intArrayType(r, dr - ARRPTR(r));
187+
return resize_intArrayType(r, k);
185188
}
186189

187190
void

contrib/intarray/expected/_int.out

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -143,6 +143,12 @@ SELECT '{123,623,445}'::int[] & '{1623,623}';
143143
{623}
144144
(1 row)
145145

146+
SELECT '{-1,3,1}'::int[] & '{1,2}';
147+
?column?
148+
----------
149+
{1}
150+
(1 row)
151+
146152
--test query_int
147153
SELECT '1'::query_int;
148154
query_int

contrib/intarray/sql/_int.sql

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@ SELECT '{123,623,445}'::int[] | 623;
3232
SELECT '{123,623,445}'::int[] | 1623;
3333
SELECT '{123,623,445}'::int[] | '{1623,623}';
3434
SELECT '{123,623,445}'::int[] & '{1623,623}';
35+
SELECT '{-1,3,1}'::int[] & '{1,2}';
3536

3637

3738
--test query_int

0 commit comments

Comments
 (0)