File: ip4r.c

package info (click to toggle)
ip4r 1.03-2
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 140 kB
  • ctags: 232
  • sloc: ansic: 1,411; makefile: 51
file content (1897 lines) | stat: -rw-r--r-- 45,319 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
/* $Id: ip4r.c,v 1.8 2008/01/28 23:18:35 andrewsn Exp $ */
/*
  New type 'ip4' used to represent a single IPv4 address efficiently

  New type 'ip4r' used to represent a range of IPv4 addresses, along
  with support for GiST and rtree indexing of the type.

  V1.03: fix the inet conversions which were not handling short varlenas
  correctly on 8.3

  V1.02: updates for 8.3

  V1.01: updates for 8.2

  V0.1: updates for 8.1. add some documentation and new functions.
  WARNING: semantics of &<< and &>> changed to track changes in rtree.

  V0.08: SQL changes only; functions returning "internal" must take
  at least one parameter of type "internal".

  V0.07: fix GIST interfaces for 8.0.

  V0.06: make everything 8.0-friendly. For no clear reason the inet
  type renamed some struct elements between 7.4 and 8.0, so the casts
  between ip4 and inet break. Steve Atkins <steve@blighty.com>

  V0.05: mess with operators a bit. clean up error handling. Hopefully,
  this should freeze the visible interface for the forseeable future.

  V0.04: change semantics of &<< and &>> to match rtree requirements

  V0.03: new gist picksplit function based on code from rtree_gist,
  which seems much better than the previous seg-based version. Changed
  the cost metric back so that ip4r_size returns the actual number of
  IPs in the range.

  V0.02: added rtree, changed some cost metrics. The gist code is
  broken somehow; the resulting indexes are bloated with excessive
  numbers of single-value leaf pages.

  this code by andrew@supernews.net Oct 2004 - Dec 2005

  [derived from 'ipr' by:  
   Steve Atkins <steve@blighty.com> August 2003, derived from the 'seg'
   type distributed with PostgreSQL.]

  Distributed under the same terms as PostgreSQL itself.
*/

/******************************************************************************
  This file contains routines that can be bound to a Postgres backend and
  called by the backend in the process of processing queries.  The calling
  format for these routines is dictated by Postgres architecture.
******************************************************************************/

#include <stdio.h>
#include "postgres.h"

#include "access/gist.h"
#include "access/skey.h"
#include "access/hash.h"
#include "libpq/pqformat.h"
#include "utils/elog.h"
#include "utils/palloc.h"
#include "utils/builtins.h"
#include "utils/inet.h"
#include <sys/socket.h>
#include <math.h>

/* IP4 = uint32, stored in host-order. fixed-length and pass by value. */
typedef uint32 IP4;

/* IP4R = range of IP4, stored in host-order. fixed-length by reference */
typedef struct IP4R {
    IP4 lower;
    IP4 upper;
} IP4R;

/**************************************************************************/
/* This part is the internal implementation of all functionality, with no
 * reference to the interface with postgres. That part comes later and is
 * implemented in terms of these functions.
 */

static inline
uint32 hostmask(unsigned masklen)
{
    return (masklen) ? ( (((uint32)(1U)) << (32-masklen)) - 1U ) : 0xFFFFFFFFU;
}

static inline
uint32 netmask(unsigned masklen)
{
    return ~hostmask(masklen);
}

/* if LO and HI are ends of a CIDR prefix, return the mask length.
 * If not, returns ~0.
 */

static inline
unsigned masklen(uint32 lo, uint32 hi)
{
    uint32 d = (lo ^ hi) + 1;
    /* at this point, d can be:
     *  0 if A and B have all bits different
     *  1 if A and B are equal
     *  1 << (32-masklen)
     *  some other value if A and B are not ends of a CIDR range
     * but in any case, after extracting the masklen, we have to
     * recheck because some non-CIDR ranges will produce the same
     * results.
     */
    int fbit = ffs(d);
    switch (fbit)
    {
	case 0: return (lo == 0 && hi == ~0) ? 0 : ~0;
	case 1: return (lo == hi) ? 32 : ~0;
	default:
	    if ( ((uint32)(1U) << (fbit-1)) == d )
	    {
		uint32 mask = hostmask(33-fbit);
		if ((lo & mask) == 0 && (hi & mask) == mask)
		    return 33-fbit;
	    }
	    return ~0;
    }
}

static inline
bool ip4_valid_netmask(uint32 mask)
{
    uint32 d = ~mask + 1;
    /* at this point, d can be:
     *  0 if mask was 0x00000000 (valid)
     *  1 << (32-masklen)   (valid)
     *  some other value  (invalid)
     */
    int fbit = ffs(d);
    switch (fbit)
    {
	case 0:
	    return true;
	default:
	    return ( ((uint32)(1U) << (fbit-1)) == d );
    }
}


/* extract an IP from text. Don't try and use inet_addr/inet_aton, because
 * they often support too many bogus historical formats (octal or hex,
 * classful addresses with less than three dots, etc.)
 */
static inline
bool ip4_from_str(char *str, IP4 *ip)
{
    unsigned a,b,c,d;
    char dummy;
    if (sscanf(str, "%u.%u.%u.%u%c", &a,&b,&c,&d, &dummy) == 4
	&& (a|b|c|d) < 256)
    {
	*ip = (a << 24) | (b << 16) | (c << 8) | d;
	return TRUE;
    }
    return FALSE;
}

/* Output an ip in text form
 */
static inline
int ip4_to_str(IP4 ip, char *str, int slen)
{
    return snprintf(str, slen, "%u.%u.%u.%u",
		    (ip >> 24)&0xff, (ip >> 16)&0xff, (ip >> 8)&0xff, (ip)&0xff);
}

static inline
bool ip4r_from_cidr(IP4 prefix, unsigned masklen, IP4R *ipr)
{
    uint32 mask = hostmask(masklen);
    if (masklen > 32)
	return FALSE;
    if (prefix & mask)
	return FALSE;
    ipr->lower = prefix;
    ipr->upper = prefix | mask;
    return TRUE;
}

static inline
bool ip4r_from_inet(IP4 addr, unsigned masklen, IP4R *ipr)
{
    uint32 mask = hostmask(masklen);
    if (masklen > 32)
	return FALSE;
    ipr->lower = addr & ~mask;
    ipr->upper = addr | mask;
    return TRUE;
}


/* extract an IP range from text.
 */
static
bool ip4r_from_str(char *str, IP4R *ipr)
{
    unsigned a,b,c,d;
    unsigned a2,b2,c2,d2;
    char dummy;
    if (sscanf(str, "%u.%u.%u.%u-%u.%u.%u.%u%c", &a,&b,&c,&d, &a2,&b2,&c2,&d2, &dummy) == 8
	&& (a|b|c|d|a2|b2|c2|d2) < 256)
    {
	IP4 l = (a << 24) | (b << 16) | (c << 8) | d;
	IP4 h = (a2 << 24) | (b2 << 16) | (c2 << 8) | d2;
	if (l > h)
	    ipr->lower = h, ipr->upper = l;
	else
	    ipr->lower = l, ipr->upper = h;
	return TRUE;
    }
    else if (sscanf(str, "%u.%u.%u.%u/%u%c", &a,&b,&c,&d, &a2, &dummy) == 5
	&& (a|b|c|d) < 256 && a2 <= 32)
    {
	IP4 pfx = (a << 24) | (b << 16) | (c << 8) | d;
	return ip4r_from_cidr(pfx, a2, ipr);
    }
    else if (sscanf(str, "%u.%u.%u.%u%c", &a,&b,&c,&d, &dummy) == 4
	&& (a|b|c|d) < 256)
    {
	ipr->lower = ipr->upper = (a << 24) | (b << 16) | (c << 8) | d;
	return TRUE;
    }
    return FALSE;
}

