sqlitegis 0.1.4

SQLiteGIS: PostGIS-style spatial functions for SQLite in pure Rust.
Documentation
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
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
//! EWKB (Extended Well-Known Binary) parser and writer.
//!
//! Wire format:
//!   \[0x01|0x00\]: byte order marker (little-endian or big-endian)
//!   \[u32\]: geometry type with flags (in the declared byte order)
//!     Bit 29 (0x20000000): SRID present
//!     Bit 31 (0x80000000): Z dimension
//!     Bit 30 (0x40000000): M dimension
//!     Bits 0-28: geometry type (1=Point, 2=LineString, etc.)
//!   \[i32\]: SRID (only when SRID flag set, in declared byte order)
//!   \[rest\]: ISO WKB geometry payload

use geo::{Coord, CoordsIter, Geometry, Point, Rect};
use geozero::wkb::Ewkb;
use geozero::{CoordDimensions, ToGeo, ToWkb};

use crate::core::error::{Result, SqliteGisError};

/// EWKB type flag: SRID is present immediately after the type word.
pub const EWKB_SRID_FLAG: u32 = 0x20000000;
/// EWKB type flag: coordinates include a Z dimension.
pub const EWKB_Z_FLAG: u32 = 0x80000000;
/// EWKB type flag: coordinates include an M (measure) dimension.
pub const EWKB_M_FLAG: u32 = 0x40000000;

/// ISO WKB geometry type code: Point.
pub const WKB_POINT: u32 = 1;
/// ISO WKB geometry type code: LineString.
pub const WKB_LINESTRING: u32 = 2;
/// ISO WKB geometry type code: Polygon.
pub const WKB_POLYGON: u32 = 3;
/// ISO WKB geometry type code: MultiPoint.
pub const WKB_MULTIPOINT: u32 = 4;
/// ISO WKB geometry type code: MultiLineString.
pub const WKB_MULTILINESTRING: u32 = 5;
/// ISO WKB geometry type code: MultiPolygon.
pub const WKB_MULTIPOLYGON: u32 = 6;
/// ISO WKB geometry type code: GeometryCollection.
pub const WKB_GEOMETRYCOLLECTION: u32 = 7;

/// Max container nesting the EWKB parsers accept. `geozero`'s recursive
/// `to_geo`/`to_wkt`/`to_json` overflow the stack around depth ~1500 (lower on
/// WASM), so a crafted ~9 KB blob aborts the process. Real geometries nest a
/// handful of levels, so this never bites legitimate data.
// TODO(georust/geozero#299): relax the geozero-facing cap once #299 lands. The
// cap on our own `walk_for_mbr` stays regardless.
pub const MAX_NESTING_DEPTH: usize = 32;

fn read_f64(bytes: [u8; 8], little_endian: bool) -> f64 {
    if little_endian {
        f64::from_le_bytes(bytes)
    } else {
        f64::from_be_bytes(bytes)
    }
}

/// Reject Z/M coordinate layouts when the operation can only process XY.
///
/// ```
/// use sqlitegis::core::ewkb::ensure_xy_only;
/// use sqlitegis::SqliteGisError;
///
/// assert!(ensure_xy_only(false, false).is_ok());
/// assert!(matches!(
///     ensure_xy_only(true, false),
///     Err(SqliteGisError::UnsupportedDimensions { dimensions: "Z" }),
/// ));
/// ```
pub fn ensure_xy_only(has_z: bool, has_m: bool) -> Result<()> {
    let dimensions = if has_z && has_m {
        "ZM"
    } else if has_z {
        "Z"
    } else if has_m {
        "M"
    } else {
        return Ok(());
    };
    Err(SqliteGisError::UnsupportedDimensions { dimensions })
}

fn point_is_empty_with_header(blob: &[u8], header: &EwkbHeader) -> Result<bool> {
    if header.geom_type != WKB_POINT {
        return Ok(false);
    }

    let dims = 2 + usize::from(header.has_z) + usize::from(header.has_m);
    let needed = header.data_offset + 8 * dims;
    if blob.len() < needed {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "point payload truncated: got {} bytes",
            blob.len()
        )));
    }

    let mut x_bytes = [0u8; 8];
    x_bytes.copy_from_slice(&blob[header.data_offset..header.data_offset + 8]);
    let mut y_bytes = [0u8; 8];
    y_bytes.copy_from_slice(&blob[header.data_offset + 8..header.data_offset + 16]);

    let x = read_f64(x_bytes, header.little_endian);
    let y = read_f64(y_bytes, header.little_endian);
    Ok(x.is_nan() && y.is_nan())
}

/// Return true when the EWKB blob encodes `POINT EMPTY`.
///
/// ```
/// use sqlitegis::core::ewkb::is_empty_point_blob;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let empty = geom_from_text("POINT EMPTY", None).unwrap();
/// assert!(is_empty_point_blob(&empty).unwrap());
///
/// let real = geom_from_text("POINT(1 2)", None).unwrap();
/// assert!(!is_empty_point_blob(&real).unwrap());
/// ```
pub fn is_empty_point_blob(blob: &[u8]) -> Result<bool> {
    let header = parse_ewkb_header(blob)?;
    point_is_empty_with_header(blob, &header)
}

/// Validate EWKB header + payload structure without forcing XY-only dimensions
/// and without deserializing through geozero.
///
/// Intended for metadata-oriented functions that read only the header and raw
/// coordinate bytes (`ST_SRID`, `ST_NDims`, `ST_Z`, ...). It checks header
/// well-formedness, bounded nesting depth, and that every element count fits
/// inside the blob, and it accepts Z/M geometries. Crucially it never calls
/// `to_geo`, so it cannot trigger geozero's count-driven pre-allocation: a
/// hostile blob that would make `to_geo` reserve gigabytes is rejected or
/// handled structurally here. Use [`validate_xy_ewkb_payload`] when you also
/// need a full geozero decode (XY-only).
///
/// ```
/// use sqlitegis::core::ewkb::validate_ewkb_payload;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// let hdr = validate_ewkb_payload(&blob).unwrap();
/// assert_eq!(hdr.srid, Some(4326));
/// ```
pub fn validate_ewkb_payload(blob: &[u8]) -> Result<EwkbHeader> {
    let header = parse_ewkb_header(blob)?;
    validate_payload_structure(blob, &header)?;
    Ok(header)
}

/// Validate EWKB header + payload and enforce XY-only coordinate dimensions.
///
/// Rejects Z, M, and ZM geometries via [`ensure_xy_only`] after validating
/// the wire format. The XY-only contract matches what every spatial
/// function in `crate::core::functions` accepts on input.
///
/// ```
/// use sqlitegis::core::ewkb::validate_xy_ewkb_payload;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let xy = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// let hdr = validate_xy_ewkb_payload(&xy).unwrap();
/// assert!(!hdr.has_z && !hdr.has_m);
/// ```
pub fn validate_xy_ewkb_payload(blob: &[u8]) -> Result<EwkbHeader> {
    let header = validate_ewkb_payload(blob)?;
    // Enforce XY BEFORE the geozero decode below: a Z/M element shifts
    // coordinate offsets (24 vs 16 bytes) so this crate's structural walk and
    // geozero's decoder disagree on where counts live, letting a crafted Z
    // blob slip a huge count past validation and make `to_geo` pre-allocate
    // gigabytes. Rejecting Z/M first keeps the decode bounded.
    ensure_xy_only(header.has_z, header.has_m)?;
    if !point_is_empty_with_header(blob, &header)? {
        let _: Geometry<f64> = Ewkb(blob).to_geo()?;
    }
    Ok(header)
}

/// Parsed EWKB header metadata.
#[derive(Debug, Clone)]
pub struct EwkbHeader {
    /// Base geometry type code (1=Point, 2=LineString, up to 7=GeometryCollection).
    pub geom_type: u32,
    /// SRID embedded in the EWKB, if the SRID flag is set.
    pub srid: Option<i32>,
    /// Whether the geometry has Z coordinates.
    pub has_z: bool,
    /// Whether the geometry has M coordinates.
    pub has_m: bool,
    /// Byte offset where the geometry payload starts (after header + optional SRID).
    pub data_offset: usize,
    /// Whether numeric header fields are encoded in little-endian order.
    pub little_endian: bool,
}

/// Peek at the EWKB header without fully parsing the geometry.
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::parse_ewkb_header;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// let hdr = parse_ewkb_header(&blob).unwrap();
/// assert_eq!(hdr.geom_type, 1); // WKB_POINT
/// assert_eq!(hdr.srid, Some(4326));
/// ```
pub fn parse_ewkb_header(blob: &[u8]) -> Result<EwkbHeader> {
    if blob.len() < 5 {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "blob too short: got {} bytes, need at least 5",
            blob.len()
        )));
    }

    let little_endian = match blob[0] {
        0x01 => true,
        0x00 => false,
        _ => {
            return Err(SqliteGisError::InvalidEwkb(
                "invalid byte order marker".to_string(),
            ))
        }
    };

    let read_u32 = |bytes: [u8; 4]| {
        if little_endian {
            u32::from_le_bytes(bytes)
        } else {
            u32::from_be_bytes(bytes)
        }
    };
    let read_i32 = |bytes: [u8; 4]| {
        if little_endian {
            i32::from_le_bytes(bytes)
        } else {
            i32::from_be_bytes(bytes)
        }
    };

    let raw_type = read_u32([blob[1], blob[2], blob[3], blob[4]]);
    let has_srid = (raw_type & EWKB_SRID_FLAG) != 0;
    let has_z = (raw_type & EWKB_Z_FLAG) != 0;
    let has_m = (raw_type & EWKB_M_FLAG) != 0;
    let geom_type = raw_type & 0x1FFFFFFF;

    let mut offset = 5usize;
    let srid = if has_srid {
        if blob.len() < 9 {
            return Err(SqliteGisError::InvalidEwkb(
                "SRID flag set but blob too short".to_string(),
            ));
        }
        let s = read_i32([blob[5], blob[6], blob[7], blob[8]]);
        offset += 4;
        Some(s)
    } else {
        None
    };

    Ok(EwkbHeader {
        geom_type,
        srid,
        has_z,
        has_m,
        data_offset: offset,
        little_endian,
    })
}