/* Output an ip range in text form
 */
static inline
int ip4r_to_str(IP4R *ipr, char *str, int slen)
{
    IP4 lo = ipr->lower;
    IP4 hi = ipr->upper;
    unsigned msk;
    if (lo == hi)
	return ip4_to_str(lo, str, slen);
    if ((msk = masklen(lo,hi)) <= 32)
	return snprintf(str, slen, "%u.%u.%u.%u/%u",
			(lo >> 24)&0xff, (lo >> 16)&0xff, (lo >> 8)&0xff, (lo)&0xff, msk);
    return snprintf(str, slen, "%u.%u.%u.%u-%u.%u.%u.%u",
		    (lo >> 24)&0xff, (lo >> 16)&0xff, (lo >> 8)&0xff, (lo)&0xff,
		    (hi >> 24)&0xff, (hi >> 16)&0xff, (hi >> 8)&0xff, (hi)&0xff);
}

/* helpers for union/intersection for indexing */

static inline
IP4R *ip4r_union_internal(IP4R *a, IP4R *b, IP4R *result)
{
    if (a->lower < b->lower)
	result->lower = a->lower;
    else
	result->lower = b->lower;

    if (a->upper > b->upper)
	result->upper = a->upper;
    else
	result->upper = b->upper;

    return result;
}

static inline
IP4R *ip4r_inter_internal(IP4R *a, IP4R *b, IP4R *result)
{
    if (a->upper < b->lower || a->lower > b->upper)
    {
	/* disjoint */
	result->lower = 1;
	result->upper = 0;  /* INVALID VALUE */
	return NULL;
    }

    if (a->upper < b->upper)
	result->upper = a->upper;
    else
	result->upper = b->upper;

    if (a->lower > b->lower)
	result->lower = a->lower;
    else
	result->lower = b->lower;

    return result;
}

static inline
double ip4r_metric(IP4R *v)
{
    if (!v)
	return 0.0;
    return ((v->upper - v->lower) + 1.0);
}

/* comparisons */

static inline
bool ip4_equal(IP4 a, IP4 b)
{
    return (a == b);
}

static inline
bool ip4_lessthan(IP4 a, IP4 b)
{
    return (a < b);
}

static inline
bool ip4_less_eq(IP4 a, IP4 b)
{
    return (a <= b);
}

static inline
bool ip4r_equal(IP4R *a, IP4R *b)
{
    return (a->lower == b->lower && a->upper == b->upper);
}

static inline
bool ip4r_lessthan(IP4R *a, IP4R *b)
{
    return (a->lower == b->lower) ? (a->upper < b->upper) : (a->lower < b->lower);
}

static inline
bool ip4r_less_eq(IP4R *a, IP4R *b)
{
    return (a->lower == b->lower) ? (a->upper <= b->upper) : (a->lower < b->lower);
}

static inline
bool ip4r_contains_internal(IP4R *left, IP4R *right, bool eqval)
{
    if (ip4r_equal(left,right))
	return eqval;
    return ((left->lower <= right->lower) && (left->upper >= right->upper));
}

static inline
bool ip4r_overlaps_internal(IP4R *left, IP4R *right)
{
    return (left->upper >= right->lower && left->lower <= right->upper);
}

static inline
bool ip4_contains_internal(IP4R *left, IP4 right)
{
    return (left->lower <= right && left->upper >= right);
}

static inline
bool ip4r_left_internal(IP4R *left, IP4R *right)
{
    return (left->upper < right->lower);
}

static inline
bool ip4r_extends_left_of_internal(IP4R *left, IP4R *right)
{
    return (left->lower < right->lower);
}

static inline
bool ip4r_extends_right_of_internal(IP4R *left, IP4R *right)
{
    return (left->upper > right->upper);
}



/**************************************************************************/
/* This part handles all aspects of postgres interfacing.
 */

#define DatumGetIP4RP(X)	((IP4R *) DatumGetPointer(X))
#define IP4RPGetDatum(X)	PointerGetDatum(X)
#define PG_GETARG_IP4R_P(n) DatumGetIP4RP(PG_GETARG_DATUM(n))
#define PG_RETURN_IP4R_P(x) return IP4RPGetDatum(x)

#define PG_GETARG_IP4(n) PG_GETARG_UINT32(n)
#define PG_RETURN_IP4(x) PG_RETURN_UINT32(x)

/* PG version dependencies */

#if !defined(IP4R_PGVER) || IP4R_PGVER >= 9000000 || IP4R_PGVER < 7003000
#error "Unknown or unsupported postgresql version"
#endif

/* 8.3 changes the varlena header (to support "short" varlenas without
 * needing a full 32-bit length field) and changes the varlena macros
 * to support this. Keep the new interface (which is cleaner than the
 * old one anyway) and emulate it for older versions.
 *
 * But for the "inet" type, unlike all other types, 8.3 does not convert
 * the packed short format back to the unpacked format in the normal
 * parameter macros. So we need additional macros to hide that change.
 * We implicitly assume here that none of the fields of 'inet_struct'
 * require any alignment stricter than byte (which is true at the moment,
 * but it's anyone's guess whether it will stay true, given how often it
 * seems to get changed).
 */

#if IP4R_PGVER >= 8003000

#define INET_STRUCT_DATA(is_) ((inet_struct *)VARDATA_ANY(is_))

#else /* IP4R_PGVER < 8003000 */

#define SET_VARSIZE(var_,val_) VARATT_SIZEP(var_) = (val_)

#define INET_STRUCT_DATA(is_) ((inet_struct *)VARDATA(is_))

#endif

/* PG_MODULE_MAGIC was introduced in 8.2. */

#if IP4R_PGVER >= 8002000
PG_MODULE_MAGIC;
#endif

/* The "inet" type representation lost its "type" field in 8.2 - it was
 * always redundant
 */

#if IP4R_PGVER >= 8002000

#define INET_INIT_CIDR(i)
#define INET_IS_CIDR(i) (1)

#else /* IP4R_PGVER < 8002000 */

#define INET_INIT_CIDR(i) ((i)->type = 1)
#define INET_IS_CIDR(i) ((i)->type)

#endif

/* The semantics of the rtree opclass operators changed in 8.1. Since we
 * don't really consider our &<< and &>> operators as useful except for
 * internal use with rtree, we make our operators change in semantics to
 * match what rtree expects.
 * This becomes academic for 8.2 on since rtree no longer exists, but we
 * stick with the 8.1 semantics.
 */

#if IP4R_PGVER >= 8001000

#define IP4R_LEFT_OVERLAP_OP(a,b) (! ip4r_extends_right_of_internal((a),(b)))
#define IP4R_RIGHT_OVERLAP_OP(a,b) (! ip4r_extends_left_of_internal((a),(b)))

#else

#define IP4R_LEFT_OVERLAP_OP(a,b) (ip4r_extends_left_of_internal((a),(b)))
#define IP4R_RIGHT_OVERLAP_OP(a,b) (ip4r_extends_right_of_internal((a),(b)))

#endif

/* The data structure name for the internal representation of "inet"
 * was changed in 8.0 for no readily apparent reason.
 */

#if IP4R_PGVER >= 8000000

#define INET_IPADDR ipaddr

#else /* IP4R_PGVER < 8000000 */

#define INET_IPADDR ip_addr

#endif

/* The interface to GiST was improved in 8.0, with a new structure for
 * GiST entry vectors rather than passing them as bytea. Hide the change
 * behind some macros.
 */

#if IP4R_PGVER >= 8000000

#define GISTENTRYCOUNT(v) ((v)->n)
#define GISTENTRYVEC(v) ((v)->vector)

#else /* IP4R_PGVER < 8000000 */

typedef bytea GistEntryVector;
#define GISTENTRYCOUNT(v) ( (VARSIZE((v)) - VARHDRSZ) / sizeof(GISTENTRY) )
#define GISTENTRYVEC(v) ((GISTENTRY *) VARDATA(entryvec))

#endif

/* end of version dependencies */

Datum ip4_in(PG_FUNCTION_ARGS);
Datum ip4_out(PG_FUNCTION_ARGS);
Datum ip4_recv(PG_FUNCTION_ARGS);
Datum ip4_send(PG_FUNCTION_ARGS);
Datum ip4hash(PG_FUNCTION_ARGS);
Datum ip4_cast_to_text(PG_FUNCTION_ARGS);
Datum ip4_cast_from_text(PG_FUNCTION_ARGS);
Datum ip4_cast_from_inet(PG_FUNCTION_ARGS);
Datum ip4_cast_to_cidr(PG_FUNCTION_ARGS);
Datum ip4_cast_to_bigint(PG_FUNCTION_ARGS);
Datum ip4_cast_from_bigint(PG_FUNCTION_ARGS);
Datum ip4_cast_to_double(PG_FUNCTION_ARGS);
Datum ip4_cast_from_double(PG_FUNCTION_ARGS);
Datum ip4r_in(PG_FUNCTION_ARGS);
Datum ip4r_out(PG_FUNCTION_ARGS);
Datum ip4r_recv(PG_FUNCTION_ARGS);
Datum ip4r_send(PG_FUNCTION_ARGS);
Datum ip4rhash(PG_FUNCTION_ARGS);
Datum ip4r_cast_to_text(PG_FUNCTION_ARGS);
Datum ip4r_cast_from_text(PG_FUNCTION_ARGS);
Datum ip4r_cast_from_cidr(PG_FUNCTION_ARGS);
Datum ip4r_cast_to_cidr(PG_FUNCTION_ARGS);
Datum ip4r_cast_from_ip4(PG_FUNCTION_ARGS);
Datum ip4r_from_ip4s(PG_FUNCTION_ARGS);
Datum ip4r_net_prefix(PG_FUNCTION_ARGS);
Datum ip4r_net_mask(PG_FUNCTION_ARGS);
Datum ip4r_lower(PG_FUNCTION_ARGS);
Datum ip4r_upper(PG_FUNCTION_ARGS);
Datum ip4r_is_cidr(PG_FUNCTION_ARGS);
Datum ip4_netmask(PG_FUNCTION_ARGS);
Datum ip4_net_lower(PG_FUNCTION_ARGS);
Datum ip4_net_upper(PG_FUNCTION_ARGS);
Datum ip4_plus_int(PG_FUNCTION_ARGS);
Datum ip4_plus_bigint(PG_FUNCTION_ARGS);
Datum ip4_minus_int(PG_FUNCTION_ARGS);
Datum ip4_minus_bigint(PG_FUNCTION_ARGS);
Datum ip4_minus_ip4(PG_FUNCTION_ARGS);
Datum ip4_and(PG_FUNCTION_ARGS);
Datum ip4_or(PG_FUNCTION_ARGS);
Datum ip4_xor(PG_FUNCTION_ARGS);
Datum ip4_not(PG_FUNCTION_ARGS);
Datum ip4_lt(PG_FUNCTION_ARGS);
Datum ip4_le(PG_FUNCTION_ARGS);
Datum ip4_gt(PG_FUNCTION_ARGS);
Datum ip4_ge(PG_FUNCTION_ARGS);
Datum ip4_eq(PG_FUNCTION_ARGS);
Datum ip4_neq(PG_FUNCTION_ARGS);
Datum ip4r_lt(PG_FUNCTION_ARGS);
Datum ip4r_le(PG_FUNCTION_ARGS);
Datum ip4r_gt(PG_FUNCTION_ARGS);
Datum ip4r_ge(PG_FUNCTION_ARGS);
Datum ip4r_eq(PG_FUNCTION_ARGS);
Datum ip4r_neq(PG_FUNCTION_ARGS);
Datum ip4r_overlaps(PG_FUNCTION_ARGS);
Datum ip4r_contains(PG_FUNCTION_ARGS);
Datum ip4r_contains_strict(PG_FUNCTION_ARGS);
Datum ip4r_contained_by(PG_FUNCTION_ARGS);
Datum ip4r_contained_by_strict(PG_FUNCTION_ARGS);
Datum ip4_contains(PG_FUNCTION_ARGS);
Datum ip4_contained_by(PG_FUNCTION_ARGS);
Datum ip4r_union(PG_FUNCTION_ARGS);
Datum ip4r_inter(PG_FUNCTION_ARGS);
Datum ip4r_size(PG_FUNCTION_ARGS);
Datum ip4r_cmp(PG_FUNCTION_ARGS);
Datum ip4_cmp(PG_FUNCTION_ARGS);
Datum ip4r_left_of(PG_FUNCTION_ARGS);
Datum ip4r_left_overlap(PG_FUNCTION_ARGS);
Datum ip4r_right_of(PG_FUNCTION_ARGS);
Datum ip4r_right_overlap(PG_FUNCTION_ARGS);

/*
#define GIST_DEBUG
#define GIST_QUERY_DEBUG
*/

static
text *
make_text(char *str, int len)
{
    text *ret = (text *) palloc(len + VARHDRSZ);
    SET_VARSIZE(ret, len + VARHDRSZ);
    if (str)
	memcpy(VARDATA(ret), str, len);
    else
	memset(VARDATA(ret), 0, len);
    return ret;
}

static inline
void
set_text_len(text *txt, int len)
{
    if ((len + VARHDRSZ) < VARSIZE(txt))
      SET_VARSIZE(txt, len + VARHDRSZ);
}

static inline
int
get_text_len(text *txt)
{
    return VARSIZE(txt) - VARHDRSZ;
}

/*
** Input/Output routines
*/