/// Extract only the SRID from an EWKB blob (cheap, no geometry parsing).
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::extract_srid;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// assert_eq!(extract_srid(&blob), Some(4326));
///
/// let no_srid = geom_from_text("POINT(1 2)", None).unwrap();
/// assert_eq!(extract_srid(&no_srid), None);
/// ```
pub fn extract_srid(blob: &[u8]) -> Option<i32> {
    parse_ewkb_header(blob).ok().and_then(|h| h.srid)
}

/// Enforce equal SRIDs for binary geometry operations.
///
/// Returns the shared SRID when both inputs are compatible.
pub fn ensure_matching_srid(left: Option<i32>, right: Option<i32>) -> Result<Option<i32>> {
    let l = left.unwrap_or(0);
    let r = right.unwrap_or(0);
    if l != r {
        return Err(SqliteGisError::InvalidInput(format!(
            "operation on mixed SRID geometries ({l} != {r})"
        )));
    }

    if left.is_none() && right.is_none() {
        Ok(None)
    } else {
        Ok(Some(l))
    }
}

/// Parse an EWKB blob into a `geo::Geometry<f64>`.
/// Returns `(geometry, srid)`.
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::parse_ewkb;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// let (geom, srid) = parse_ewkb(&blob).unwrap();
/// assert_eq!(srid, Some(4326));
/// ```
pub fn parse_ewkb(blob: &[u8]) -> Result<(Geometry<f64>, Option<i32>)> {
    let header = parse_ewkb_header(blob)?;
    ensure_xy_only(header.has_z, header.has_m)?;
    if point_is_empty_with_header(blob, &header)? {
        return Ok((Geometry::Point(Point::new(f64::NAN, f64::NAN)), header.srid));
    }
    // Structurally validate before geozero's recursive decoder sees the blob.
    validate_payload_structure(blob, &header)?;
    let geom = Ewkb(blob).to_geo()?;
    reject_non_finite_coords(&geom)?;
    Ok((geom, header.srid))
}

/// Reject a non-finite coordinate (NaN or infinity), which aborts several `geo`
/// algorithms (centroid `is_closed` assert, `lex_cmp` unwrap, relate graph).
/// `POINT EMPTY` (`NaN NaN`) is handled earlier and never reaches here. Only
/// `parse_ewkb` (the algorithm decode) calls this, so ingestion still stores
/// non-finite coordinates like PostGIS.
// TODO(georust/geo#1552, #1555, #1556): move from parse-time to the specific
// algorithms once fixed and released.
fn reject_non_finite_coords(geom: &Geometry<f64>) -> Result<()> {
    if geom
        .coords_iter()
        .any(|c| !c.x.is_finite() || !c.y.is_finite())
    {
        return Err(SqliteGisError::InvalidInput(
            "geometry has non-finite (NaN or infinite) coordinates".to_string(),
        ));
    }
    Ok(())
}

/// Parse two EWKB blobs and enforce matching SRID.
///
/// Returns `(left_geometry, right_geometry, shared_srid)`.
pub fn parse_ewkb_pair(a: &[u8], b: &[u8]) -> Result<(Geometry<f64>, Geometry<f64>, Option<i32>)> {
    let (ga, srid_a) = parse_ewkb(a)?;
    let (gb, srid_b) = parse_ewkb(b)?;
    let srid = ensure_matching_srid(srid_a, srid_b)?;
    Ok((ga, gb, srid))
}

/// Compute the planar minimum bounding rectangle of an EWKB blob without
/// allocating a [`Geometry`] enum.
///
/// Walks the EWKB byte payload, reads only the X/Y coordinates, and tracks
/// running min/max. For the "many points vs one window" filter shape this
/// is roughly 10-100x cheaper per call than `parse_ewkb(...).bounding_rect()`
/// because it skips the heap-allocating decode entirely.
///
/// Returns `Ok(None)` when the geometry is empty (empty Point with NaN
/// coordinates, empty LineString, empty Polygon, or any container whose
/// elements are all empty). Returns `Err` only for malformed blobs.
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::extract_mbr;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POLYGON((0 0, 10 0, 10 5, 0 5, 0 0))", None).unwrap();
/// let mbr = extract_mbr(&blob).unwrap().unwrap();
/// assert_eq!(mbr.min().x, 0.0);
/// assert_eq!(mbr.min().y, 0.0);
/// assert_eq!(mbr.max().x, 10.0);
/// assert_eq!(mbr.max().y, 5.0);
///
/// let empty = geom_from_text("POINT EMPTY", None).unwrap();
/// assert!(extract_mbr(&empty).unwrap().is_none());
/// ```
pub fn extract_mbr(blob: &[u8]) -> Result<Option<Rect<f64>>> {
    let header = parse_ewkb_header(blob)?;
    let mut acc: BboxAcc = None;
    walk_for_mbr(
        blob,
        header.data_offset,
        header.geom_type,
        header.has_z,
        header.has_m,
        header.little_endian,
        0,
        &mut acc,
    )?;
    Ok(acc
        .map(|(mnx, mny, mxx, mxy)| Rect::new(Coord { x: mnx, y: mny }, Coord { x: mxx, y: mxy })))
}

/// Running (min_x, min_y, max_x, max_y) accumulator. `None` means no
/// finite coordinates have been seen yet.
type BboxAcc = Option<(f64, f64, f64, f64)>;

fn update_bbox(acc: &mut BboxAcc, x: f64, y: f64) {
    // Skip NaN coordinates (PostGIS-style empty Points).
    if x.is_nan() || y.is_nan() {
        return;
    }
    match acc {
        Some((mnx, mny, mxx, mxy)) => {
            if x < *mnx {
                *mnx = x;
            }
            if y < *mny {
                *mny = y;
            }
            if x > *mxx {
                *mxx = x;
            }
            if y > *mxy {
                *mxy = y;
            }
        }
        None => *acc = Some((x, y, x, y)),
    }
}

fn read_f64_at(blob: &[u8], offset: usize, little_endian: bool) -> Result<f64> {
    if blob.len() < offset + 8 {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "blob truncated reading f64 at offset {offset}"
        )));
    }
    let mut bytes = [0u8; 8];
    bytes.copy_from_slice(&blob[offset..offset + 8]);
    Ok(read_f64(bytes, little_endian))
}

fn read_u32_at(blob: &[u8], offset: usize, little_endian: bool) -> Result<u32> {
    if blob.len() < offset + 4 {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "blob truncated reading u32 at offset {offset}"
        )));
    }
    let bytes = [
        blob[offset],
        blob[offset + 1],
        blob[offset + 2],
        blob[offset + 3],
    ];
    Ok(if little_endian {
        u32::from_le_bytes(bytes)
    } else {
        u32::from_be_bytes(bytes)
    })
}

/// Advance `offset` past `n_bytes`, checking overflow and presence.
fn advance_past(blob: &[u8], offset: usize, n_bytes: usize) -> Result<usize> {
    let end = offset.checked_add(n_bytes).ok_or_else(|| {
        SqliteGisError::InvalidEwkb("EWKB coordinate run overflows the address space".to_string())
    })?;
    if end > blob.len() {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "EWKB payload truncated: need {end} bytes, have {}",
            blob.len()
        )));
    }
    Ok(end)
}

/// Validate structure and nesting depth at `offset`, returning the offset past
/// this geometry. Reads only counts (skipping coordinate bytes via
/// [`advance_past`], with checked multiplication), bounded by the depth cap so
/// it cannot itself overflow. Run before `geozero`'s unguarded decoders.
fn validate_nesting(
    blob: &[u8],
    mut offset: usize,
    geom_type: u32,
    has_z: bool,
    has_m: bool,
    little_endian: bool,
    depth: usize,
) -> Result<usize> {
    if depth > MAX_NESTING_DEPTH {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "EWKB nesting depth exceeds limit of {MAX_NESTING_DEPTH}"
        )));
    }

    let coord_size = 16 + 8 * usize::from(has_z) + 8 * usize::from(has_m);
    // TODO(georust/geozero#297): bounding counts against remaining bytes is what
    // stops geozero's `Vec::with_capacity(untrusted_count)` OOM. Drop once #297
    // lands, or keep as defense in depth.
    let coord_run = |count: usize| -> Result<usize> {
        count.checked_mul(coord_size).ok_or_else(|| {
            SqliteGisError::InvalidEwkb("EWKB coordinate count overflows the address space".into())
        })
    };

    match geom_type {
        WKB_POINT => offset = advance_past(blob, offset, coord_size)?,
        WKB_LINESTRING => {
            let npoints = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            offset = advance_past(blob, offset, coord_run(npoints)?)?;
        }
        WKB_POLYGON => {
            let nrings = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            for _ in 0..nrings {
                let npoints = read_u32_at(blob, offset, little_endian)? as usize;
                offset += 4;
                offset = advance_past(blob, offset, coord_run(npoints)?)?;
            }
        }
        WKB_MULTIPOINT | WKB_MULTILINESTRING | WKB_MULTIPOLYGON | WKB_GEOMETRYCOLLECTION => {
            // A typed Multi* holds only its matching element type (a
            // GeometryCollection holds any). Enforcing this keeps the walk in
            // lockstep with geozero so a type-inconsistent container cannot
            // desync the two and slip a huge count into its pre-allocation.
            let expected_element: Option<u32> = match geom_type {
                WKB_MULTIPOINT => Some(WKB_POINT),
                WKB_MULTILINESTRING => Some(WKB_LINESTRING),
                WKB_MULTIPOLYGON => Some(WKB_POLYGON),
                _ => None,
            };
            let count = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            for _ in 0..count {
                if blob.len() < offset + 5 {
                    return Err(SqliteGisError::InvalidEwkb(format!(
                        "nested WKB header truncated at offset {offset}"
                    )));
                }
                let nested_le = match blob[offset] {
                    0x01 => true,
                    0x00 => false,
                    other => {
                        return Err(SqliteGisError::InvalidEwkb(format!(
                            "invalid nested byte-order marker {other} at offset {offset}"
                        )));
                    }
                };
                let nested_type = read_u32_at(blob, offset + 1, nested_le)?;
                let nested_geom_type = nested_type & 0x1FFFFFFF;
                let nested_has_z = (nested_type & EWKB_Z_FLAG) != 0;
                let nested_has_m = (nested_type & EWKB_M_FLAG) != 0;
                if let Some(expected) = expected_element {
                    if nested_geom_type != expected {
                        return Err(SqliteGisError::InvalidEwkb(format!(
                            "{} element has wrong type code {nested_geom_type}, expected {expected}",
                            geom_type_name(geom_type),
                        )));
                    }
                }
                offset += 5;
                // geozero skips a 4-byte SRID on a nested SRID-flagged header,
                // so skip it here too to stay byte-aligned. Otherwise every
                // later offset shifts and a huge count slips through.
                if nested_type & EWKB_SRID_FLAG != 0 {
                    offset = advance_past(blob, offset, 4)?;
                }
                offset = validate_nesting(
                    blob,
                    offset,
                    nested_geom_type,
                    nested_has_z,
                    nested_has_m,
                    nested_le,
                    depth + 1,
                )?;
            }
        }
        other => {
            return Err(SqliteGisError::InvalidEwkb(format!(
                "unsupported geometry type code {other} during EWKB validation"
            )));
        }
    }

    Ok(offset)
}