PG_FUNCTION_INFO_V1(ip4_in);
Datum
ip4_in(PG_FUNCTION_ARGS)
{
    char *str = PG_GETARG_CSTRING(0);
    IP4 ip;
    if (ip4_from_str(str, &ip))
	PG_RETURN_IP4(ip);

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid IP4 value: '%s'", str)));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4_out);
Datum
ip4_out(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    char *out = palloc(32);
    ip4_to_str(ip, out, 32);
    PG_RETURN_CSTRING(out);
}

PG_FUNCTION_INFO_V1(ip4_recv);
Datum
ip4_recv(PG_FUNCTION_ARGS)
{
    StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
    PG_RETURN_IP4((IP4) pq_getmsgint(buf, sizeof(IP4)));
}

PG_FUNCTION_INFO_V1(ip4_send);
Datum
ip4_send(PG_FUNCTION_ARGS)
{
    IP4 arg1 = PG_GETARG_IP4(0);
    StringInfoData buf;

    pq_begintypsend(&buf);
    pq_sendint(&buf, arg1, sizeof(IP4));
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

PG_FUNCTION_INFO_V1(ip4hash);
Datum
ip4hash(PG_FUNCTION_ARGS)
{
    IP4 arg1 = PG_GETARG_IP4(0);

    return hash_any((unsigned char *)&arg1, sizeof(IP4));
}

PG_FUNCTION_INFO_V1(ip4_cast_to_text);
Datum
ip4_cast_to_text(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    text *out = make_text(NULL,32);
    set_text_len(out, ip4_to_str(ip, VARDATA(out), 32));
    PG_RETURN_TEXT_P(out);
}

PG_FUNCTION_INFO_V1(ip4_cast_from_text);
Datum
ip4_cast_from_text(PG_FUNCTION_ARGS)
{
    text *txt = PG_GETARG_TEXT_P(0);
    int tlen = get_text_len(txt);
    char buf[32];

    if (tlen < sizeof(buf))
    {
	IP4 ip;

	memcpy(buf, VARDATA(txt), tlen);
	buf[tlen] = 0;
	if (ip4_from_str(buf, &ip))
	    PG_RETURN_IP4(ip);
    }

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid IP4 value in text")));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4_cast_from_inet);
Datum
ip4_cast_from_inet(PG_FUNCTION_ARGS)
{
    inet *inetptr = PG_GETARG_INET_P(0);
    inet_struct *in = INET_STRUCT_DATA(inetptr);

    if (in->family == PGSQL_AF_INET)
    {
        unsigned char *p = in->INET_IPADDR;
    	IP4 ip = (p[0] << 24)|(p[1] << 16)|(p[2] << 8)|p[3];
	PG_RETURN_IP4(ip);
    }

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid INET value for conversion to IP4")));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4_cast_to_cidr);
Datum
ip4_cast_to_cidr(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    inet *res = palloc0(VARHDRSZ + sizeof(inet_struct));
    inet_struct *in;

    SET_VARSIZE(res, VARHDRSZ + offsetof(inet_struct, INET_IPADDR) + 4);

    in = ((inet_struct *)VARDATA(res));
    INET_INIT_CIDR(in);
    in->bits = 32;
    in->family = PGSQL_AF_INET;
    {
	unsigned char *p = in->INET_IPADDR;
	p[0] = (ip >> 24) & 0xff;
	p[1] = (ip >> 16) & 0xff;
	p[2] = (ip >>  8) & 0xff;
	p[3] = (ip      ) & 0xff;
    }

    PG_RETURN_INET_P(res);
}

PG_FUNCTION_INFO_V1(ip4_cast_to_bigint);
Datum
ip4_cast_to_bigint(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    PG_RETURN_INT64(ip);
}

PG_FUNCTION_INFO_V1(ip4_cast_from_bigint);
Datum
ip4_cast_from_bigint(PG_FUNCTION_ARGS)
{
    int64 val = PG_GETARG_INT64(0);
    PG_RETURN_IP4(val);
}

PG_FUNCTION_INFO_V1(ip4_cast_to_double);
Datum
ip4_cast_to_double(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    PG_RETURN_FLOAT8(ip);
}

PG_FUNCTION_INFO_V1(ip4_cast_from_double);
Datum
ip4_cast_from_double(PG_FUNCTION_ARGS)
{
    float8 val = PG_GETARG_FLOAT8(0);
    float8 ival = 0;

    if (modf(val,&ival) != 0.0)
    {
	ereport(WARNING,
		(errcode(ERRCODE_WARNING),
		 errmsg("double converted to IP4 is not integral")));
    }

    PG_RETURN_IP4((unsigned long) ival);
}

PG_FUNCTION_INFO_V1(ip4_netmask);
Datum
ip4_netmask(PG_FUNCTION_ARGS)
{
    int pfxlen = PG_GETARG_INT32(0);

    if (pfxlen < 0 || pfxlen > 32)
    {
	ereport(ERROR,
		(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
		 errmsg("prefix length out of range")));
    }

    PG_RETURN_IP4( netmask(pfxlen) );
}

PG_FUNCTION_INFO_V1(ip4_net_lower);
Datum
ip4_net_lower(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int pfxlen = PG_GETARG_INT32(1);

    if (pfxlen < 0 || pfxlen > 32)
    {
	ereport(ERROR,
		(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
		 errmsg("prefix length out of range")));
    }

    PG_RETURN_IP4( ip & netmask(pfxlen) );
}

PG_FUNCTION_INFO_V1(ip4_net_upper);
Datum
ip4_net_upper(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int pfxlen = PG_GETARG_INT32(1);

    if (pfxlen < 0 || pfxlen > 32)
    {
	ereport(ERROR,
		(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
		 errmsg("prefix length out of range")));
    }

    PG_RETURN_IP4( ip | hostmask(pfxlen) );
}

PG_FUNCTION_INFO_V1(ip4_plus_int);
Datum
ip4_plus_int(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int addend = PG_GETARG_INT32(1);
    IP4 result = ip + (IP4) addend;

    if ((addend < 0) != (result < ip))
    {
	ereport(ERROR,
		(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
		 errmsg("ip address out of range")));
    }

    PG_RETURN_IP4(result);
}

PG_FUNCTION_INFO_V1(ip4_plus_bigint);
Datum
ip4_plus_bigint(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int64 addend = PG_GETARG_INT64(1);
    int64 result = (int64) ip + addend;

    if (((addend < 0) != (result < ip))
	|| result != (int64)(IP4)result)
    {
	ereport(ERROR,
		(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
		 errmsg("ip address out of range")));
    }

    PG_RETURN_IP4( (IP4)(result) );
}

PG_FUNCTION_INFO_V1(ip4_minus_int);
Datum
ip4_minus_int(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int subtrahend = PG_GETARG_INT32(1);
    IP4 result = ip - (IP4) subtrahend;

    if ((subtrahend > 0) != (result < ip))
    {
	ereport(ERROR,
		(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
		 errmsg("ip address out of range")));
    }

    PG_RETURN_IP4(result);
}

PG_FUNCTION_INFO_V1(ip4_minus_bigint);
Datum
ip4_minus_bigint(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int64 subtrahend = PG_GETARG_INT64(1);
    int64 result = (int64) ip - subtrahend;

    if (((subtrahend > 0) != (result < ip))
	|| result != (int64)(IP4)result)
    {
	ereport(ERROR,
		(errcode(ERRCODE_NUMERIC_VALUE_OUT_OF_RANGE),
		 errmsg("ip address out of range")));
    }

    PG_RETURN_IP4( (IP4)(result) );
}

PG_FUNCTION_INFO_V1(ip4_minus_ip4);
Datum
ip4_minus_ip4(PG_FUNCTION_ARGS)
{
    IP4 minuend = PG_GETARG_IP4(0);
    IP4 subtrahend = PG_GETARG_IP4(1);
    int64 result = (int64) minuend - (int64) subtrahend;

    PG_RETURN_INT64(result);
}

PG_FUNCTION_INFO_V1(ip4_and);
Datum
ip4_and(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);
    IP4 b = PG_GETARG_IP4(1);

    PG_RETURN_IP4(a & b);
}

PG_FUNCTION_INFO_V1(ip4_or);
Datum
ip4_or(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);
    IP4 b = PG_GETARG_IP4(1);

    PG_RETURN_IP4(a | b);
}

PG_FUNCTION_INFO_V1(ip4_xor);
Datum
ip4_xor(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);
    IP4 b = PG_GETARG_IP4(1);

    PG_RETURN_IP4(a ^ b);
}

PG_FUNCTION_INFO_V1(ip4_not);
Datum
ip4_not(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);

    PG_RETURN_IP4(~a);
}


/*---- ip4r ----*/

PG_FUNCTION_INFO_V1(ip4r_in);
Datum
ip4r_in(PG_FUNCTION_ARGS)
{
    char *str = PG_GETARG_CSTRING(0);
    IP4R ipr;
    if (ip4r_from_str(str, &ipr))
    {
	IP4R *res = palloc(sizeof(IP4R));
	*res = ipr;
	PG_RETURN_IP4R_P(res);
    }

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid IP4R value: \"%s\"", str)));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4r_out);
Datum
ip4r_out(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    char *out = palloc(32);
    ip4r_to_str(ipr, out, 32);
    PG_RETURN_CSTRING(out);
}

PG_FUNCTION_INFO_V1(ip4r_recv);
Datum
ip4r_recv(PG_FUNCTION_ARGS)
{
    StringInfo buf = (StringInfo) PG_GETARG_POINTER(0);
    IP4R *ipr = palloc(sizeof(IP4R));

    ipr->lower = (IP4) pq_getmsgint(buf, sizeof(IP4));
    ipr->upper = (IP4) pq_getmsgint(buf, sizeof(IP4));

    PG_RETURN_IP4R_P(ipr);
}

PG_FUNCTION_INFO_V1(ip4r_send);
Datum
ip4r_send(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    StringInfoData buf;

    pq_begintypsend(&buf);
    pq_sendint(&buf, ipr->lower, sizeof(IP4));
    pq_sendint(&buf, ipr->upper, sizeof(IP4));
    PG_RETURN_BYTEA_P(pq_endtypsend(&buf));
}

PG_FUNCTION_INFO_V1(ip4rhash);
Datum
ip4rhash(PG_FUNCTION_ARGS)
{
    IP4R *arg1 = PG_GETARG_IP4R_P(0);

    return hash_any((unsigned char *)arg1, sizeof(IP4R));
}

PG_FUNCTION_INFO_V1(ip4r_cast_to_text);
Datum
ip4r_cast_to_text(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    text *out = make_text(NULL,32);
    set_text_len(out, ip4r_to_str(ipr, VARDATA(out), 32));
    PG_RETURN_TEXT_P(out);
}

PG_FUNCTION_INFO_V1(ip4r_cast_from_text);
Datum
ip4r_cast_from_text(PG_FUNCTION_ARGS)
{
    text *txt = PG_GETARG_TEXT_P(0);
    int tlen = get_text_len(txt);
    char buf[32];

    if (tlen < sizeof(buf))
    {
	IP4R ipr;

	memcpy(buf, VARDATA(txt), tlen);
	buf[tlen] = 0;
	if (ip4r_from_str(buf, &ipr))
	{
	    IP4R *res = palloc(sizeof(IP4R));
	    *res = ipr;
	    PG_RETURN_IP4R_P(res);
	}
    }

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid IP4R value in text")));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4r_cast_from_cidr);
Datum
ip4r_cast_from_cidr(PG_FUNCTION_ARGS)
{
    inet *inetptr = PG_GETARG_INET_P(0);
    inet_struct *in = INET_STRUCT_DATA(inetptr);

    if (INET_IS_CIDR(in) && in->family == PGSQL_AF_INET)
    {
        unsigned char *p = in->INET_IPADDR;
    	IP4 ip = (p[0] << 24)|(p[1] << 16)|(p[2] << 8)|p[3];
	IP4R ipr;
	if (ip4r_from_cidr(ip, in->bits, &ipr))
	{
	    IP4R *res = palloc(sizeof(IP4R));
	    *res = ipr;
	    PG_RETURN_IP4R_P(res);
	}
    }

    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid CIDR value for conversion to IP4R")));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4r_cast_to_cidr);
Datum
ip4r_cast_to_cidr(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    IP4 ip = ipr->lower;
    inet *res;
    inet_struct *in;
    unsigned bits = masklen(ip, ipr->upper);

    if (bits > 32)
	PG_RETURN_NULL();

    res = palloc0(VARHDRSZ + sizeof(inet_struct));
    SET_VARSIZE(res, VARHDRSZ + offsetof(inet_struct, INET_IPADDR) + 4);

    in = ((inet_struct *)VARDATA(res));
    INET_INIT_CIDR(in);
    in->bits = bits;
    in->family = PGSQL_AF_INET;
    {
	unsigned char *p = in->INET_IPADDR;
	p[0] = (ip >> 24) & 0xff;
	p[1] = (ip >> 16) & 0xff;
	p[2] = (ip >>  8) & 0xff;
	p[3] = (ip      ) & 0xff;
    }

    PG_RETURN_INET_P(res);
}

PG_FUNCTION_INFO_V1(ip4r_cast_from_ip4);
Datum
ip4r_cast_from_ip4(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    IP4R *res = palloc(sizeof(IP4R));
    if (ip4r_from_inet(ip, 32, res))
    {
	PG_RETURN_IP4R_P(res);
    }

    pfree(res);
    ereport(ERROR,
	    (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
	     errmsg("invalid IP4 value for conversion to IP4R (shouldn't be possible)")));
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4r_from_ip4s);
Datum
ip4r_from_ip4s(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);
    IP4 b = PG_GETARG_IP4(1);
    IP4R *res = palloc(sizeof(IP4R));
    if (a < b)
	res->lower = a, res->upper = b;
    else
	res->lower = b, res->upper = a;
    PG_RETURN_IP4R_P( res );
}

PG_FUNCTION_INFO_V1(ip4r_net_prefix);
Datum
ip4r_net_prefix(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    int pfxlen = PG_GETARG_INT32(1);

    if (pfxlen < 0 || pfxlen > 32)
    {
	ereport(ERROR,
		(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
		 errmsg("prefix length out of range")));
    }

    {
	IP4 mask = netmask(pfxlen);
	IP4R *res = palloc(sizeof(IP4R));
    
	res->lower = ip & mask;
	res->upper = ip | ~mask;

	PG_RETURN_IP4R_P(res);
    }
}

PG_FUNCTION_INFO_V1(ip4r_net_mask);
Datum
ip4r_net_mask(PG_FUNCTION_ARGS)
{
    IP4 ip = PG_GETARG_IP4(0);
    IP4 mask = PG_GETARG_IP4(1);

    if (!ip4_valid_netmask(mask))
    {
	ereport(ERROR,
		(errcode(ERRCODE_INVALID_PARAMETER_VALUE),
		 errmsg("invalid netmask")));
    }

    {
	IP4R *res = palloc(sizeof(IP4R));
    
	res->lower = ip & mask;
	res->upper = ip | ~mask;

	PG_RETURN_IP4R_P(res);
    }
}


PG_FUNCTION_INFO_V1(ip4r_lower);
Datum
ip4r_lower(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    PG_RETURN_IP4( ipr->lower );
}

PG_FUNCTION_INFO_V1(ip4r_upper);
Datum
ip4r_upper(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    PG_RETURN_IP4( ipr->upper );
}

PG_FUNCTION_INFO_V1(ip4r_is_cidr);
Datum
ip4r_is_cidr(PG_FUNCTION_ARGS)
{
    IP4R *ipr = PG_GETARG_IP4R_P(0);
    PG_RETURN_BOOL( (masklen(ipr->lower,ipr->upper) <= 32U) );
}

PG_FUNCTION_INFO_V1(ip4_lt);
Datum
ip4_lt(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_lessthan(PG_GETARG_IP4(0), PG_GETARG_IP4(1)) );
}