/// Reject EWKB whose nesting exceeds [`MAX_NESTING_DEPTH`], guarding the
/// recursive `geozero` decoders against stack overflow. Reads only structural
/// counts, never the coordinate payload.
///
/// ```
/// use sqlitegis::core::ewkb::ensure_ewkb_nesting_ok;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("GEOMETRYCOLLECTION(POINT(1 2))", None).unwrap();
/// assert!(ensure_ewkb_nesting_ok(&blob).is_ok());
/// ```
pub fn ensure_ewkb_nesting_ok(blob: &[u8]) -> Result<()> {
    let header = parse_ewkb_header(blob)?;
    validate_payload_structure(blob, &header)
}

/// Validate the payload: bounded depth, type-consistent containers, in-bounds
/// counts, and exact consumption (no trailing bytes). Exact consumption keeps
/// this aligned with geozero so a crafted blob cannot desync the two.
fn validate_payload_structure(blob: &[u8], header: &EwkbHeader) -> Result<()> {
    if point_is_empty_with_header(blob, header)? {
        return Ok(());
    }
    let end = validate_nesting(
        blob,
        header.data_offset,
        header.geom_type,
        header.has_z,
        header.has_m,
        header.little_endian,
        0,
    )?;
    if end != blob.len() {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "EWKB has {} trailing byte(s) after the geometry",
            blob.len().saturating_sub(end)
        )));
    }
    Ok(())
}

/// Walk the WKB payload at `offset` for a geometry of the given type +
/// dimensions, updating `acc` with each (X, Y) it sees. Returns the offset
/// just past this geometry's payload (so container types can chain).
///
/// `depth` is rejected past [`MAX_NESTING_DEPTH`] so a nested blob cannot
/// overflow the stack here.
#[allow(clippy::too_many_arguments)]
fn walk_for_mbr(
    blob: &[u8],
    mut offset: usize,
    geom_type: u32,
    has_z: bool,
    has_m: bool,
    little_endian: bool,
    depth: usize,
    acc: &mut BboxAcc,
) -> Result<usize> {
    if depth > MAX_NESTING_DEPTH {
        return Err(SqliteGisError::InvalidEwkb(format!(
            "EWKB nesting depth exceeds limit of {MAX_NESTING_DEPTH}"
        )));
    }

    let coord_size = 16 + 8 * usize::from(has_z) + 8 * usize::from(has_m);

    match geom_type {
        WKB_POINT => {
            let x = read_f64_at(blob, offset, little_endian)?;
            let y = read_f64_at(blob, offset + 8, little_endian)?;
            update_bbox(acc, x, y);
            offset += coord_size;
        }
        WKB_LINESTRING => {
            let npoints = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            for _ in 0..npoints {
                let x = read_f64_at(blob, offset, little_endian)?;
                let y = read_f64_at(blob, offset + 8, little_endian)?;
                update_bbox(acc, x, y);
                offset += coord_size;
            }
        }
        WKB_POLYGON => {
            let nrings = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            for _ in 0..nrings {
                let npoints = read_u32_at(blob, offset, little_endian)? as usize;
                offset += 4;
                for _ in 0..npoints {
                    let x = read_f64_at(blob, offset, little_endian)?;
                    let y = read_f64_at(blob, offset + 8, little_endian)?;
                    update_bbox(acc, x, y);
                    offset += coord_size;
                }
            }
        }
        WKB_MULTIPOINT | WKB_MULTILINESTRING | WKB_MULTIPOLYGON | WKB_GEOMETRYCOLLECTION => {
            let count = read_u32_at(blob, offset, little_endian)? as usize;
            offset += 4;
            for _ in 0..count {
                // Each nested element carries its own WKB mini-header
                // (byte-order byte + 4-byte type). EWKB's SRID flag is only
                // valid at the top level. Nested elements use plain WKB.
                if blob.len() < offset + 5 {
                    return Err(SqliteGisError::InvalidEwkb(format!(
                        "nested WKB header truncated at offset {offset}"
                    )));
                }
                let nested_le = match blob[offset] {
                    0x01 => true,
                    0x00 => false,
                    other => {
                        return Err(SqliteGisError::InvalidEwkb(format!(
                            "invalid nested byte-order marker {other} at offset {offset}"
                        )));
                    }
                };
                let nested_type = read_u32_at(blob, offset + 1, nested_le)?;
                let nested_geom_type = nested_type & 0x1FFFFFFF;
                let nested_has_z = (nested_type & EWKB_Z_FLAG) != 0;
                let nested_has_m = (nested_type & EWKB_M_FLAG) != 0;
                offset += 5;
                offset = walk_for_mbr(
                    blob,
                    offset,
                    nested_geom_type,
                    nested_has_z,
                    nested_has_m,
                    nested_le,
                    depth + 1,
                    acc,
                )?;
            }
        }
        other => {
            return Err(SqliteGisError::InvalidEwkb(format!(
                "unsupported geometry type code {other} during MBR extraction"
            )));
        }
    }

    Ok(offset)
}

fn patch_wkb_with_srid(iso_wkb: &[u8], srid_val: i32) -> Result<Vec<u8>> {
    if iso_wkb.len() < 5 {
        return Err(SqliteGisError::InvalidEwkb(
            "WKB output too short".to_string(),
        ));
    }
    let little_endian = match iso_wkb[0] {
        0x01 => true,
        0x00 => false,
        _ => {
            return Err(SqliteGisError::InvalidEwkb(
                "invalid byte order marker".to_string(),
            ))
        }
    };
    let raw_type = if little_endian {
        u32::from_le_bytes([iso_wkb[1], iso_wkb[2], iso_wkb[3], iso_wkb[4]])
    } else {
        u32::from_be_bytes([iso_wkb[1], iso_wkb[2], iso_wkb[3], iso_wkb[4]])
    };
    let ewkb_type = raw_type | EWKB_SRID_FLAG;

    // ISO WKB: [byte_order(1)][type_u32(4)][payload...]
    // EWKB:    [byte_order(1)][type_u32_with_flag(4)][srid_i32(4)][payload...]
    let mut out = Vec::with_capacity(iso_wkb.len() + 4);
    out.push(iso_wkb[0]);
    if little_endian {
        out.extend_from_slice(&ewkb_type.to_le_bytes());
        out.extend_from_slice(&srid_val.to_le_bytes());
    } else {
        out.extend_from_slice(&ewkb_type.to_be_bytes());
        out.extend_from_slice(&srid_val.to_be_bytes());
    }
    out.extend_from_slice(&iso_wkb[5..]);
    Ok(out)
}

/// Serialise a `geo::Geometry<f64>` to EWKB with an optional SRID.
///
/// If `srid` is `None`, produces standard ISO WKB (no SRID flag).
///
/// # Example
///
/// ```
/// use geo::{Geometry, Point};
/// use sqlitegis::core::ewkb::{write_ewkb, parse_ewkb};
///
/// let geom = Geometry::Point(Point::new(1.0, 2.0));
/// let blob = write_ewkb(&geom, Some(4326)).unwrap();
/// let (parsed, srid) = parse_ewkb(&blob).unwrap();
/// assert_eq!(srid, Some(4326));
/// ```
pub fn write_ewkb(geom: &Geometry<f64>, srid: Option<i32>) -> Result<Vec<u8>> {
    if let Geometry::Point(p) = geom {
        if p.x().is_nan() && p.y().is_nan() {
            let mut out = Vec::with_capacity(if srid.is_some() { 25 } else { 21 });
            out.push(0x01);
            let mut geom_type = WKB_POINT;
            if srid.is_some() {
                geom_type |= EWKB_SRID_FLAG;
            }
            out.extend_from_slice(&geom_type.to_le_bytes());
            if let Some(srid_val) = srid {
                out.extend_from_slice(&srid_val.to_le_bytes());
            }
            out.extend_from_slice(&f64::NAN.to_le_bytes());
            out.extend_from_slice(&f64::NAN.to_le_bytes());
            return Ok(out);
        }
    }

    // Use geozero to produce ISO WKB (XY only for now)
    let iso_wkb = geom
        .to_wkb(CoordDimensions::xy())
        .map_err(SqliteGisError::Geozero)?;

    if let Some(srid_val) = srid {
        patch_wkb_with_srid(&iso_wkb, srid_val)
    } else {
        Ok(iso_wkb)
    }
}

/// Rewrite the SRID in an existing EWKB blob without re-parsing the geometry.
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::{set_srid, extract_srid};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
/// let updated = set_srid(&blob, 3857).unwrap();
/// assert_eq!(extract_srid(&updated), Some(3857));
/// ```
pub fn set_srid(blob: &[u8], new_srid: i32) -> Result<Vec<u8>> {
    // Validate full payload before rewriting header bytes so malformed EWKB
    // cannot be silently "fixed" by adding/replacing an SRID.
    let header = validate_ewkb_payload(blob)?;

    let mut out = Vec::with_capacity(blob.len() + 4);
    out.push(if header.little_endian { 0x01 } else { 0x00 });

    let raw_type = if header.little_endian {
        u32::from_le_bytes([blob[1], blob[2], blob[3], blob[4]])
    } else {
        u32::from_be_bytes([blob[1], blob[2], blob[3], blob[4]])
    };
    let ewkb_type = raw_type | EWKB_SRID_FLAG;
    if header.little_endian {
        out.extend_from_slice(&ewkb_type.to_le_bytes());
        out.extend_from_slice(&new_srid.to_le_bytes());
    } else {
        out.extend_from_slice(&ewkb_type.to_be_bytes());
        out.extend_from_slice(&new_srid.to_be_bytes());
    }

    // Skip old SRID bytes if they were present, copy remaining payload
    out.extend_from_slice(&blob[header.data_offset..]);
    Ok(out)
}

/// Return a static string naming the variant of a `geo::Geometry` value (for diagnostics).
///
/// ```
/// use sqlitegis::core::ewkb::{geometry_type_name, parse_ewkb};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("POLYGON((0 0, 1 0, 1 1, 0 0))", None).unwrap();
/// let (geom, _srid) = parse_ewkb(&blob).unwrap();
/// assert_eq!(geometry_type_name(&geom), "Polygon");
/// ```
/// Build a `MultiPolygon` EWKB by concatenating the polygon bodies of two
/// inputs without ever decoding them. Both inputs must be `Polygon` or
/// `MultiPolygon` and must share an SRID.
///
/// This is the wire-level fast path for `ST_Union` and `ST_SymDifference`
/// when the inputs have disjoint MBRs: the geometric result IS just the
/// concatenation of the two polygon lists, so we can avoid the round trip
/// through `geo::Geometry` and `geozero`.
///
/// The output is always little-endian. Sub-polygon endianness is preserved
/// for `MultiPolygon` inputs (each sub-polygon WKB has its own endian byte)
/// and matches the input outer endian when wrapping a top-level `Polygon`.
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::{concat_multipolygon_bodies, parse_ewkb_header, WKB_MULTIPOLYGON};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
/// let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", Some(4326)).unwrap();
/// let combined = concat_multipolygon_bodies(&a, &b).unwrap();
/// let hdr = parse_ewkb_header(&combined).unwrap();
/// assert_eq!(hdr.geom_type, WKB_MULTIPOLYGON);
/// assert_eq!(hdr.srid, Some(4326));
/// ```
pub fn concat_multipolygon_bodies(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
    let ha = parse_ewkb_header(a)?;
    let hb = parse_ewkb_header(b)?;
    ensure_xy_only(ha.has_z, ha.has_m)?;
    ensure_xy_only(hb.has_z, hb.has_m)?;
    let srid = ensure_matching_srid(ha.srid, hb.srid)?;

    let mut out = Vec::with_capacity(a.len() + b.len() + 16);
    out.push(0x01u8);
    let type_word: u32 = WKB_MULTIPOLYGON | if srid.is_some() { EWKB_SRID_FLAG } else { 0 };
    out.extend_from_slice(&type_word.to_le_bytes());
    if let Some(s) = srid {
        out.extend_from_slice(&s.to_le_bytes());
    }
    let count_pos = out.len();
    out.extend_from_slice(&0u32.to_le_bytes());

    let count_a = append_subpolygons(&mut out, a, &ha)?;
    let count_b = append_subpolygons(&mut out, b, &hb)?;
    let total = count_a.checked_add(count_b).ok_or_else(|| {
        SqliteGisError::InvalidInput("concat_multipolygon_bodies: polygon count overflow".into())
    })?;
    out[count_pos..count_pos + 4].copy_from_slice(&total.to_le_bytes());

    Ok(out)
}

/// Helper for `concat_multipolygon_bodies`. Appends the sub-polygon WKB
/// bodies of `blob` (which `header` describes) to `out` and returns how
/// many sub-polygons were appended.
fn append_subpolygons(out: &mut Vec<u8>, blob: &[u8], header: &EwkbHeader) -> Result<u32> {
    match header.geom_type {
        WKB_POLYGON => {
            // Wrap the top-level Polygon as a sub-polygon: endian byte +
            // type code (no SRID flag on inner geometries) + body bytes.
            let endian_byte = if header.little_endian { 0x01u8 } else { 0x00u8 };
            out.push(endian_byte);
            let type_bytes = if header.little_endian {
                WKB_POLYGON.to_le_bytes()
            } else {
                WKB_POLYGON.to_be_bytes()
            };
            out.extend_from_slice(&type_bytes);
            out.extend_from_slice(&blob[header.data_offset..]);
            Ok(1)
        }
        WKB_MULTIPOLYGON => {
            if blob.len() < header.data_offset + 4 {
                return Err(SqliteGisError::InvalidEwkb(
                    "MultiPolygon body too short to hold polygon count".into(),
                ));
            }
            let count_bytes: [u8; 4] = blob[header.data_offset..header.data_offset + 4]
                .try_into()
                .expect("slice length checked above");
            let count = if header.little_endian {
                u32::from_le_bytes(count_bytes)
            } else {
                u32::from_be_bytes(count_bytes)
            };
            out.extend_from_slice(&blob[header.data_offset + 4..]);
            Ok(count)
        }
        other => Err(SqliteGisError::InvalidInput(format!(
            "concat_multipolygon_bodies: expected Polygon or MultiPolygon, got {}",
            geom_type_name(other),
        ))),
    }
}

/// Return the human-readable name of a `geo::Geometry` enum variant.
pub fn geometry_type_name(geom: &Geometry<f64>) -> &'static str {
    match geom {
        Geometry::Point(_) => "Point",
        Geometry::Line(_) => "Line",
        Geometry::LineString(_) => "LineString",
        Geometry::Polygon(_) => "Polygon",
        Geometry::MultiPoint(_) => "MultiPoint",
        Geometry::MultiLineString(_) => "MultiLineString",
        Geometry::MultiPolygon(_) => "MultiPolygon",
        Geometry::GeometryCollection(_) => "GeometryCollection",
        Geometry::Rect(_) => "Rect",
        Geometry::Triangle(_) => "Triangle",
    }
}