PG_FUNCTION_INFO_V1(ip4_le);
Datum
ip4_le(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_less_eq(PG_GETARG_IP4(0), PG_GETARG_IP4(1)) );
}

PG_FUNCTION_INFO_V1(ip4_gt);
Datum
ip4_gt(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_lessthan(PG_GETARG_IP4(1), PG_GETARG_IP4(0)) );
}

PG_FUNCTION_INFO_V1(ip4_ge);
Datum
ip4_ge(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_less_eq(PG_GETARG_IP4(1), PG_GETARG_IP4(0)) );
}

PG_FUNCTION_INFO_V1(ip4_eq);
Datum
ip4_eq(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_equal(PG_GETARG_IP4(0), PG_GETARG_IP4(1)) );
}

PG_FUNCTION_INFO_V1(ip4_neq);
Datum
ip4_neq(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( !ip4_equal(PG_GETARG_IP4(0), PG_GETARG_IP4(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_lt);
Datum
ip4r_lt(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_lessthan(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_le);
Datum
ip4r_le(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_less_eq(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_gt);
Datum
ip4r_gt(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_lessthan(PG_GETARG_IP4R_P(1), PG_GETARG_IP4R_P(0)) );
}

PG_FUNCTION_INFO_V1(ip4r_ge);
Datum
ip4r_ge(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_less_eq(PG_GETARG_IP4R_P(1), PG_GETARG_IP4R_P(0)) );
}

PG_FUNCTION_INFO_V1(ip4r_eq);
Datum
ip4r_eq(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_equal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_neq);
Datum
ip4r_neq(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( !ip4r_equal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_overlaps);
Datum
ip4r_overlaps(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_overlaps_internal(PG_GETARG_IP4R_P(0), 
					   PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_contains);
Datum
ip4r_contains(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_contains_internal(PG_GETARG_IP4R_P(0),
					   PG_GETARG_IP4R_P(1),
					   TRUE) );
}

PG_FUNCTION_INFO_V1(ip4r_contains_strict);
Datum
ip4r_contains_strict(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_contains_internal(PG_GETARG_IP4R_P(0),
					   PG_GETARG_IP4R_P(1),
					   FALSE) );
}

PG_FUNCTION_INFO_V1(ip4r_contained_by);
Datum
ip4r_contained_by(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_contains_internal(PG_GETARG_IP4R_P(1),
					   PG_GETARG_IP4R_P(0),
					   TRUE) );
}

PG_FUNCTION_INFO_V1(ip4r_contained_by_strict);
Datum
ip4r_contained_by_strict(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_contains_internal(PG_GETARG_IP4R_P(1),
					   PG_GETARG_IP4R_P(0),
					   FALSE) );
}

PG_FUNCTION_INFO_V1(ip4_contains);
Datum
ip4_contains(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_contains_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4(1)) );
}

PG_FUNCTION_INFO_V1(ip4_contained_by);
Datum
ip4_contained_by(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4_contains_internal(PG_GETARG_IP4R_P(1), PG_GETARG_IP4(0)) );
}

PG_FUNCTION_INFO_V1(ip4r_left_of);
Datum
ip4r_left_of(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_left_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_left_overlap);
Datum 
ip4r_left_overlap(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( IP4R_LEFT_OVERLAP_OP(PG_GETARG_IP4R_P(0),
                                         PG_GETARG_IP4R_P(1)) );
}

PG_FUNCTION_INFO_V1(ip4r_right_of);
Datum
ip4r_right_of(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( ip4r_left_internal(PG_GETARG_IP4R_P(1), PG_GETARG_IP4R_P(0)) );
}

PG_FUNCTION_INFO_V1(ip4r_right_overlap);
Datum
ip4r_right_overlap(PG_FUNCTION_ARGS)
{
    PG_RETURN_BOOL( IP4R_RIGHT_OVERLAP_OP(PG_GETARG_IP4R_P(0),
                                          PG_GETARG_IP4R_P(1)) );
}


PG_FUNCTION_INFO_V1(ip4r_union);
Datum
ip4r_union(PG_FUNCTION_ARGS)
{
    IP4R *res = (IP4R *) palloc(sizeof(IP4R));
    ip4r_union_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1), res);
    PG_RETURN_IP4R_P(res);
}

PG_FUNCTION_INFO_V1(ip4r_inter);
Datum
ip4r_inter(PG_FUNCTION_ARGS)
{
    IP4R *res = (IP4R *) palloc(sizeof(IP4R));
    if (ip4r_inter_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1), res))
    {
	PG_RETURN_IP4R_P(res);
    }
    pfree(res);
    PG_RETURN_NULL();
}

PG_FUNCTION_INFO_V1(ip4r_size);
Datum
ip4r_size(PG_FUNCTION_ARGS)
{
    double size = ip4r_metric(PG_GETARG_IP4R_P(0));
    PG_RETURN_FLOAT8(size);
}


/*****************************************************************************
 *						   Btree functions
 *****************************************************************************/

PG_FUNCTION_INFO_V1(ip4r_cmp);
Datum
ip4r_cmp(PG_FUNCTION_ARGS)
{
    IP4R *a = PG_GETARG_IP4R_P(0);
    IP4R *b = PG_GETARG_IP4R_P(1);
    if (ip4r_lessthan(a,b))
	PG_RETURN_INT32(-1);
    if (ip4r_equal(a,b))
	PG_RETURN_INT32(0);
    PG_RETURN_INT32(1);
}

PG_FUNCTION_INFO_V1(ip4_cmp);
Datum
ip4_cmp(PG_FUNCTION_ARGS)
{
    IP4 a = PG_GETARG_IP4(0);
    IP4 b = PG_GETARG_IP4(1);
    if (ip4_lessthan(a,b))
	PG_RETURN_INT32(-1);
    if (ip4_equal(a,b))
	PG_RETURN_INT32(0);
    PG_RETURN_INT32(1);
}


/*****************************************************************************
 *						   Rtree functions
 *****************************************************************************/

Datum rt_ip4r_union(PG_FUNCTION_ARGS);
Datum rt_ip4r_inter(PG_FUNCTION_ARGS);
Datum rt_ip4r_size(PG_FUNCTION_ARGS);

PG_FUNCTION_INFO_V1(rt_ip4r_union);
Datum
rt_ip4r_union(PG_FUNCTION_ARGS)
{
    IP4R *res = (IP4R *) palloc(sizeof(IP4R));
    ip4r_union_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1), res);
    PG_RETURN_IP4R_P(res);
}

PG_FUNCTION_INFO_V1(rt_ip4r_inter);
Datum
rt_ip4r_inter(PG_FUNCTION_ARGS)
{
    IP4R *res = (IP4R *) palloc(sizeof(IP4R));
    if (ip4r_inter_internal(PG_GETARG_IP4R_P(0), PG_GETARG_IP4R_P(1), res))
    {
	PG_RETURN_IP4R_P(res);
    }
    pfree(res);
    PG_RETURN_IP4R_P(NULL);
}

PG_FUNCTION_INFO_V1(rt_ip4r_size);
Datum
rt_ip4r_size(PG_FUNCTION_ARGS)
{
    float *psize = (float *) PG_GETARG_POINTER(1);
    *psize = (float) ip4r_metric(PG_GETARG_IP4R_P(0));

    PG_RETURN_VOID();
}

/*****************************************************************************
 *						   GiST functions
 *****************************************************************************/

/*
** GiST support methods
*/

Datum gip4r_consistent(PG_FUNCTION_ARGS);
Datum gip4r_compress(PG_FUNCTION_ARGS);
Datum gip4r_decompress(PG_FUNCTION_ARGS);
Datum gip4r_penalty(PG_FUNCTION_ARGS);
Datum gip4r_picksplit(PG_FUNCTION_ARGS);
Datum gip4r_union(PG_FUNCTION_ARGS);
Datum gip4r_same(PG_FUNCTION_ARGS);

static bool gip4r_leaf_consistent(IP4R * key, IP4R * query, StrategyNumber strategy);
static bool gip4r_internal_consistent(IP4R * key, IP4R * query, StrategyNumber strategy);

/*
** The GiST Consistent method for IP ranges
** Should return false if for all data items x below entry,
** the predicate x op query == FALSE, where op is the oper
** corresponding to strategy in the pg_amop table.
*/
PG_FUNCTION_INFO_V1(gip4r_consistent);
Datum
gip4r_consistent(PG_FUNCTION_ARGS)
{
    GISTENTRY *entry = (GISTENTRY *) PG_GETARG_POINTER(0);
    IP4R *query = (IP4R *) PG_GETARG_POINTER(1);
    StrategyNumber strategy = (StrategyNumber) PG_GETARG_UINT16(2);
    IP4R *key = (IP4R *) DatumGetPointer(entry->key);
    bool retval;

    /*
     * * if entry is not leaf, use gip4r_internal_consistent, * else use
     * gip4r_leaf_consistent
     */
    if (GIST_LEAF(entry))
	retval = gip4r_leaf_consistent(key, query, strategy);
    else
	retval = gip4r_internal_consistent(key, query, strategy);

    PG_RETURN_BOOL(retval);
}

/*
** The GiST Union method for IP ranges
** returns the minimal bounding IP4R that encloses all the entries in entryvec
*/
PG_FUNCTION_INFO_V1(gip4r_union);
Datum
gip4r_union(PG_FUNCTION_ARGS)
{
    GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
    int	*sizep = (int *) PG_GETARG_POINTER(1);
    GISTENTRY *ent = GISTENTRYVEC(entryvec);

    int	numranges, i;
    IP4R *out = (IP4R *) palloc(sizeof(IP4R));
    IP4R *tmp;
  
#ifdef GIST_DEBUG
    fprintf(stderr, "union\n");
#endif
  
    numranges = GISTENTRYCOUNT(entryvec);
    tmp = (IP4R *) DatumGetPointer(ent[0].key);
    *sizep = sizeof(IP4R);
    *out = *tmp;
  
    for (i = 1; i < numranges; i++)
    {
	tmp = (IP4R *) DatumGetPointer(ent[i].key);
	if (tmp->lower < out->lower)
	    out->lower = tmp->lower;
	if (tmp->upper > out->upper)
	    out->upper = tmp->upper;
    }
    
    PG_RETURN_IP4R_P(out);
}

/*
** GiST Compress and Decompress methods for IP ranges
** do not do anything.
*/
PG_FUNCTION_INFO_V1(gip4r_compress);
Datum
gip4r_compress(PG_FUNCTION_ARGS)
{
    PG_RETURN_POINTER(PG_GETARG_POINTER(0));
}

PG_FUNCTION_INFO_V1(gip4r_decompress);
Datum
gip4r_decompress(PG_FUNCTION_ARGS)
{
    PG_RETURN_POINTER(PG_GETARG_POINTER(0));
}

/*
** The GiST Penalty method for IP ranges
** As in the R-tree paper, we use change in area as our penalty metric
*/
PG_FUNCTION_INFO_V1(gip4r_penalty);
Datum
gip4r_penalty(PG_FUNCTION_ARGS)
{
    GISTENTRY *origentry = (GISTENTRY *) PG_GETARG_POINTER(0);
    GISTENTRY *newentry = (GISTENTRY *) PG_GETARG_POINTER(1);
    float *result = (float *) PG_GETARG_POINTER(2);
    IP4R *key;
    IP4R ud;
    float tmp1, tmp2;

    key = (IP4R *) DatumGetPointer(origentry->key);
    ud = *key;
    tmp2 = ip4r_metric(&ud);

    key = (IP4R *) DatumGetPointer(newentry->key);
    if (key->lower < ud.lower)
	ud.lower = key->lower;
    if (key->upper > ud.upper)
	ud.upper = key->upper;
    tmp1 = ip4r_metric(&ud);

    *result = tmp1 - tmp2;
  
#ifdef GIST_DEBUG
    fprintf(stderr, "penalty\n");
    fprintf(stderr, "\t%g\n", *result);
#endif
  
    PG_RETURN_POINTER(result);
}


/* Helper functions for picksplit. We might need to sort a list of
 * ranges by size; these are for that.
 */

struct gip4r_sort
{
    IP4R *key;
    OffsetNumber pos;
};

static int
gip4r_sort_compare(const void *a, const void *b)
{
    double sa = ip4r_metric(((struct gip4r_sort *)a)->key);
    double sb = ip4r_metric(((struct gip4r_sort *)b)->key);
    return (sa > sb) ? 1 : ((sa == sb) ? 0 : -1);
}