/// Return a human-readable geometry type name (PostGIS convention).
///
/// # Example
///
/// ```
/// use sqlitegis::core::ewkb::{geom_type_name, WKB_POINT, WKB_POLYGON};
///
/// assert_eq!(geom_type_name(WKB_POINT), "ST_Point");
/// assert_eq!(geom_type_name(WKB_POLYGON), "ST_Polygon");
/// assert_eq!(geom_type_name(999), "ST_Unknown");
/// ```
pub fn geom_type_name(raw_type: u32) -> &'static str {
    match raw_type & 0x1FFF_FFFF {
        WKB_POINT => "ST_Point",
        WKB_LINESTRING => "ST_LineString",
        WKB_POLYGON => "ST_Polygon",
        WKB_MULTIPOINT => "ST_MultiPoint",
        WKB_MULTILINESTRING => "ST_MultiLineString",
        WKB_MULTIPOLYGON => "ST_MultiPolygon",
        WKB_GEOMETRYCOLLECTION => "ST_GeometryCollection",
        _ => "ST_Unknown",
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::functions::io::geom_from_text;

    #[test]
    fn header_blob_too_short() {
        assert!(parse_ewkb_header(&[0x01, 0x02]).is_err());
        assert!(parse_ewkb_header(&[]).is_err());
    }

    #[test]
    fn header_big_endian_point_without_srid() {
        // big-endian: byte-order + type(1) + x(1.0) + y(2.0)
        let mut blob = vec![0x00];
        blob.extend_from_slice(&WKB_POINT.to_be_bytes());
        blob.extend_from_slice(&1.0f64.to_be_bytes());
        blob.extend_from_slice(&2.0f64.to_be_bytes());

        let hdr = parse_ewkb_header(&blob).unwrap();
        assert_eq!(hdr.geom_type, WKB_POINT);
        assert_eq!(hdr.srid, None);
        assert!(!hdr.has_z);
        assert!(!hdr.has_m);
        assert_eq!(hdr.data_offset, 5);
        assert!(!hdr.little_endian);
    }

    #[test]
    fn header_big_endian_point_with_srid() {
        // big-endian EWKB type with SRID flag.
        let mut blob = vec![0x00];
        let typ = WKB_POINT | EWKB_SRID_FLAG;
        blob.extend_from_slice(&typ.to_be_bytes());
        blob.extend_from_slice(&4326i32.to_be_bytes());
        blob.extend_from_slice(&1.0f64.to_be_bytes());
        blob.extend_from_slice(&2.0f64.to_be_bytes());

        let hdr = parse_ewkb_header(&blob).unwrap();
        assert_eq!(hdr.geom_type, WKB_POINT);
        assert_eq!(hdr.srid, Some(4326));
        assert_eq!(hdr.data_offset, 9);
        assert!(!hdr.little_endian);
    }

    #[test]
    fn header_invalid_byte_order_marker() {
        assert!(parse_ewkb_header(&[0x02, 0x01, 0x00, 0x00, 0x00]).is_err());
    }

    #[test]
    fn header_srid_flag_but_truncated() {
        // byte order + type word with SRID flag, but no SRID bytes
        let mut blob = vec![0x01];
        let raw_type = WKB_POINT | EWKB_SRID_FLAG;
        blob.extend_from_slice(&raw_type.to_le_bytes());
        assert!(parse_ewkb_header(&blob).is_err());
    }

    #[test]
    fn header_valid_point_with_srid() {
        let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
        let hdr = parse_ewkb_header(&blob).unwrap();
        assert_eq!(hdr.geom_type, WKB_POINT);
        assert_eq!(hdr.srid, Some(4326));
        assert!(!hdr.has_z);
        assert!(!hdr.has_m);
        assert_eq!(hdr.data_offset, 9); // 1 + 4 + 4
    }

    #[test]
    fn header_valid_point_without_srid() {
        let blob = geom_from_text("POINT(1 2)", None).unwrap();
        let hdr = parse_ewkb_header(&blob).unwrap();
        assert_eq!(hdr.geom_type, WKB_POINT);
        assert_eq!(hdr.srid, None);
        assert_eq!(hdr.data_offset, 5); // 1 + 4
    }

    #[test]
    fn extract_srid_empty_blob() {
        assert_eq!(extract_srid(&[]), None);
    }

    #[test]
    fn extract_srid_malformed_blob() {
        assert_eq!(extract_srid(&[0xFF, 0xFF]), None);
    }

    #[test]
    fn write_ewkb_without_srid() {
        let geom = geo::Geometry::Point(geo::Point::new(1.0, 2.0));
        let blob = write_ewkb(&geom, None).unwrap();
        assert_eq!(extract_srid(&blob), None);
        // ISO WKB: byte order(1) + type(4) + x(8) + y(8) = 21 bytes
        assert_eq!(blob.len(), 21);
    }

    #[test]
    fn write_ewkb_with_srid() {
        let geom = geo::Geometry::Point(geo::Point::new(1.0, 2.0));
        let blob = write_ewkb(&geom, Some(4326)).unwrap();
        assert_eq!(extract_srid(&blob), Some(4326));
        // EWKB: byte order(1) + type(4) + srid(4) + x(8) + y(8) = 25 bytes
        assert_eq!(blob.len(), 25);
    }

    #[test]
    fn set_srid_replaces_existing() {
        let blob = geom_from_text("POINT(1 2)", Some(4326)).unwrap();
        let updated = set_srid(&blob, 3857).unwrap();
        assert_eq!(extract_srid(&updated), Some(3857));
        // Geometry should still parse correctly
        let (_, srid) = parse_ewkb(&updated).unwrap();
        assert_eq!(srid, Some(3857));
    }

    #[test]
    fn set_srid_adds_to_blob_without_srid() {
        let blob = geom_from_text("POINT(1 2)", None).unwrap();
        let updated = set_srid(&blob, 4326).unwrap();
        assert_eq!(extract_srid(&updated), Some(4326));
    }

    #[test]
    fn set_srid_rejects_truncated_point_payload() {
        // byte-order + Point type + only one coordinate (x), missing y
        let mut truncated = vec![0x01];
        truncated.extend_from_slice(&WKB_POINT.to_le_bytes());
        truncated.extend_from_slice(&1.0f64.to_le_bytes());

        set_srid(&truncated, 4326).expect_err("truncated payload must error");
    }

    #[test]
    fn set_srid_rejects_malformed_non_empty_payload() {
        // byte-order + LineString type + point count, but no coordinate payload
        let mut malformed = vec![0x01];
        malformed.extend_from_slice(&WKB_LINESTRING.to_le_bytes());
        malformed.extend_from_slice(&1u32.to_le_bytes());

        set_srid(&malformed, 3857).expect_err("malformed payload must error");
    }

    #[test]
    fn set_srid_allows_valid_empty_point_blob() {
        let empty = geom_from_text("POINT EMPTY", None).unwrap();
        let updated = set_srid(&empty, 4326).unwrap();

        let (geom, srid) = parse_ewkb(&updated).unwrap();
        assert_eq!(srid, Some(4326));
        match geom {
            Geometry::Point(p) => {
                assert!(p.x().is_nan());
                assert!(p.y().is_nan());
            }
            other => panic!("expected Point, got {other:?}"),
        }
    }

    #[test]
    fn geom_type_name_all_types() {
        assert_eq!(geom_type_name(WKB_POINT), "ST_Point");
        assert_eq!(geom_type_name(WKB_LINESTRING), "ST_LineString");
        assert_eq!(geom_type_name(WKB_POLYGON), "ST_Polygon");
        assert_eq!(geom_type_name(WKB_MULTIPOINT), "ST_MultiPoint");
        assert_eq!(geom_type_name(WKB_MULTILINESTRING), "ST_MultiLineString");
        assert_eq!(geom_type_name(WKB_MULTIPOLYGON), "ST_MultiPolygon");
        assert_eq!(
            geom_type_name(WKB_GEOMETRYCOLLECTION),
            "ST_GeometryCollection"
        );
        assert_eq!(geom_type_name(42), "ST_Unknown");
    }

    #[test]
    fn parse_ewkb_roundtrip() {
        let blob = geom_from_text("LINESTRING(0 0, 1 1, 2 2)", Some(4326)).unwrap();
        let (geom, srid) = parse_ewkb(&blob).unwrap();
        assert_eq!(srid, Some(4326));
        let blob2 = write_ewkb(&geom, srid).unwrap();
        let (geom2, srid2) = parse_ewkb(&blob2).unwrap();
        assert_eq!(srid, srid2);
        assert_eq!(format!("{geom:?}"), format!("{geom2:?}"));
    }

    #[test]
    fn parse_big_endian_ewkb_point() {
        let mut blob = vec![0x00];
        let typ = WKB_POINT | EWKB_SRID_FLAG;
        blob.extend_from_slice(&typ.to_be_bytes());
        blob.extend_from_slice(&4326i32.to_be_bytes());
        blob.extend_from_slice(&10.0f64.to_be_bytes());
        blob.extend_from_slice(&(-20.0f64).to_be_bytes());

        let (geom, srid) = parse_ewkb(&blob).unwrap();
        assert_eq!(srid, Some(4326));
        assert_eq!(
            geom,
            Geometry::Point(geo::Point::new(10.0, -20.0)),
            "big-endian EWKB should parse into XY geometry"
        );
    }

    #[test]
    fn parse_ewkb_with_zm_point_is_rejected() {
        let mut blob = vec![0x01];
        let typ = WKB_POINT | EWKB_Z_FLAG | EWKB_M_FLAG;
        blob.extend_from_slice(&typ.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&2.0f64.to_le_bytes());
        blob.extend_from_slice(&3.0f64.to_le_bytes()); // Z
        blob.extend_from_slice(&4.0f64.to_le_bytes()); // M

        let err = parse_ewkb(&blob).expect_err("Z/M payloads must not be flattened to XY");
        assert!(format!("{err}").contains("unsupported coordinate dimensions"));
    }

    #[test]
    fn set_srid_preserves_big_endian_header_order() {
        let mut blob = vec![0x00];
        blob.extend_from_slice(&WKB_POINT.to_be_bytes());
        blob.extend_from_slice(&7.0f64.to_be_bytes());
        blob.extend_from_slice(&8.0f64.to_be_bytes());

        let updated = set_srid(&blob, 4326).unwrap();
        assert_eq!(updated[0], 0x00, "byte-order marker must stay big-endian");
        assert_eq!(extract_srid(&updated), Some(4326));

        let (geom, srid) = parse_ewkb(&updated).unwrap();
        assert_eq!(srid, Some(4326));
        assert_eq!(geom, Geometry::Point(geo::Point::new(7.0, 8.0)));
    }

    #[test]
    fn parse_ewkb_invalid_blob() {
        assert!(parse_ewkb(&[0x01, 0x02]).is_err());
    }

    #[test]
    fn ensure_matching_srid_accepts_equal() {
        assert_eq!(
            ensure_matching_srid(Some(4326), Some(4326)).unwrap(),
            Some(4326)
        );
        assert_eq!(ensure_matching_srid(None, None).unwrap(), None);
    }

    #[test]
    fn ensure_matching_srid_treats_unknown_and_zero_as_compatible() {
        assert_eq!(ensure_matching_srid(None, Some(0)).unwrap(), Some(0));
        assert_eq!(ensure_matching_srid(Some(0), None).unwrap(), Some(0));
    }

    #[test]
    fn ensure_matching_srid_rejects_mismatch() {
        assert!(ensure_matching_srid(Some(4326), Some(3857)).is_err());
        assert!(ensure_matching_srid(Some(4326), None).is_err());
    }

    #[test]
    fn parse_ewkb_pair_requires_matching_srid() {
        let a = crate::core::functions::io::geom_from_text("POINT(0 0)", Some(4326)).unwrap();
        let b = crate::core::functions::io::geom_from_text("POINT(1 1)", Some(4326)).unwrap();
        assert!(parse_ewkb_pair(&a, &b).is_ok());

        let mixed = crate::core::functions::io::geom_from_text("POINT(1 1)", Some(3857)).unwrap();
        assert!(parse_ewkb_pair(&a, &mixed).is_err());
    }

    #[test]
    fn parse_ewkb_pair_accepts_unknown_and_zero_srid() {
        let a = crate::core::functions::io::geom_from_text("POINT(0 0)", None).unwrap();
        let b = crate::core::functions::io::geom_from_text("POINT(1 1)", Some(0)).unwrap();
        let pair = parse_ewkb_pair(&a, &b).expect("None and SRID=0 should be compatible");
        assert_eq!(pair.2, Some(0));
    }

    #[test]
    fn parse_empty_point() {
        let blob =
            write_ewkb(&Geometry::Point(Point::new(f64::NAN, f64::NAN)), Some(4326)).unwrap();
        let (geom, srid) = parse_ewkb(&blob).unwrap();
        assert_eq!(srid, Some(4326));
        match geom {
            Geometry::Point(p) => {
                assert!(p.x().is_nan());
                assert!(p.y().is_nan());
            }
            other => panic!("expected point, got {other:?}"),
        }
        assert!(is_empty_point_blob(&blob).unwrap());
    }

    #[test]
    fn patch_wkb_with_srid_little_endian() {
        let mut iso = vec![0x01];
        iso.extend_from_slice(&WKB_POINT.to_le_bytes());
        iso.extend_from_slice(&1.0f64.to_le_bytes());
        iso.extend_from_slice(&2.0f64.to_le_bytes());

        let ewkb = patch_wkb_with_srid(&iso, 4326).unwrap();
        let hdr = parse_ewkb_header(&ewkb).unwrap();
        assert!(hdr.little_endian);
        assert_eq!(hdr.srid, Some(4326));
    }

    #[test]
    fn patch_wkb_with_srid_big_endian() {
        let mut iso = vec![0x00];
        iso.extend_from_slice(&WKB_POINT.to_be_bytes());
        iso.extend_from_slice(&1.0f64.to_be_bytes());
        iso.extend_from_slice(&2.0f64.to_be_bytes());

        let ewkb = patch_wkb_with_srid(&iso, 4326).unwrap();
        let hdr = parse_ewkb_header(&ewkb).unwrap();
        assert!(!hdr.little_endian);
        assert_eq!(hdr.srid, Some(4326));

        let (geom, srid) = parse_ewkb(&ewkb).unwrap();
        assert_eq!(srid, Some(4326));
        assert_eq!(geom, Geometry::Point(Point::new(1.0, 2.0)));
    }

    #[test]
    fn patch_wkb_with_srid_rejects_short_input() {
        assert!(patch_wkb_with_srid(&[0x01], 4326).is_err());
    }

    #[test]
    fn patch_wkb_with_srid_rejects_invalid_byte_order_marker() {
        let mut blob = vec![0x02];
        blob.extend_from_slice(&WKB_POINT.to_le_bytes());
        let err = patch_wkb_with_srid(&blob, 4326).expect_err("must reject 0x02");
        assert!(
            matches!(err, SqliteGisError::InvalidEwkb(ref s) if s.contains("byte order marker"))
        );
    }

    #[test]
    fn validate_ewkb_payload_accepts_valid_blob() {
        let blob = crate::core::functions::io::geom_from_text("LINESTRING(0 0,1 1)", Some(4326))
            .expect("valid EWKB");
        let header = validate_ewkb_payload(&blob).expect("valid payload");
        assert_eq!(header.geom_type, WKB_LINESTRING);
        assert_eq!(header.srid, Some(4326));
    }

    #[test]
    fn validate_ewkb_payload_rejects_malformed_non_empty_blob() {
        // byte-order + LineString type + point count, but no coordinate payload
        let mut malformed = vec![0x01];
        malformed.extend_from_slice(&WKB_LINESTRING.to_le_bytes());
        malformed.extend_from_slice(&1u32.to_le_bytes());

        validate_ewkb_payload(&malformed).expect_err("malformed payload must error");
    }

    #[test]
    fn validate_xy_ewkb_payload_rejects_zm_blob() {
        let mut blob = vec![0x01];
        let typ = WKB_POINT | EWKB_Z_FLAG | EWKB_M_FLAG;
        blob.extend_from_slice(&typ.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&2.0f64.to_le_bytes());
        blob.extend_from_slice(&3.0f64.to_le_bytes());
        blob.extend_from_slice(&4.0f64.to_le_bytes());

        let err = validate_xy_ewkb_payload(&blob).expect_err("Z/M payload must be rejected");
        assert!(format!("{err}").contains("unsupported coordinate dimensions"));
    }

    // -----------------------------------------------------------------
    // extract_mbr coverage
    // -----------------------------------------------------------------

    /// Assert that `extract_mbr` agrees with the reference path
    /// (`parse_ewkb` + `geo::BoundingRect`) on `wkt`. Both should be
    /// `None` for empty geometries, or matching `Rect` for non-empty.
    fn assert_mbr_matches_reference(wkt: &str) {
        use geo::BoundingRect;

        let blob = geom_from_text(wkt, None).expect("seed blob from WKT");
        let fast = extract_mbr(&blob).expect("fast MBR path must succeed on valid blob");
        let (geom, _) = parse_ewkb(&blob).expect("reference parse must succeed");
        let reference = geom.bounding_rect();

        match (fast, reference) {
            (None, None) => {}
            (Some(f), Some(r)) => {
                assert!(
                    (f.min().x - r.min().x).abs() < 1e-12
                        && (f.min().y - r.min().y).abs() < 1e-12
                        && (f.max().x - r.max().x).abs() < 1e-12
                        && (f.max().y - r.max().y).abs() < 1e-12,
                    "MBR mismatch for {wkt:?}: fast={f:?}, reference={r:?}",
                );
            }
            other => panic!("MBR presence mismatch for {wkt:?}: {other:?}"),
        }
    }

    #[test]
    fn extract_mbr_point_matches_reference() {
        assert_mbr_matches_reference("POINT(1 2)");
        assert_mbr_matches_reference("POINT(-180 -90)");
        assert_mbr_matches_reference("POINT(180 90)");
    }

    #[test]
    fn extract_mbr_empty_point_returns_none() {
        let blob = geom_from_text("POINT EMPTY", None).expect("seed");
        assert!(extract_mbr(&blob).expect("ok").is_none());
    }

    #[test]
    fn extract_mbr_linestring_matches_reference() {
        assert_mbr_matches_reference("LINESTRING(0 0, 10 0, 10 5, 0 5)");
        assert_mbr_matches_reference("LINESTRING(-5 -10, 5 10)");
    }

    #[test]
    fn extract_mbr_polygon_with_hole_matches_reference() {
        // Outer ring + inner hole. The hole's vertices are within the outer
        // ring's bbox so the MBR is the outer ring's extent.
        assert_mbr_matches_reference(
            "POLYGON((0 0, 10 0, 10 10, 0 10, 0 0), (2 2, 4 2, 4 4, 2 4, 2 2))",
        );
    }

    #[test]
    fn extract_mbr_multipoint_matches_reference() {
        assert_mbr_matches_reference("MULTIPOINT((1 2), (5 5), (-3 4))");
    }

    #[test]
    fn extract_mbr_multilinestring_matches_reference() {
        assert_mbr_matches_reference("MULTILINESTRING((0 0, 1 1), (5 5, 6 7, -2 3))");
    }

    #[test]
    fn extract_mbr_multipolygon_matches_reference() {
        assert_mbr_matches_reference(
            "MULTIPOLYGON(((0 0, 1 0, 1 1, 0 1, 0 0)), ((10 10, 20 10, 20 20, 10 20, 10 10)))",
        );
    }

    #[test]
    fn extract_mbr_geometrycollection_matches_reference() {
        assert_mbr_matches_reference(
            "GEOMETRYCOLLECTION(POINT(1 2), LINESTRING(0 0, 5 5), POLYGON((0 0, 2 0, 2 2, 0 2, 0 0)))",
        );
    }

    /// Build an EWKB nesting `wrappers` GeometryCollections around an
    /// innermost empty GeometryCollection. The outermost is at depth 0, so the
    /// innermost sits at depth `wrappers`.
    fn nested_geometrycollection(wrappers: usize) -> Vec<u8> {
        let mut blob = vec![0x01u8];
        blob.extend_from_slice(&WKB_GEOMETRYCOLLECTION.to_le_bytes());
        blob.extend_from_slice(&0u32.to_le_bytes());
        for _ in 0..wrappers {
            let mut outer = Vec::with_capacity(blob.len() + 9);
            outer.push(0x01u8);
            outer.extend_from_slice(&WKB_GEOMETRYCOLLECTION.to_le_bytes());
            outer.extend_from_slice(&1u32.to_le_bytes());
            outer.extend_from_slice(&blob);
            blob = outer;
        }
        blob
    }

    #[test]
    fn deeply_nested_ewkb_is_rejected_not_overflowed() {
        // A blob with ~100k nested GeometryCollections used to overflow the
        // stack in both our walker and geozero's decoder. Every parser must
        // now reject it with an error instead of aborting the process.
        let bomb = nested_geometrycollection(100_000);
        assert!(matches!(
            extract_mbr(&bomb),
            Err(SqliteGisError::InvalidEwkb(_))
        ));
        assert!(matches!(
            parse_ewkb(&bomb),
            Err(SqliteGisError::InvalidEwkb(_))
        ));
        assert!(matches!(
            validate_ewkb_payload(&bomb),
            Err(SqliteGisError::InvalidEwkb(_))
        ));
        assert!(matches!(
            ensure_ewkb_nesting_ok(&bomb),
            Err(SqliteGisError::InvalidEwkb(_))
        ));
    }

    #[test]
    fn nesting_depth_boundary_is_inclusive() {
        // The cap admits up to MAX_NESTING_DEPTH levels below the root and
        // rejects one deeper, on both the MBR walker and the geozero guard.
        let at_limit = nested_geometrycollection(MAX_NESTING_DEPTH);
        extract_mbr(&at_limit).expect("nesting at the limit must be accepted");
        ensure_ewkb_nesting_ok(&at_limit).expect("nesting at the limit must be accepted");

        let over_limit = nested_geometrycollection(MAX_NESTING_DEPTH + 1);
        assert!(extract_mbr(&over_limit).is_err());
        assert!(ensure_ewkb_nesting_ok(&over_limit).is_err());
    }

    #[test]
    fn malformed_z_blob_does_not_oom() {
        // Fuzzer-reduced EWKB: a Z-flagged MultiPolygon whose crafted nested
        // headers desync this crate's structural walk from geozero's decoder,
        // sliding a ~2.1-billion element count into a position where `to_geo`
        // pre-allocates tens of gigabytes. The structural validator must not
        // call `to_geo` (so it returns without OOM), and the XY validator must
        // reject the Z geometry before any decode.
        const BLOB: &[u8] = &[
            1, 6, 0, 0, 128, 4, 0, 0, 0, 0, 0, 0, 0, 1, 6, 128, 0, 255, 254, 255, 127, 0, 6, 0, 0,
            131, 93, 0, 1, 1, 0, 0, 0, 0, 1, 6, 0, 1, 0, 64, 1, 6, 0, 1, 1, 0, 128, 93, 0, 1, 1, 0,
            0, 0, 0, 1, 6, 0, 0, 1, 1, 0, 128, 0, 6, 0, 0, 128, 93, 0, 1, 1, 0, 0, 0, 0, 1, 6, 0,
            45, 250, 255, 255, 0, 6, 0, 1, 1, 0, 0, 0, 247, 1, 6, 0, 0, 0, 0, 0, 0, 1, 6, 0, 0,
            128,
        ];
        // Returns (Ok or Err) rather than aborting the process: reaching this
        // line at all proves no OOM occurred.
        let _ = validate_ewkb_payload(BLOB);
        assert!(
            validate_xy_ewkb_payload(BLOB).is_err(),
            "Z geometry must be rejected before the geozero decode"
        );
    }

    #[test]
    fn shallow_nesting_round_trips() {
        let blob = geom_from_text(
            "GEOMETRYCOLLECTION(POINT(1 2), LINESTRING(0 0,1 1))",
            Some(4326),
        )
        .expect("seed");
        ensure_ewkb_nesting_ok(&blob).expect("shallow nesting is fine");
        let (_geom, srid) = parse_ewkb(&blob).expect("shallow nesting parses");
        assert_eq!(srid, Some(4326));
    }

    #[test]
    fn extract_mbr_respects_big_endian_byte_order() {
        // Manually build a big-endian POINT(3 4) blob.
        let mut blob = vec![0x00];
        blob.extend_from_slice(&WKB_POINT.to_be_bytes());
        blob.extend_from_slice(&3.0f64.to_be_bytes());
        blob.extend_from_slice(&4.0f64.to_be_bytes());

        let mbr = extract_mbr(&blob).expect("ok").expect("non-empty");
        assert_eq!(mbr.min().x, 3.0);
        assert_eq!(mbr.min().y, 4.0);
        assert_eq!(mbr.max().x, 3.0);
        assert_eq!(mbr.max().y, 4.0);
    }

    #[test]
    fn extract_mbr_respects_srid_flag_offset() {
        // POINT(7 8) with SRID flag: header is 9 bytes (1 + 4 + 4), coords follow.
        let blob = geom_from_text("POINT(7 8)", Some(4326)).expect("seed");
        let mbr = extract_mbr(&blob).expect("ok").expect("non-empty");
        assert_eq!(mbr.min().x, 7.0);
        assert_eq!(mbr.max().y, 8.0);
    }

    #[test]
    fn extract_mbr_rejects_truncated_point_blob() {
        // Header says POINT but no coordinate bytes follow.
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_POINT.to_le_bytes());
        assert!(extract_mbr(&blob).is_err());
    }

    #[test]
    fn extract_mbr_rejects_truncated_polygon_blob() {
        // Polygon header says 1 ring with 4 points, but no coords follow.
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_POLYGON.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes()); // nrings
        blob.extend_from_slice(&4u32.to_le_bytes()); // npoints
        assert!(extract_mbr(&blob).is_err());
    }

    // -- concat_multipolygon_bodies ---------------------------------

    fn area_round_trip(blob: &[u8]) -> f64 {
        use crate::core::functions::measurement::st_area;
        st_area(blob).expect("decode and area")
    }

    fn poly_count(blob: &[u8]) -> u32 {
        // Both Polygon and MultiPolygon: decode then count outer rings.
        let (g, _) = parse_ewkb(blob).expect("decode");
        match g {
            Geometry::Polygon(_) => 1,
            Geometry::MultiPolygon(mp) => mp.0.len() as u32,
            other => panic!("expected Polygon or MultiPolygon, got {other:?}"),
        }
    }

    #[test]
    fn concat_two_polygons_no_srid_yields_multipolygon() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        let hdr = parse_ewkb_header(&combined).unwrap();
        assert_eq!(hdr.geom_type, WKB_MULTIPOLYGON);
        assert_eq!(hdr.srid, None);
        assert_eq!(poly_count(&combined), 2);
        assert!((area_round_trip(&combined) - 2.0).abs() < 1e-10);
    }

    #[test]
    fn concat_two_polygons_with_srid_preserves_srid() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", Some(4326)).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        let hdr = parse_ewkb_header(&combined).unwrap();
        assert_eq!(hdr.geom_type, WKB_MULTIPOLYGON);
        assert_eq!(hdr.srid, Some(4326));
        assert_eq!(poly_count(&combined), 2);
    }

    #[test]
    fn concat_polygon_with_multipolygon_combines_counts() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let b = geom_from_text(
            "MULTIPOLYGON(((10 10,11 10,11 11,10 11,10 10)),((20 20,21 20,21 21,20 21,20 20)))",
            None,
        )
        .unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 3);
        assert!((area_round_trip(&combined) - 3.0).abs() < 1e-10);
    }

    #[test]
    fn concat_two_multipolygons_combines_counts() {
        let a = geom_from_text(
            "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 0,3 0,3 1,2 1,2 0)))",
            None,
        )
        .unwrap();
        let b = geom_from_text(
            "MULTIPOLYGON(((10 10,11 10,11 11,10 11,10 10)),((20 20,21 20,21 21,20 21,20 20)))",
            None,
        )
        .unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 4);
        assert!((area_round_trip(&combined) - 4.0).abs() < 1e-10);
    }

    #[test]
    fn concat_empty_multipolygon_with_polygon_yields_single_polygon_multipoly() {
        let a = geom_from_text("MULTIPOLYGON EMPTY", None).unwrap();
        let b = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 1);
        assert!((area_round_trip(&combined) - 1.0).abs() < 1e-10);
    }

    #[test]
    fn concat_rejects_srid_mismatch() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", Some(3857)).unwrap();
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    #[test]
    fn concat_rejects_non_polygon_input() {
        let a = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        let b = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    // -- edge cases for concat_multipolygon_bodies ---------------------

    /// Hand-craft a big-endian Polygon EWKB for the unit square
    /// (0,0)->(1,0)->(1,1)->(0,1)->(0,0).
    fn be_unit_square_polygon(srid: Option<i32>) -> Vec<u8> {
        let mut blob = vec![0x00u8]; // big-endian marker
        let type_word = WKB_POLYGON | if srid.is_some() { EWKB_SRID_FLAG } else { 0 };
        blob.extend_from_slice(&type_word.to_be_bytes());
        if let Some(s) = srid {
            blob.extend_from_slice(&s.to_be_bytes());
        }
        blob.extend_from_slice(&1u32.to_be_bytes()); // numRings
        blob.extend_from_slice(&5u32.to_be_bytes()); // numPoints
        for (x, y) in [(0.0, 0.0), (1.0, 0.0), (1.0, 1.0), (0.0, 1.0), (0.0, 0.0)] {
            blob.extend_from_slice(&f64::to_be_bytes(x));
            blob.extend_from_slice(&f64::to_be_bytes(y));
        }
        blob
    }

    /// Hand-craft a big-endian MultiPolygon EWKB containing one unit
    /// square offset by `(dx, dy)`.
    fn be_unit_square_multipolygon(dx: f64, dy: f64, srid: Option<i32>) -> Vec<u8> {
        let mut blob = vec![0x00u8];
        let type_word = WKB_MULTIPOLYGON | if srid.is_some() { EWKB_SRID_FLAG } else { 0 };
        blob.extend_from_slice(&type_word.to_be_bytes());
        if let Some(s) = srid {
            blob.extend_from_slice(&s.to_be_bytes());
        }
        blob.extend_from_slice(&1u32.to_be_bytes()); // numPolygons
                                                     // Sub-polygon: independent endian byte + type + rings.
        blob.push(0x00u8);
        blob.extend_from_slice(&WKB_POLYGON.to_be_bytes());
        blob.extend_from_slice(&1u32.to_be_bytes()); // numRings
        blob.extend_from_slice(&5u32.to_be_bytes()); // numPoints
        for (x, y) in [
            (dx, dy),
            (dx + 1.0, dy),
            (dx + 1.0, dy + 1.0),
            (dx, dy + 1.0),
            (dx, dy),
        ] {
            blob.extend_from_slice(&f64::to_be_bytes(x));
            blob.extend_from_slice(&f64::to_be_bytes(y));
        }
        blob
    }

    #[test]
    fn concat_big_endian_polygon_inputs_preserve_sub_polygon_endianness() {
        let a = be_unit_square_polygon(None);
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        // Outer wrapper is always little-endian.
        assert_eq!(combined[0], 0x01);
        let hdr = parse_ewkb_header(&combined).unwrap();
        assert_eq!(hdr.geom_type, WKB_MULTIPOLYGON);
        // Decode round-trip: area = 2.0 (two unit squares).
        assert!((area_round_trip(&combined) - 2.0).abs() < 1e-10);
        assert_eq!(poly_count(&combined), 2);
    }

    #[test]
    fn concat_big_endian_multipolygon_input_reads_count_correctly() {
        let a = be_unit_square_multipolygon(0.0, 0.0, None);
        let b = be_unit_square_multipolygon(10.0, 0.0, None);
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 2);
        assert!((area_round_trip(&combined) - 2.0).abs() < 1e-10);
    }

    #[test]
    fn concat_mixed_endianness_inputs() {
        let a = be_unit_square_polygon(Some(4326));
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", Some(4326)).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        let hdr = parse_ewkb_header(&combined).unwrap();
        assert_eq!(hdr.srid, Some(4326));
        assert_eq!(poly_count(&combined), 2);
        assert!((area_round_trip(&combined) - 2.0).abs() < 1e-10);
    }

    #[test]
    fn concat_rejects_truncated_multipolygon_input() {
        // Header says MultiPolygon but no polygon-count u32 follows.
        let mut a = vec![0x01u8];
        a.extend_from_slice(&WKB_MULTIPOLYGON.to_le_bytes());
        // Deliberately omit the 4-byte count.
        let b = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    #[test]
    fn concat_rejects_z_dimension_inputs() {
        let mut a = vec![0x01u8];
        let type_word = WKB_POLYGON | EWKB_Z_FLAG;
        a.extend_from_slice(&type_word.to_le_bytes());
        a.extend_from_slice(&1u32.to_le_bytes());
        a.extend_from_slice(&4u32.to_le_bytes());
        // Coords don't matter here, header validation fires first.
        for _ in 0..(4 * 3) {
            a.extend_from_slice(&0f64.to_le_bytes());
        }
        let b = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let err = concat_multipolygon_bodies(&a, &b).unwrap_err();
        assert!(
            matches!(
                err,
                SqliteGisError::UnsupportedDimensions { dimensions: "Z" }
            ),
            "expected Z rejection, got {err:?}"
        );
    }

    #[test]
    fn concat_rejects_m_dimension_inputs() {
        let mut b = vec![0x01u8];
        let type_word = WKB_POLYGON | EWKB_M_FLAG;
        b.extend_from_slice(&type_word.to_le_bytes());
        b.extend_from_slice(&1u32.to_le_bytes());
        b.extend_from_slice(&4u32.to_le_bytes());
        for _ in 0..(4 * 3) {
            b.extend_from_slice(&0f64.to_le_bytes());
        }
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    #[test]
    fn concat_rejects_malformed_header_blob_a() {
        // 3-byte blob: too short for any EWKB header.
        let a = vec![0x01, 0x03, 0x00];
        let b = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    #[test]
    fn concat_rejects_malformed_header_blob_b() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let b = vec![0x42]; // invalid byte-order marker
        assert!(concat_multipolygon_bodies(&a, &b).is_err());
    }

    #[test]
    fn concat_polygon_with_interior_ring_preserves_hole() {
        // Outer 4x4 square with a 1x1 inner hole at (1,1)-(2,2).
        let a =
            geom_from_text("POLYGON((0 0,4 0,4 4,0 4,0 0),(1 1,2 1,2 2,1 2,1 1))", None).unwrap();
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 2);
        // Outer-with-hole: 16 - 1 = 15. Plus 1x1 = 16.
        assert!((area_round_trip(&combined) - 16.0).abs() < 1e-10);
    }

    #[test]
    fn concat_polygon_and_empty_multipolygon_yields_single_polygon() {
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let b = geom_from_text("MULTIPOLYGON EMPTY", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 1);
        assert!((area_round_trip(&combined) - 1.0).abs() < 1e-10);
    }

    #[test]
    fn concat_two_empty_multipolygons_yields_empty_multipolygon() {
        let a = geom_from_text("MULTIPOLYGON EMPTY", None).unwrap();
        let b = geom_from_text("MULTIPOLYGON EMPTY", None).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        let hdr = parse_ewkb_header(&combined).unwrap();
        assert_eq!(hdr.geom_type, WKB_MULTIPOLYGON);
        assert_eq!(poly_count(&combined), 0);
    }

    #[test]
    fn concat_one_null_srid_one_some_srid_treated_as_compatible() {
        // ensure_matching_srid treats None/Some(0) as compatible. Verify
        // that passes through to a successful concat.
        let a = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        let b = geom_from_text("POLYGON((10 10,11 10,11 11,10 11,10 10))", Some(0)).unwrap();
        let combined = concat_multipolygon_bodies(&a, &b).unwrap();
        assert_eq!(poly_count(&combined), 2);
    }
    // -- Hardening: validate_xy_ewkb_payload geozero decode path (line 173) --

    #[test]
    fn validate_xy_ewkb_payload_decodes_through_geozero() {
        // A valid XY point that is NOT empty triggers the geozero decode at line 172-173.
        let blob = geom_from_text("POINT(5 10)", Some(4326)).unwrap();
        let hdr = validate_xy_ewkb_payload(&blob).unwrap();
        assert_eq!(hdr.srid, Some(4326));
        assert!(!hdr.has_z && !hdr.has_m);
    }

    // -- Hardening: read_u32_at truncated (lines 448-450) --

    #[test]
    fn read_u32_at_rejects_truncated_blob() {
        // Polygon header with no ring count bytes: only 5 bytes total.
        let blob: Vec<u8> = vec![0x01, 0x03, 0x00, 0x00, 0x00];
        assert!(validate_ewkb_payload(&blob).is_err());
    }

    // -- Hardening: advance_past overflow (lines 468-469) --

    #[test]
    fn advance_past_catches_offset_overflow() {
        // LineString with u32::MAX point count: count * 16 overflows.
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_LINESTRING.to_le_bytes());
        blob.extend_from_slice(&u32::MAX.to_le_bytes());
        assert!(validate_ewkb_payload(&blob).is_err());
    }

    // -- Hardening: validate_nesting nested header truncated (lines 539-541) --

    #[test]
    fn validate_nesting_rejects_truncated_nested_header() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_MULTIPOINT.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        assert!(validate_ewkb_payload(&blob).is_err());
    }

    // -- Hardening: validate_nesting invalid byte-order marker (lines 546-549) --

    #[test]
    fn validate_nesting_rejects_invalid_nested_byte_order() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_MULTIPOINT.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        blob.push(0xFF);
        blob.extend_from_slice(&WKB_POINT.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&2.0f64.to_le_bytes());
        assert!(validate_ewkb_payload(&blob).is_err());
    }

    // -- Hardening: validate_nesting unsupported type (lines 582-585) --

    #[test]
    fn validate_nesting_rejects_unknown_type_code() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&0u32.to_le_bytes());
        assert!(validate_ewkb_payload(&blob).is_err());
    }

    // -- Hardening: validate_nesting nested SRID flag (line 569) --

    #[test]
    fn validate_nesting_skips_nested_srid() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_GEOMETRYCOLLECTION.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        blob.push(0x01);
        blob.extend_from_slice(&(WKB_POINT | EWKB_SRID_FLAG).to_le_bytes());
        blob.extend_from_slice(&4326i32.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&2.0f64.to_le_bytes());
        assert!(validate_ewkb_payload(&blob).is_ok());
    }

    // -- Hardening: walk_for_mbr errors --

    #[test]
    fn walk_for_mbr_rejects_truncated_nested_header() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_MULTIPOINT.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        assert!(extract_mbr(&blob).is_err());
    }

    #[test]
    fn walk_for_mbr_rejects_invalid_nested_byte_order() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_MULTIPOINT.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        blob.push(0xFF);
        blob.extend_from_slice(&WKB_POINT.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&2.0f64.to_le_bytes());
        assert!(extract_mbr(&blob).is_err());
    }

    #[test]
    fn walk_for_mbr_rejects_unknown_type() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&0u32.to_le_bytes());
        assert!(extract_mbr(&blob).is_err());
    }

    // -- Hardening: geometry_type_name for Line, Rect, Triangle --

    #[test]
    fn geometry_type_name_line() {
        let line = geo::Line::new(geo::Point::new(0.0, 0.0), geo::Point::new(1.0, 1.0));
        assert_eq!(geometry_type_name(&geo::Geometry::Line(line)), "Line");
    }

    #[test]
    fn geometry_type_name_rect() {
        let rect = geo::Rect::new(geo::Point::new(0.0, 0.0), geo::Point::new(1.0, 1.0));
        assert_eq!(geometry_type_name(&geo::Geometry::Rect(rect)), "Rect");
    }

    #[test]
    fn geometry_type_name_triangle() {
        let tri = geo::Triangle::new(
            geo::Coord { x: 0.0, y: 0.0 },
            geo::Coord { x: 1.0, y: 0.0 },
            geo::Coord { x: 0.0, y: 1.0 },
        );
        assert_eq!(
            geometry_type_name(&geo::Geometry::Triangle(tri)),
            "Triangle"
        );
    }

    // -- Hardening: type consistency in Multi* containers --

    #[test]
    fn validate_nesting_rejects_type_inconsistent_multipoint() {
        let mut blob = vec![0x01];
        blob.extend_from_slice(&WKB_MULTIPOINT.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes());
        blob.push(0x01);
        blob.extend_from_slice(&WKB_LINESTRING.to_le_bytes());
        blob.extend_from_slice(&2u32.to_le_bytes());
        blob.extend_from_slice(&0.0f64.to_le_bytes());
        blob.extend_from_slice(&0.0f64.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        blob.extend_from_slice(&1.0f64.to_le_bytes());
        let err = validate_ewkb_payload(&blob).unwrap_err();
        let err_str = format!("{err}");
        assert!(
            err_str.contains("wrong type"),
            "unexpected error: {err_str}"
        );
    }
}