/*
** The GiST PickSplit method for IP ranges
** This is a linear-time algorithm based on a left/right split,
** based on the box functions in rtree_gist simplified to one
** dimension
*/
PG_FUNCTION_INFO_V1(gip4r_picksplit);
Datum
gip4r_picksplit(PG_FUNCTION_ARGS)
{
    GistEntryVector *entryvec = (GistEntryVector *) PG_GETARG_POINTER(0);
    GIST_SPLITVEC *v = (GIST_SPLITVEC *) PG_GETARG_POINTER(1);
    GISTENTRY *ent = GISTENTRYVEC(entryvec);
    OffsetNumber i;
    int	nbytes;
    OffsetNumber maxoff;
    OffsetNumber *listL;
    OffsetNumber *listR;
    bool allisequal = true;
    IP4R pageunion;
    IP4R *cur;
    IP4R *unionL;
    IP4R *unionR;
    int posL = 0;
    int posR = 0;

    posL = posR = 0;
    maxoff = GISTENTRYCOUNT(entryvec) - 1;

    cur = (IP4R *) DatumGetPointer(ent[FirstOffsetNumber].key);
    pageunion = *cur;

    /* find MBR */
    for (i = OffsetNumberNext(FirstOffsetNumber); i <= maxoff; i = OffsetNumberNext(i))
    {
	cur = (IP4R *) DatumGetPointer(ent[i].key);
	if (allisequal == true
	    && (pageunion.lower != cur->lower || pageunion.upper != cur->upper))
	    allisequal = false;

	if (cur->lower < pageunion.lower)
	    pageunion.lower = cur->lower;
	if (cur->upper > pageunion.upper)
	    pageunion.upper = cur->upper;
    }

    nbytes = (maxoff + 2) * sizeof(OffsetNumber);
    listL = (OffsetNumber *) palloc(nbytes);
    listR = (OffsetNumber *) palloc(nbytes);
    unionL = (IP4R *) palloc(sizeof(IP4R));
    unionR = (IP4R *) palloc(sizeof(IP4R));
    v->spl_ldatum = PointerGetDatum(unionL);
    v->spl_rdatum = PointerGetDatum(unionR);
    v->spl_left = listL;
    v->spl_right = listR;

    if (allisequal)
    {
	cur = (IP4R *) DatumGetPointer(ent[OffsetNumberNext(FirstOffsetNumber)].key);
	if (ip4r_equal(cur, &pageunion))
	{
	    OffsetNumber split_at = FirstOffsetNumber + (maxoff - FirstOffsetNumber + 1)/2;
	    v->spl_nleft = v->spl_nright = 0;
	    *unionL = pageunion;
	    *unionR = pageunion;

	    for (i = FirstOffsetNumber; i < split_at; i = OffsetNumberNext(i))
		v->spl_left[v->spl_nleft++] = i;
	    for (; i <= maxoff; i = OffsetNumberNext(i))
		v->spl_right[v->spl_nright++] = i;

	    PG_RETURN_POINTER(v);
	}
    }

#define ADDLIST( list_, u_, pos_, num_ ) do { \
	if ( pos_ ) { \
		if ( (u_)->upper < (cur)->upper ) (u_)->upper = (cur)->upper; \
		if ( (u_)->lower > (cur)->lower ) (u_)->lower = (cur)->lower; \
	} else { \
		*(u_) = *(cur); \
	} \
	(list_)[(pos_)++] = (num_); \
} while(0)

    for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
    {
	cur = (IP4R *) DatumGetPointer(ent[i].key);
	if (cur->lower - pageunion.lower < pageunion.upper - cur->upper)
	    ADDLIST(listL, unionL, posL, i);
	else
	    ADDLIST(listR, unionR, posR, i);
    }

    /* bad disposition, sort by ascending size and resplit */
    if (posR == 0 || posL == 0)
    {
	struct gip4r_sort *arr = (struct gip4r_sort *)
	    palloc(sizeof(struct gip4r_sort) * (maxoff + FirstOffsetNumber));

	for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
	{
	    arr[i].key = (IP4R *) DatumGetPointer(ent[i].key);
	    arr[i].pos = i;
	}

	qsort(arr + FirstOffsetNumber,
	      maxoff - FirstOffsetNumber + 1,
	      sizeof(struct gip4r_sort),
	      gip4r_sort_compare);

	posL = posR = 0;
	for (i = FirstOffsetNumber; i <= maxoff; i = OffsetNumberNext(i))
	{
	    cur = arr[i].key;
	    if (cur->lower - pageunion.lower < pageunion.upper - cur->upper)
		ADDLIST(listL, unionL, posL, arr[i].pos);
	    else if (cur->lower - pageunion.lower == pageunion.upper - cur->upper)
	    {
		if (posL > posR)
		    ADDLIST(listR, unionR, posR, arr[i].pos);
		else
		    ADDLIST(listL, unionL, posL, arr[i].pos);
	    }
	    else
		ADDLIST(listR, unionR, posR, arr[i].pos);
	}
	pfree(arr);
    }

    v->spl_nleft = posL;
    v->spl_nright = posR;

    PG_RETURN_POINTER(v);
}

#undef ADDLIST

/*
** Equality methods
*/
PG_FUNCTION_INFO_V1(gip4r_same);
Datum
gip4r_same(PG_FUNCTION_ARGS)
{
    IP4R *v1 = (IP4R *) PG_GETARG_POINTER(0);
    IP4R *v2 = (IP4R *) PG_GETARG_POINTER(1);
    bool *result = (bool *) PG_GETARG_POINTER(2);

    if (v1 && v2)
	*result = ip4r_equal(v1,v2);
    else
	*result = (v1 == NULL && v2 == NULL);

#ifdef GIST_DEBUG
    fprintf(stderr, "same: %s\n", (*result ? "TRUE" : "FALSE"));
#endif

    PG_RETURN_POINTER(result);
}


/*
 * Strategy numbers:
 *	OPERATOR	1	>>= ,
 *	OPERATOR	2	<<= ,
 *	OPERATOR	3	>> ,
 *	OPERATOR	4	<< ,
 *	OPERATOR	5	&& ,
 *	OPERATOR	6	= ,
 */

/*
** SUPPORT ROUTINES
*/
static bool
gip4r_leaf_consistent(IP4R * key,
		      IP4R * query,
		      StrategyNumber strategy)
{
#ifdef GIST_QUERY_DEBUG
    fprintf(stderr, "leaf_consistent, %d\n", strategy);
#endif
  
    switch (strategy)
    {
	case 1:   /* left contains right nonstrict */
	    return ip4r_contains_internal(key, query, TRUE);
	case 2:   /* left contained in right nonstrict */
	    return ip4r_contains_internal(query, key, TRUE);
	case 3:   /* left contains right strict */
	    return ip4r_contains_internal(key, query, FALSE);
	case 4:   /* left contained in right strict */
	    return ip4r_contains_internal(query, key, FALSE);
	case 5:   /* left overlaps right */
	    return ip4r_overlaps_internal(key, query);
	case 6:   /* left equal right */
	    return ip4r_equal(key, query);
	default:
	    return FALSE;
    }
}

/* logic notes:
 * If the union value we're looking at overlaps with our query value
 * at all, then any of the values underneath it might overlap with us
 * or be contained by us, so all the "contained by" and "overlaps"
 * cases degenerate to "overlap".
 * If the union value is equal to the query value, then none of the
 * values under it can strictly contain the query value, so for
 * "contained" queries the strictness is preserved.
 * If we're looking for an "equal" value, then we have to enter any
 * subtree whose union contains (not strictly) our query value.
 */

bool
gip4r_internal_consistent(IP4R * key,
			  IP4R * query,
			  StrategyNumber strategy)
{
#ifdef GIST_QUERY_DEBUG
    fprintf(stderr, "internal_consistent, %d\n", strategy);
#endif
  
    switch (strategy)
    {
	case 2:   /* left contained in right nonstrict */
	case 4:   /* left contained in right strict */
	case 5:   /* left overlaps right */
	    return ip4r_overlaps_internal(key, query);
	case 3:   /* left contains right strict */
	    return ip4r_contains_internal(key, query, FALSE);
	case 1:   /* left contains right nonstrict */
	case 6:   /* left equal right */
	    return ip4r_contains_internal(key, query, TRUE);
	default:
	    return FALSE;
    }
}

/* end */