sqlitegis 0.3.1

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
//! Measurement functions.
//!
//! ST_Area, ST_Perimeter, ST_Length, ST_Length2D, ST_Distance,
//! ST_Centroid, ST_PointOnSurface, ST_XMin/XMax/YMin/YMax,
//! ST_DistanceSphere, ST_DistanceSpheroid, ST_LengthSphere, ST_LengthSpheroid,
//! ST_AreaSphere, ST_AreaSpheroid, ST_PerimeterSphere, ST_PerimeterSpheroid,
//! ST_Azimuth, ST_Project, ST_ClosestPoint, ST_HausdorffDistance

use geo::algorithm::line_measures::metric_spaces::{Euclidean, Geodesic, Haversine};
use geo::algorithm::line_measures::{Bearing, Destination, Distance, Length};
use geo::algorithm::InteriorPoint;
use geo::algorithm::{Area, BoundingRect, Centroid, ClosestPoint, GeodesicArea, HausdorffDistance};
use geo::Closest;
use geo::{Geometry, LineString, Polygon};
use geo::{Point, Rect};
use geographiclib_rs::{Geodesic as GeodesicModel, PolygonArea, Winding};
use std::sync::LazyLock;

use crate::core::error::{Result, SqliteGisError};
use crate::core::ewkb::{ensure_matching_srid, parse_ewkb, parse_ewkb_pair, write_ewkb};
use crate::core::functions::emptiness::is_empty_geometry;

fn require_non_empty_geometry(geom: &Geometry<f64>, fn_name: &str) -> Result<()> {
    if is_empty_geometry(geom) {
        return Err(SqliteGisError::InvalidInput(format!(
            "{fn_name} does not accept empty geometries"
        )));
    }
    Ok(())
}

fn require_non_empty_point(point: Point<f64>, fn_name: &str) -> Result<Point<f64>> {
    if point.x().is_nan() || point.y().is_nan() {
        return Err(SqliteGisError::InvalidInput(format!(
            "{fn_name} does not accept empty points"
        )));
    }
    Ok(point)
}

fn latitude_in_range(lat: f64) -> bool {
    (-90.0..=90.0).contains(&lat)
}

/// Reject a point whose latitude is outside `[-90, 90]`, where `geo`'s Karney
/// `Geodesic` returns `NaN` and `Haversine` a wrong finite value. Longitude is
/// periodic and left to the algorithms.
// TODO(georust/geo#1553): drop the Karney half once fixed and released. The
// Haversine paths still need it (wrong finite value, not NaN).
fn require_geographic_latitude(point: Point<f64>, fn_name: &str) -> Result<Point<f64>> {
    if !latitude_in_range(point.y()) {
        return Err(SqliteGisError::InvalidInput(format!(
            "{fn_name}: latitude {} is outside the valid range [-90, 90]",
            point.y()
        )));
    }
    Ok(point)
}

/// Reject a line whose any vertex latitude falls outside `[-90, 90]`, so
/// `Haversine` length is not computed over invalid geographic coordinates.
pub(crate) fn require_geographic_line_latitudes(
    ls: &geo::LineString<f64>,
    fn_name: &str,
) -> Result<()> {
    for coord in ls.coords() {
        if !latitude_in_range(coord.y) {
            return Err(SqliteGisError::InvalidInput(format!(
                "{fn_name}: latitude {} is outside the valid range [-90, 90]",
                coord.y
            )));
        }
    }
    Ok(())
}

/// ST_Area: planar area (square units of the CRS).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_area;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
/// assert!((st_area(&poly).unwrap() - 1.0).abs() < 1e-10);
/// ```
pub fn st_area(blob: &[u8]) -> Result<f64> {
    let (geom, _) = parse_ewkb(blob)?;
    Ok(geom.unsigned_area())
}

/// ST_Length / ST_Length2D: planar arc length of a LineString or MultiLineString.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_length;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let line = geom_from_text("LINESTRING(0 0,3 4)", None).unwrap();
/// assert!((st_length(&line).unwrap() - 5.0).abs() < 1e-10);
/// ```
pub fn st_length(blob: &[u8]) -> Result<f64> {
    let (geom, _) = parse_ewkb(blob)?;
    let len = match &geom {
        Geometry::LineString(ls) => Euclidean.length(ls),
        Geometry::MultiLineString(mls) => mls.0.iter().map(|ls| Euclidean.length(ls)).sum(),
        other => {
            return Err(SqliteGisError::wrong_type(
                "LineString or MultiLineString",
                other,
            ))
        }
    };
    Ok(len)
}

/// ST_Perimeter: planar perimeter of a Polygon or MultiPolygon.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_perimeter;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
/// assert!((st_perimeter(&poly).unwrap() - 4.0).abs() < 1e-10);
/// ```
pub fn st_perimeter(blob: &[u8]) -> Result<f64> {
    fn poly_perimeter(p: &geo::Polygon<f64>) -> f64 {
        Euclidean.length(p.exterior())
            + p.interiors()
                .iter()
                .map(|r| Euclidean.length(r))
                .sum::<f64>()
    }
    let (geom, _) = parse_ewkb(blob)?;
    let perim = match &geom {
        Geometry::Polygon(p) => poly_perimeter(p),
        Geometry::MultiPolygon(mp) => mp.0.iter().map(poly_perimeter).sum(),
        other => return Err(SqliteGisError::wrong_type("Polygon or MultiPolygon", other)),
    };
    Ok(perim)
}

/// Dispatch euclidean distance between any two geo geometry types.
fn euclidean_geometry_distance(a: &Geometry<f64>, b: &Geometry<f64>) -> f64 {
    Euclidean.distance(a, b)
}

/// ST_Distance: minimum Euclidean distance between two geometries.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_distance;
/// use sqlitegis::core::functions::constructors::st_point;
///
/// let a = st_point(0.0, 0.0, None).unwrap();
/// let b = st_point(3.0, 4.0, None).unwrap();
/// assert!((st_distance(&a, &b).unwrap() - 5.0).abs() < 1e-10);
/// ```
pub fn st_distance(a: &[u8], b: &[u8]) -> Result<f64> {
    crate::core::functions::catch_geo("ST_Distance", || {
        let (ga, gb, _) = parse_ewkb_pair(a, b)?;
        require_non_empty_geometry(&ga, "ST_Distance")?;
        require_non_empty_geometry(&gb, "ST_Distance")?;
        Ok(euclidean_geometry_distance(&ga, &gb))
    })
}

/// ST_Centroid: geometric centroid of any geometry.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_centroid;
/// use sqlitegis::core::functions::accessors::{st_x, st_y};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,2 0,2 2,0 2,0 0))", None).unwrap();
/// let c = st_centroid(&poly).unwrap();
/// assert!((st_x(&c).unwrap().unwrap() - 1.0).abs() < 1e-10);
/// assert!((st_y(&c).unwrap().unwrap() - 1.0).abs() < 1e-10);
/// ```
pub fn st_centroid(blob: &[u8]) -> Result<Vec<u8>> {
    crate::core::functions::catch_geo("ST_Centroid", || {
        let (geom, srid) = parse_ewkb(blob)?;
        let c = geom
            .centroid()
            .ok_or_else(|| SqliteGisError::wrong_type("non-empty geometry", &geom))?;
        write_ewkb(&Geometry::Point(c), srid)
    })
}

/// ST_PointOnSurface: a point guaranteed to lie on the geometry.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_point_on_surface;
/// use sqlitegis::core::functions::predicates::st_within;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,4 0,4 4,0 4,0 0))", None).unwrap();
/// let pt = st_point_on_surface(&poly).unwrap();
/// // The point on surface should be within the polygon
/// assert!(st_within(&pt, &poly).unwrap());
/// ```
pub fn st_point_on_surface(blob: &[u8]) -> Result<Vec<u8>> {
    crate::core::functions::catch_geo("ST_PointOnSurface", || {
        let (geom, srid) = parse_ewkb(blob)?;
        let p = geom
            .interior_point()
            .ok_or_else(|| SqliteGisError::wrong_type("non-empty geometry", &geom))?;
        write_ewkb(&Geometry::Point(p), srid)
    })
}

/// ST_HausdorffDistance: Hausdorff distance between two geometries.
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_hausdorff_distance;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let a = geom_from_text("LINESTRING(0 0,1 0)", None).unwrap();
/// let b = geom_from_text("LINESTRING(0 1,1 1)", None).unwrap();
/// assert!((st_hausdorff_distance(&a, &b).unwrap() - 1.0).abs() < 1e-10);
/// ```
pub fn st_hausdorff_distance(a: &[u8], b: &[u8]) -> Result<f64> {
    crate::core::functions::catch_geo("ST_HausdorffDistance", || {
        let (ga, gb, _) = parse_ewkb_pair(a, b)?;
        require_non_empty_geometry(&ga, "ST_HausdorffDistance")?;
        require_non_empty_geometry(&gb, "ST_HausdorffDistance")?;
        Ok(ga.hausdorff_distance(&gb))
    })
}

// Bounding-box accessors

/// ST_XMin: minimum X of the bounding rectangle.
///
/// Returns `None` for empty geometries (PostGIS-compatible).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_xmin;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("LINESTRING(1 2,3 4)", None).unwrap();
/// assert!((st_xmin(&blob).unwrap().unwrap() - 1.0).abs() < 1e-10);
/// ```
pub fn st_xmin(blob: &[u8]) -> Result<Option<f64>> {
    let r = bbox(blob)?;
    Ok(r.map(|r| r.min().x))
}

/// ST_XMax: maximum X of the bounding rectangle.
///
/// Returns `None` for empty geometries (PostGIS-compatible).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_xmax;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("LINESTRING(1 2,3 4)", None).unwrap();
/// assert!((st_xmax(&blob).unwrap().unwrap() - 3.0).abs() < 1e-10);
/// ```
pub fn st_xmax(blob: &[u8]) -> Result<Option<f64>> {
    let r = bbox(blob)?;
    Ok(r.map(|r| r.max().x))
}

/// ST_YMin: minimum Y of the bounding rectangle.
///
/// Returns `None` for empty geometries (PostGIS-compatible).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_ymin;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("LINESTRING(1 2,3 4)", None).unwrap();
/// assert!((st_ymin(&blob).unwrap().unwrap() - 2.0).abs() < 1e-10);
/// ```
pub fn st_ymin(blob: &[u8]) -> Result<Option<f64>> {
    let r = bbox(blob)?;
    Ok(r.map(|r| r.min().y))
}

/// ST_YMax: maximum Y of the bounding rectangle.
///
/// Returns `None` for empty geometries (PostGIS-compatible).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_ymax;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let blob = geom_from_text("LINESTRING(1 2,3 4)", None).unwrap();
/// assert!((st_ymax(&blob).unwrap().unwrap() - 4.0).abs() < 1e-10);
/// ```
pub fn st_ymax(blob: &[u8]) -> Result<Option<f64>> {
    let r = bbox(blob)?;
    Ok(r.map(|r| r.max().y))
}

fn bbox(blob: &[u8]) -> Result<Option<Rect<f64>>> {
    let (geom, _) = parse_ewkb(blob)?;
    if is_empty_geometry(&geom) {
        return Ok(None);
    }
    geom.bounding_rect()
        .ok_or_else(|| SqliteGisError::wrong_type("non-empty geometry", &geom))
        .map(Some)
}

// Spherical / geodetic variants

fn require_point(g: Geometry<f64>) -> Result<Point<f64>> {
    match g {
        Geometry::Point(p) => Ok(p),
        other => Err(SqliteGisError::wrong_type("Point", &other)),
    }
}

pub(crate) fn ensure_geographic_srid(srid: Option<i32>, fn_name: &str) -> Result<()> {
    match srid {
        Some(4326) => Ok(()),
        Some(srid) => Err(SqliteGisError::InvalidInput(format!(
            "{fn_name} requires SRID 4326 (got {srid})"
        ))),
        None => Err(SqliteGisError::InvalidInput(format!(
            "{fn_name} requires SRID 4326 (got unknown/unspecified SRID)"
        ))),
    }
}

fn ensure_matching_geographic_srid(
    left: Option<i32>,
    right: Option<i32>,
    fn_name: &str,
) -> Result<Option<i32>> {
    let srid = ensure_matching_srid(left, right)?;
    ensure_geographic_srid(srid, fn_name)?;
    Ok(srid)
}

fn parse_two_geographic_points(
    a: &[u8],
    b: &[u8],
    fn_name: &str,
) -> Result<(Point<f64>, Point<f64>, Option<i32>)> {
    let (ga, srid_a) = parse_ewkb(a)?;
    let (gb, srid_b) = parse_ewkb(b)?;
    let srid = ensure_matching_geographic_srid(srid_a, srid_b, fn_name)?;
    let pa = require_geographic_latitude(
        require_non_empty_point(require_point(ga)?, fn_name)?,
        fn_name,
    )?;
    let pb = require_geographic_latitude(
        require_non_empty_point(require_point(gb)?, fn_name)?,
        fn_name,
    )?;
    Ok((pa, pb, srid))
}

/// ST_DistanceSphere: Haversine distance in metres (requires Point inputs, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_distance_sphere;
/// use sqlitegis::core::functions::constructors::st_point;
///
/// let london = st_point(-0.1278, 51.5074, Some(4326)).unwrap();
/// let paris = st_point(2.3522, 48.8566, Some(4326)).unwrap();
/// let dist = st_distance_sphere(&london, &paris).unwrap();
/// assert!(dist > 300_000.0 && dist < 400_000.0); // ~340 km
/// ```
pub fn st_distance_sphere(a: &[u8], b: &[u8]) -> Result<f64> {
    let (pa, pb, _) = parse_two_geographic_points(a, b, "ST_DistanceSphere")?;
    Ok(Haversine.distance(pa, pb))
}

/// ST_DistanceSpheroid: Geodesic distance in metres (Karney algorithm, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_distance_spheroid;
/// use sqlitegis::core::functions::constructors::st_point;
///
/// let london = st_point(-0.1278, 51.5074, Some(4326)).unwrap();
/// let paris = st_point(2.3522, 48.8566, Some(4326)).unwrap();
/// let dist = st_distance_spheroid(&london, &paris).unwrap();
/// assert!(dist > 300_000.0 && dist < 400_000.0); // ~340 km
/// ```
pub fn st_distance_spheroid(a: &[u8], b: &[u8]) -> Result<f64> {
    let (pa, pb, _) = parse_two_geographic_points(a, b, "ST_DistanceSpheroid")?;
    Ok(Geodesic.distance(pa, pb))
}

/// A perfectly round earth of the radius `Haversine` uses, so `ST_AreaSphere`
/// reports area on the same planet `ST_LengthSphere` and `ST_DistanceSphere`
/// measure lengths on. `geo`'s own spherical area helper is fixed to the
/// equatorial radius, which would put the two 0.22% apart.
static SPHERE: LazyLock<GeodesicModel> =
    LazyLock::new(|| GeodesicModel::new(Haversine.radius(), 0.0));

/// Reject a polygon with any vertex latitude outside `[-90, 90]`, where the
/// Karney area returns `NaN` and Haversine a wrong finite value.
fn require_geographic_polygon_latitudes(poly: &Polygon<f64>, fn_name: &str) -> Result<()> {
    require_geographic_line_latitudes(poly.exterior(), fn_name)?;
    for ring in poly.interiors() {
        require_geographic_line_latitudes(ring, fn_name)?;
    }
    Ok(())
}

/// Apply a curved-earth line measure to a lineal geometry, summing over the
/// parts of a MultiLineString.
fn measure_geographic_lines(
    blob: &[u8],
    fn_name: &str,
    measure: impl Fn(&LineString<f64>) -> f64,
) -> Result<f64> {
    let (geom, srid) = parse_ewkb(blob)?;
    ensure_geographic_srid(srid, fn_name)?;
    match &geom {
        Geometry::LineString(ls) => {
            require_geographic_line_latitudes(ls, fn_name)?;
            Ok(measure(ls))
        }
        Geometry::MultiLineString(mls) => {
            for ls in &mls.0 {
                require_geographic_line_latitudes(ls, fn_name)?;
            }
            Ok(mls.0.iter().map(measure).sum())
        }
        other => Err(SqliteGisError::wrong_type(
            "LineString or MultiLineString",
            other,
        )),
    }
}

/// Apply a curved-earth areal measure to an areal geometry, summing over the
/// parts of a MultiPolygon.
fn measure_geographic_polygons(
    blob: &[u8],
    fn_name: &str,
    measure: impl Fn(&Polygon<f64>) -> f64,
) -> Result<f64> {
    let (geom, srid) = parse_ewkb(blob)?;
    ensure_geographic_srid(srid, fn_name)?;
    match &geom {
        Geometry::Polygon(p) => {
            require_geographic_polygon_latitudes(p, fn_name)?;
            Ok(measure(p))
        }
        Geometry::MultiPolygon(mp) => {
            for p in &mp.0 {
                require_geographic_polygon_latitudes(p, fn_name)?;
            }
            Ok(mp.0.iter().map(measure).sum())
        }
        other => Err(SqliteGisError::wrong_type("Polygon or MultiPolygon", other)),
    }
}

/// Signed area of one ring on [`SPHERE`], mirroring the ring walk `geo` uses
/// for the ellipsoid.
fn sphere_ring_area(ring: &LineString<f64>, winding: Winding) -> f64 {
    let mut area = PolygonArea::new(&SPHERE, winding);
    for p in ring.points() {
        area.add_point(p.y(), p.x());
    }
    area.compute(true).1
}

/// Area of a polygon on [`SPHERE`], holes subtracted.
///
/// The magnitude is taken so either ring winding reports a positive area, the
/// way PostGIS does. That costs the ability to tell a clockwise ring from a
/// polygon covering more than half the planet, a limitation PostGIS and `geo`
/// share.
fn sphere_polygon_area(poly: &Polygon<f64>) -> f64 {
    let shell = sphere_ring_area(poly.exterior(), Winding::CounterClockwise).abs();
    let holes: f64 = poly
        .interiors()
        .iter()
        .map(|ring| sphere_ring_area(ring, Winding::Clockwise).abs())
        .sum();
    shell - holes
}

/// Haversine perimeter of a polygon, interior rings included.
fn sphere_polygon_perimeter(poly: &Polygon<f64>) -> f64 {
    Haversine.length(poly.exterior())
        + poly
            .interiors()
            .iter()
            .map(|ring| Haversine.length(ring))
            .sum::<f64>()
}

/// ST_LengthSphere: Haversine arc length of a line in metres (SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_length_sphere;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let line = geom_from_text("LINESTRING(-0.1278 51.5074, 2.3522 48.8566)", Some(4326)).unwrap();
/// let len = st_length_sphere(&line).unwrap();
/// assert!(len > 300_000.0); // > 300 km
/// ```
pub fn st_length_sphere(blob: &[u8]) -> Result<f64> {
    measure_geographic_lines(blob, "ST_LengthSphere", |ls| Haversine.length(ls))
}

/// ST_LengthSpheroid: geodesic arc length of a line in metres on the WGS84
/// ellipsoid (Karney algorithm, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::{st_length_sphere, st_length_spheroid};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let line = geom_from_text("LINESTRING(0 0, 1 1)", Some(4326)).unwrap();
/// // PostGIS answers 156899.56829134029 for this line read as `geography`.
/// assert!((st_length_spheroid(&line).unwrap() - 156_899.568_291_340_29).abs() < 1e-6);
/// // The sphere is 0.22% high on the same line.
/// assert!(st_length_sphere(&line).unwrap() > st_length_spheroid(&line).unwrap());
/// ```
pub fn st_length_spheroid(blob: &[u8]) -> Result<f64> {
    measure_geographic_lines(blob, "ST_LengthSpheroid", |ls| Geodesic.length(ls))
}

/// ST_AreaSpheroid: area in square metres on the WGS84 ellipsoid (Karney
/// algorithm, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_area_spheroid;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
/// // PostGIS answers 12308778361.469454 for this polygon read as `geography`.
/// assert!((st_area_spheroid(&poly).unwrap() - 12_308_778_361.469_454).abs() < 1e-3);
/// ```
pub fn st_area_spheroid(blob: &[u8]) -> Result<f64> {
    measure_geographic_polygons(blob, "ST_AreaSpheroid", |p| p.geodesic_area_signed().abs())
}

/// ST_PerimeterSpheroid: perimeter in metres on the WGS84 ellipsoid, interior
/// rings included (Karney algorithm, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_perimeter_spheroid;
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
/// // PostGIS answers 443770.917248302 for this polygon read as `geography`.
/// assert!((st_perimeter_spheroid(&poly).unwrap() - 443_770.917_248_302).abs() < 1e-6);
/// ```
pub fn st_perimeter_spheroid(blob: &[u8]) -> Result<f64> {
    measure_geographic_polygons(blob, "ST_PerimeterSpheroid", |p| p.geodesic_perimeter())
}

/// ST_AreaSphere: area in square metres on a sphere of the mean earth radius
/// (SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::{st_area_sphere, st_area_spheroid};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
/// // A sphere overstates this equatorial cell by 0.45% against the ellipsoid.
/// assert!(st_area_sphere(&poly).unwrap() > st_area_spheroid(&poly).unwrap());
/// ```
pub fn st_area_sphere(blob: &[u8]) -> Result<f64> {
    measure_geographic_polygons(blob, "ST_AreaSphere", sphere_polygon_area)
}

/// ST_PerimeterSphere: Haversine perimeter in metres, interior rings included
/// (SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::{st_length_sphere, st_perimeter_sphere};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
/// let ring = geom_from_text("LINESTRING(0 0,1 0,1 1,0 1,0 0)", Some(4326)).unwrap();
/// assert_eq!(
///     st_perimeter_sphere(&poly).unwrap(),
///     st_length_sphere(&ring).unwrap()
/// );
/// ```
pub fn st_perimeter_sphere(blob: &[u8]) -> Result<f64> {
    measure_geographic_polygons(blob, "ST_PerimeterSphere", sphere_polygon_perimeter)
}

/// ST_Azimuth: bearing from origin to target in radians (0 = north, clockwise, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_azimuth;
/// use sqlitegis::core::functions::constructors::st_point;
///
/// let origin = st_point(0.0, 0.0, Some(4326)).unwrap();
/// let target = st_point(0.0, 1.0, Some(4326)).unwrap();
/// let az = st_azimuth(&origin, &target).unwrap();
/// // Due north -> azimuth approximately  0
/// assert!(az.abs() < 0.01);
/// ```
pub fn st_azimuth(origin: &[u8], target: &[u8]) -> Result<f64> {
    let (po, pt, _) = parse_two_geographic_points(origin, target, "ST_Azimuth")?;
    Ok(Geodesic.bearing(po, pt).to_radians())
}

/// ST_Project: destination point given a start, bearing (radians), and distance (metres, SRID 4326).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_project;
/// use sqlitegis::core::functions::constructors::st_point;
/// use sqlitegis::core::functions::accessors::st_y;
///
/// let origin = st_point(0.0, 0.0, Some(4326)).unwrap();
/// // Project 111_000m due north (azimuth=0)
/// let dest = st_project(&origin, 111_000.0, 0.0).unwrap();
/// // Should be roughly 1 degree north
/// assert!((st_y(&dest).unwrap().unwrap() - 1.0).abs() < 0.1);
/// ```
pub fn st_project(origin: &[u8], distance: f64, azimuth: f64) -> Result<Vec<u8>> {
    if !distance.is_finite() {
        return Err(SqliteGisError::InvalidInput(
            "ST_Project: distance must be finite".to_string(),
        ));
    }
    if !azimuth.is_finite() {
        return Err(SqliteGisError::InvalidInput(
            "ST_Project: azimuth must be finite".to_string(),
        ));
    }
    let (go, srid) = parse_ewkb(origin)?;
    ensure_geographic_srid(srid, "ST_Project")?;
    let po = require_geographic_latitude(
        require_non_empty_point(require_point(go)?, "ST_Project")?,
        "ST_Project",
    )?;
    let dest: Point<f64> = Geodesic.destination(po, azimuth.to_degrees(), distance);
    write_ewkb(&Geometry::Point(dest), srid)
}

/// ST_ClosestPoint: the point on geometry A closest to geometry B (point).
///
/// # Example
///
/// ```
/// use sqlitegis::core::functions::measurement::st_closest_point;
/// use sqlitegis::core::functions::constructors::st_point;
/// use sqlitegis::core::functions::accessors::{st_x, st_y};
/// use sqlitegis::core::functions::io::geom_from_text;
///
/// let line = geom_from_text("LINESTRING(0 0,10 0)", None).unwrap();
/// let pt = st_point(5.0, 5.0, None).unwrap();
/// let cp = st_closest_point(&line, &pt).unwrap();
/// assert!((st_x(&cp).unwrap().unwrap() - 5.0).abs() < 1e-10);
/// assert!((st_y(&cp).unwrap().unwrap() - 0.0).abs() < 1e-10);
/// ```
pub fn st_closest_point(a: &[u8], b: &[u8]) -> Result<Vec<u8>> {
    crate::core::functions::catch_geo("ST_ClosestPoint", || {
        let (ga, gb, srid) = parse_ewkb_pair(a, b)?;
        require_non_empty_geometry(&ga, "ST_ClosestPoint")?;
        let pb = require_non_empty_point(require_point(gb)?, "ST_ClosestPoint")?;
        let cp = ga.closest_point(&pb);
        let pt = match cp {
            Closest::Intersection(p) | Closest::SinglePoint(p) => p,
            Closest::Indeterminate => {
                return Err(SqliteGisError::InvalidInput(
                    "ST_ClosestPoint: unable to determine closest point".to_string(),
                ))
            }
        };
        write_ewkb(&Geometry::Point(pt), srid)
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::core::functions::accessors::{st_x, st_y};
    use crate::core::functions::constructors::st_point;
    use crate::core::functions::io::geom_from_text;

    /// EWKB for a polygon whose ring has a NaN vertex, so `is_closed()` (a
    /// `first == last` compare) is false and geo's centroid `assert!` aborts.
    /// Fuzzer-found.
    fn nan_ring_polygon() -> Vec<u8> {
        use crate::core::ewkb::WKB_POLYGON;
        let mut blob = vec![0x01u8];
        blob.extend_from_slice(&WKB_POLYGON.to_le_bytes());
        blob.extend_from_slice(&1u32.to_le_bytes()); // one ring
        blob.extend_from_slice(&1u32.to_le_bytes()); // a single NaN point
        blob.extend_from_slice(&f64::NAN.to_le_bytes());
        blob.extend_from_slice(&f64::NAN.to_le_bytes());
        blob
    }

    #[test]
    fn st_centroid_degenerate_ring_does_not_panic() {
        // Must come back as a recoverable error, not abort the process.
        let blob = nan_ring_polygon();
        assert!(st_centroid(&blob).is_err());
    }

    #[test]
    fn st_point_on_surface_degenerate_ring_does_not_panic() {
        let blob = nan_ring_polygon();
        assert!(st_point_on_surface(&blob).is_err());
    }

    // -- Wrong-type errors ------------------------------------------

    #[test]
    fn st_length_wrong_type() {
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_length(&pt).is_err());
    }

    #[test]
    fn st_perimeter_wrong_type() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        assert!(st_perimeter(&line).is_err());
    }

    #[test]
    fn st_distance_sphere_non_point() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_distance_sphere(&line, &pt).is_err());
    }

    #[test]
    fn st_distance_spheroid_non_point() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_distance_spheroid(&line, &pt).is_err());
    }

    #[test]
    fn geodesic_out_of_range_latitude_errors_not_nan() {
        // Latitude past the pole drives geo's Karney geodesic to NaN; the
        // geographic functions must reject it with an error instead. The
        // fuzzer found this (a=(0,-90.00000004)).
        let valid = st_point(2.3522, 48.8566, Some(4326)).unwrap();
        for bad in [
            st_point(0.0, 95.0, Some(4326)).unwrap(),
            st_point(0.0, -90.0001, Some(4326)).unwrap(),
        ] {
            assert!(st_distance_spheroid(&bad, &valid).is_err());
            assert!(st_distance_sphere(&bad, &valid).is_err());
            assert!(st_azimuth(&bad, &valid).is_err());
            assert!(st_project(&bad, 1000.0, 0.5).is_err());
        }
    }

    #[test]
    fn st_length_sphere_out_of_range_latitude_errors() {
        // Haversine silently returns a wrong finite length past the poles, so
        // ST_LengthSphere must reject a line with an out-of-range vertex.
        let bad = geom_from_text("LINESTRING(0 0, 10 95)", Some(4326)).unwrap();
        assert!(st_length_sphere(&bad).is_err());
        let bad_multi =
            geom_from_text("MULTILINESTRING((0 0, 1 1),(2 2, 3 -91))", Some(4326)).unwrap();
        assert!(st_length_sphere(&bad_multi).is_err());
        // A valid line still works.
        let ok = geom_from_text("LINESTRING(0 0, 10 10)", Some(4326)).unwrap();
        assert!(st_length_sphere(&ok).unwrap() > 0.0);
    }

    #[test]
    fn st_azimuth_non_point() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_azimuth(&line, &pt).is_err());
    }

    #[test]
    fn st_project_non_point() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        assert!(st_project(&line, 100.0, 0.0).is_err());
    }

    #[test]
    fn st_length_sphere_non_linestring() {
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_length_sphere(&pt).is_err());
    }

    // -- Distance to self -------------------------------------------

    #[test]
    fn distance_to_self_is_zero() {
        let pt = st_point(1.0, 2.0, None).unwrap();
        assert!(st_distance(&pt, &pt).unwrap().abs() < 1e-10);
    }

    #[test]
    fn st_distance_multipoint_point_uses_min_distance() {
        let mp = geom_from_text("MULTIPOINT((0 0),(10 0))", None).unwrap();
        let pt = geom_from_text("POINT(0 0)", None).unwrap();
        let d = st_distance(&mp, &pt).unwrap();
        assert!((d - 0.0).abs() < 1e-10, "distance = {d}");
    }

    #[test]
    fn st_distance_mixed_srid_errors() {
        let a = st_point(0.0, 0.0, Some(4326)).unwrap();
        let b = st_point(3.0, 4.0, Some(3857)).unwrap();
        assert!(st_distance(&a, &b).is_err());
    }

    #[test]
    fn st_azimuth_mixed_srid_errors() {
        let a = st_point(0.0, 0.0, Some(4326)).unwrap();
        let b = st_point(0.0, 1.0, Some(3857)).unwrap();
        assert!(st_azimuth(&a, &b).is_err());
    }

    #[test]
    fn st_distance_sphere_non_geographic_srid_errors() {
        let a = st_point(0.0, 0.0, Some(3857)).unwrap();
        let b = st_point(1.0, 1.0, Some(3857)).unwrap();
        assert!(st_distance_sphere(&a, &b).is_err());
    }

    #[test]
    fn st_distance_sphere_missing_srid_errors() {
        let a = st_point(0.0, 0.0, None).unwrap();
        let b = st_point(1.0, 1.0, None).unwrap();
        assert!(st_distance_sphere(&a, &b).is_err());
    }

    #[test]
    fn st_distance_spheroid_non_geographic_srid_errors() {
        let a = st_point(0.0, 0.0, Some(3857)).unwrap();
        let b = st_point(1.0, 1.0, Some(3857)).unwrap();
        assert!(st_distance_spheroid(&a, &b).is_err());
    }

    #[test]
    fn st_distance_spheroid_missing_srid_errors() {
        let a = st_point(0.0, 0.0, None).unwrap();
        let b = st_point(1.0, 1.0, None).unwrap();
        assert!(st_distance_spheroid(&a, &b).is_err());
    }

    #[test]
    fn st_length_sphere_non_geographic_srid_errors() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", Some(3857)).unwrap();
        assert!(st_length_sphere(&line).is_err());
    }

    #[test]
    fn st_length_sphere_missing_srid_errors() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", None).unwrap();
        assert!(st_length_sphere(&line).is_err());
    }

    #[test]
    fn st_project_non_geographic_srid_errors() {
        let origin = st_point(0.0, 0.0, Some(3857)).unwrap();
        assert!(st_project(&origin, 111_000.0, 0.0).is_err());
    }

    #[test]
    fn st_project_missing_srid_errors() {
        let origin = st_point(0.0, 0.0, None).unwrap();
        assert!(st_project(&origin, 111_000.0, 0.0).is_err());
    }

    #[test]
    fn st_project_non_finite_args_error() {
        let origin = st_point(0.0, 0.0, Some(4326)).unwrap();

        let err = st_project(&origin, f64::INFINITY, 0.0)
            .expect_err("non-finite distance should be rejected");
        assert!(format!("{err}").contains("distance must be finite"));

        let err = st_project(&origin, 1_000.0, f64::NEG_INFINITY).expect_err("non-finite azimuth");
        assert!(format!("{err}").contains("azimuth must be finite"));
    }

    #[test]
    fn st_azimuth_missing_srid_errors() {
        let a = st_point(0.0, 0.0, None).unwrap();
        let b = st_point(0.0, 1.0, None).unwrap();
        assert!(st_azimuth(&a, &b).is_err());
    }

    #[test]
    fn distance_sphere_to_self_is_zero() {
        let pt = st_point(1.0, 2.0, Some(4326)).unwrap();
        assert!(st_distance_sphere(&pt, &pt).unwrap().abs() < 1e-10);
    }

    #[test]
    fn distance_spheroid_to_self_is_zero() {
        let pt = st_point(1.0, 2.0, Some(4326)).unwrap();
        assert!(st_distance_spheroid(&pt, &pt).unwrap().abs() < 1e-10);
    }

    // -- Hausdorff --------------------------------------------------

    #[test]
    fn hausdorff_identical_is_zero() {
        let line = geom_from_text("LINESTRING(0 0,1 1,2 0)", None).unwrap();
        assert!(st_hausdorff_distance(&line, &line).unwrap().abs() < 1e-10);
    }

    #[test]
    fn st_hausdorff_distance_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        let err = st_hausdorff_distance(&empty, &pt).expect_err("empty point must error");
        assert!(format!("{err}").contains("does not accept empty geometries"));
    }

    // -- Closest point ----------------------------------------------

    #[test]
    fn closest_point_perpendicular_projection() {
        let line = geom_from_text("LINESTRING(0 0,10 0)", None).unwrap();
        let pt = st_point(5.0, 3.0, None).unwrap();
        let cp = st_closest_point(&line, &pt).unwrap();
        assert!((st_x(&cp).unwrap().unwrap() - 5.0).abs() < 1e-10);
        assert!((st_y(&cp).unwrap().unwrap() - 0.0).abs() < 1e-10);
    }

    // -- Bounding box -----------------------------------------------

    #[test]
    fn bbox_invariants() {
        let poly = geom_from_text("POLYGON((1 2,5 2,5 8,1 8,1 2))", None).unwrap();
        let xmin = st_xmin(&poly).unwrap().unwrap();
        let xmax = st_xmax(&poly).unwrap().unwrap();
        let ymin = st_ymin(&poly).unwrap().unwrap();
        let ymax = st_ymax(&poly).unwrap().unwrap();
        assert!(xmin <= xmax);
        assert!(ymin <= ymax);
        assert!((xmin - 1.0).abs() < 1e-10);
        assert!((xmax - 5.0).abs() < 1e-10);
        assert!((ymin - 2.0).abs() < 1e-10);
        assert!((ymax - 8.0).abs() < 1e-10);
    }

    #[test]
    fn bbox_accessors_return_none_for_empty_geometries() {
        let empty_point = geom_from_text("POINT EMPTY", None).unwrap();
        assert_eq!(st_xmin(&empty_point).unwrap(), None);
        assert_eq!(st_xmax(&empty_point).unwrap(), None);
        assert_eq!(st_ymin(&empty_point).unwrap(), None);
        assert_eq!(st_ymax(&empty_point).unwrap(), None);

        let empty_gc = geom_from_text("GEOMETRYCOLLECTION EMPTY", None).unwrap();
        assert_eq!(st_xmin(&empty_gc).unwrap(), None);
        assert_eq!(st_xmax(&empty_gc).unwrap(), None);
        assert_eq!(st_ymin(&empty_gc).unwrap(), None);
        assert_eq!(st_ymax(&empty_gc).unwrap(), None);
    }

    #[test]
    fn st_area_point_is_zero() {
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_area(&pt).unwrap().abs() < 1e-10);
    }

    #[test]
    fn st_length_multilinestring() {
        let mls = geom_from_text("MULTILINESTRING((0 0,1 0),(0 0,0 1))", None).unwrap();
        assert!((st_length(&mls).unwrap() - 2.0).abs() < 1e-10);
    }

    #[test]
    fn st_length_linestring() {
        let line = geom_from_text("LINESTRING(0 0,3 4)", None).unwrap();
        assert!((st_length(&line).unwrap() - 5.0).abs() < 1e-10);
    }

    #[test]
    fn st_perimeter_polygon_and_multipolygon() {
        let poly =
            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();
        assert!((st_perimeter(&poly).unwrap() - 20.0).abs() < 1e-10);

        let mpoly = geom_from_text(
            "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 2,3 2,3 3,2 3,2 2)))",
            None,
        )
        .unwrap();
        assert!((st_perimeter(&mpoly).unwrap() - 8.0).abs() < 1e-10);
    }

    #[test]
    fn centroid_and_point_on_surface_are_computable() {
        let poly = geom_from_text("POLYGON((0 0,2 0,2 2,0 2,0 0))", Some(4326)).unwrap();

        let centroid = st_centroid(&poly).unwrap();
        assert!((st_x(&centroid).unwrap().unwrap() - 1.0).abs() < 1e-10);
        assert!((st_y(&centroid).unwrap().unwrap() - 1.0).abs() < 1e-10);

        let pos = st_point_on_surface(&poly).unwrap();
        assert!(st_x(&pos).unwrap().unwrap() >= 0.0);
        assert!(st_y(&pos).unwrap().unwrap() >= 0.0);
    }

    #[test]
    fn st_length_sphere_linestring_and_multilinestring() {
        let line =
            geom_from_text("LINESTRING(-0.1278 51.5074,2.3522 48.8566)", Some(4326)).unwrap();
        assert!(st_length_sphere(&line).unwrap() > 300_000.0);

        let mls = geom_from_text(
            "MULTILINESTRING((-0.1278 51.5074,2.3522 48.8566),(2.3522 48.8566,13.4050 52.5200))",
            Some(4326),
        )
        .unwrap();
        assert!(st_length_sphere(&mls).unwrap() > st_length_sphere(&line).unwrap());
    }

    #[test]
    fn st_azimuth_and_project_success() {
        let origin = st_point(0.0, 0.0, Some(4326)).unwrap();
        let north = st_point(0.0, 1.0, Some(4326)).unwrap();
        let azimuth = st_azimuth(&origin, &north).unwrap();
        assert!(azimuth.abs() < 0.01);

        let dest = st_project(&origin, 111_000.0, 0.0).unwrap();
        assert!((st_y(&dest).unwrap().unwrap() - 1.0).abs() < 0.2);
        assert_eq!(
            crate::core::functions::accessors::st_srid(&dest).unwrap(),
            4326
        );
    }

    #[test]
    fn st_closest_point_indeterminate_for_empty_geometry() {
        let empty = geom_from_text("GEOMETRYCOLLECTION EMPTY", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        assert!(st_closest_point(&empty, &pt).is_err());
    }

    #[test]
    fn st_distance_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", None).unwrap();
        let pt = st_point(0.0, 0.0, None).unwrap();
        let err = st_distance(&empty, &pt).expect_err("empty point must error");
        assert!(format!("{err}").contains("does not accept empty geometries"));
    }

    #[test]
    fn st_distance_sphere_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", Some(4326)).unwrap();
        let pt = st_point(0.0, 0.0, Some(4326)).unwrap();
        assert!(st_distance_sphere(&empty, &pt).is_err());
    }

    #[test]
    fn st_distance_spheroid_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", Some(4326)).unwrap();
        let pt = st_point(0.0, 0.0, Some(4326)).unwrap();
        assert!(st_distance_spheroid(&empty, &pt).is_err());
    }

    #[test]
    fn st_azimuth_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", Some(4326)).unwrap();
        let pt = st_point(0.0, 0.0, Some(4326)).unwrap();
        assert!(st_azimuth(&empty, &pt).is_err());
    }

    #[test]
    fn st_project_empty_point_errors() {
        let empty = geom_from_text("POINT EMPTY", Some(4326)).unwrap();
        assert!(st_project(&empty, 1_000.0, 0.0).is_err());
    }

    #[test]
    fn st_closest_point_empty_target_point_errors() {
        let line = geom_from_text("LINESTRING(0 0,10 0)", None).unwrap();
        let empty = geom_from_text("POINT EMPTY", None).unwrap();
        assert!(st_closest_point(&line, &empty).is_err());
    }

    #[test]
    fn st_length_sphere_rejects_polygon() {
        let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap();
        let err = st_length_sphere(&poly).expect_err("polygon input must error");
        assert!(format!("{err}").contains("LineString or MultiLineString"));
    }

    #[test]
    fn st_distance_sphere_second_point_bad_latitude() {
        // Exercises parse_two_geographic_points line 362-365: require_geographic_latitude
        // on the second point (pb path).
        let valid = st_point(0.0, 0.0, Some(4326)).unwrap();
        let bad = st_point(0.0, 100.0, Some(4326)).unwrap();
        let err = st_distance_sphere(&valid, &bad).expect_err("bad latitude must error");
        assert!(
            format!("{err}").contains("latitude"),
            "expected latitude error, got: {err}"
        );
    }

    #[test]
    fn st_closest_point_nan_geometry_errors_at_parse() {
        // NaN coordinates are rejected by reject_non_finite_coords in parse_ewkb,
        // so they never reach the closest_point algorithm. The Indeterminate
        // path (lines 518-520) is defensive code for geometries that geo's
        // algorithm cannot resolve, but no known finite non-empty geometry
        // triggers it in practice.
        let nan_poly = nan_ring_polygon();
        let pt = st_point(0.0, 0.0, None).unwrap();
        let err = st_closest_point(&nan_poly, &pt).expect_err("NaN geometry must error");
        assert!(
            format!("{err}").contains("non-finite"),
            "expected non-finite error, got: {err}"
        );
    }

    // -- Curved-earth length, area and perimeter ---------------------

    /// Assert against a reference constant read out of PostGIS 3.5 (or, for
    /// the sphere, out of geographiclib on a mean-radius sphere). Karney
    /// lands within a few ULP of those, so the window stays tight enough
    /// that a swapped earth model or algorithm fails the test.
    fn assert_matches_reference(got: f64, want: f64) {
        let rel = (got - want).abs() / want.abs();
        assert!(rel < 1e-12, "got {got}, want {want}, relative error {rel}");
    }

    fn unit_square_4326() -> Vec<u8> {
        geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", Some(4326)).unwrap()
    }

    #[test]
    fn st_length_spheroid_matches_postgis() {
        let line = geom_from_text("LINESTRING(0 0, 1 1)", Some(4326)).unwrap();
        assert_matches_reference(st_length_spheroid(&line).unwrap(), 156_899.568_291_340_29);
    }

    #[test]
    fn st_area_spheroid_matches_postgis() {
        assert_matches_reference(
            st_area_spheroid(&unit_square_4326()).unwrap(),
            12_308_778_361.469_454,
        );
    }

    #[test]
    fn st_perimeter_spheroid_matches_postgis() {
        assert_matches_reference(
            st_perimeter_spheroid(&unit_square_4326()).unwrap(),
            443_770.917_248_302,
        );
    }

    #[test]
    fn st_area_sphere_matches_exact_spherical_area() {
        assert_matches_reference(
            st_area_sphere(&unit_square_4326()).unwrap(),
            12_364_031_909.465_616,
        );
    }

    #[test]
    fn st_perimeter_sphere_matches_haversine_rings() {
        assert_matches_reference(
            st_perimeter_sphere(&unit_square_4326()).unwrap(),
            444_763.384_955_006_4,
        );
    }

    #[test]
    fn spheroid_length_beats_sphere_length_against_postgis() {
        // The whole point of the ellipsoid variant: the sphere is 0.22% high
        // on this line, so the two must not collapse onto the same number.
        let line = geom_from_text("LINESTRING(0 0, 1 1)", Some(4326)).unwrap();
        let sphere = st_length_sphere(&line).unwrap();
        let spheroid = st_length_spheroid(&line).unwrap();
        assert!(sphere > spheroid, "sphere {sphere} spheroid {spheroid}");
        assert!((sphere / spheroid - 1.0) > 1e-3);
    }

    #[test]
    fn st_length_spheroid_sums_multilinestring() {
        let multi = geom_from_text("MULTILINESTRING((0 0, 1 1),(1 1, 2 2))", Some(4326)).unwrap();
        assert_matches_reference(st_length_spheroid(&multi).unwrap(), 313_775.717_693_227);
    }

    #[test]
    fn spheroid_area_subtracts_holes_and_perimeter_adds_them() {
        let holed = geom_from_text(
            "POLYGON((0 0,1 0,1 1,0 1,0 0),(0.25 0.25,0.75 0.25,0.75 0.75,0.25 0.75,0.25 0.25))",
            Some(4326),
        )
        .unwrap();
        assert_matches_reference(st_area_spheroid(&holed).unwrap(), 9_231_614_224.814_873);
        assert_matches_reference(
            st_perimeter_spheroid(&holed).unwrap(),
            665_659.512_548_929_4,
        );
    }

    #[test]
    fn sphere_area_subtracts_holes() {
        let holed = geom_from_text(
            "POLYGON((0 0,1 0,1 1,0 1,0 0),(0.25 0.25,0.75 0.25,0.75 0.75,0.25 0.75,0.25 0.25))",
            Some(4326),
        )
        .unwrap();
        let solid = st_area_sphere(&unit_square_4326()).unwrap();
        let hole_only = geom_from_text(
            "POLYGON((0.25 0.25,0.75 0.25,0.75 0.75,0.25 0.75,0.25 0.25))",
            Some(4326),
        )
        .unwrap();
        assert_matches_reference(
            st_area_sphere(&holed).unwrap(),
            solid - st_area_sphere(&hole_only).unwrap(),
        );
    }

    #[test]
    fn spheroid_measures_sum_over_multipolygon() {
        let multi = geom_from_text(
            "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 2,3 2,3 3,2 3,2 2)))",
            Some(4326),
        )
        .unwrap();
        assert_matches_reference(st_area_spheroid(&multi).unwrap(), 24_606_608_733.575_493);
        assert_matches_reference(
            st_perimeter_spheroid(&multi).unwrap(),
            887_343.826_738_655_1,
        );
    }

    #[test]
    fn sphere_measures_sum_over_multipolygon() {
        // PostGIS's spherical area is 0.67% off the true spherical value, so
        // there is no constant to read. The contract that matters is that the
        // parts are summed, not that one of them is dropped.
        let parts = [
            "POLYGON((0 0,1 0,1 1,0 1,0 0))",
            "POLYGON((2 2,3 2,3 3,2 3,2 2))",
        ];
        let multi = geom_from_text(
            "MULTIPOLYGON(((0 0,1 0,1 1,0 1,0 0)),((2 2,3 2,3 3,2 3,2 2)))",
            Some(4326),
        )
        .unwrap();
        let mut area = 0.0;
        let mut perimeter = 0.0;
        for part in parts {
            let blob = geom_from_text(part, Some(4326)).unwrap();
            area += st_area_sphere(&blob).unwrap();
            perimeter += st_perimeter_sphere(&blob).unwrap();
        }
        assert_matches_reference(st_area_sphere(&multi).unwrap(), area);
        assert_matches_reference(st_perimeter_sphere(&multi).unwrap(), perimeter);
        // Both parts really are distinct, so the sum is not one part twice.
        assert!(area > st_area_sphere(&geom_from_text(parts[0], Some(4326)).unwrap()).unwrap());
    }

    #[test]
    fn areas_are_positive_regardless_of_ring_winding() {
        // PostGIS answers the same positive area for either winding. geo's
        // signed area flips sign, so the implementation has to take the
        // magnitude rather than trusting the ring order.
        let ccw = unit_square_4326();
        let cw = geom_from_text("POLYGON((0 0,0 1,1 1,1 0,0 0))", Some(4326)).unwrap();
        assert_matches_reference(
            st_area_spheroid(&cw).unwrap(),
            st_area_spheroid(&ccw).unwrap(),
        );
        assert_matches_reference(st_area_sphere(&cw).unwrap(), st_area_sphere(&ccw).unwrap());
    }

    #[test]
    fn curved_measures_require_srid_4326() {
        let line = geom_from_text("LINESTRING(0 0, 1 1)", None).unwrap();
        let poly = geom_from_text("POLYGON((0 0,1 0,1 1,0 1,0 0))", None).unwrap();
        for err in [
            st_length_spheroid(&line).expect_err("SRID-less line must error"),
            st_area_spheroid(&poly).expect_err("SRID-less polygon must error"),
            st_perimeter_spheroid(&poly).expect_err("SRID-less polygon must error"),
            st_area_sphere(&poly).expect_err("SRID-less polygon must error"),
            st_perimeter_sphere(&poly).expect_err("SRID-less polygon must error"),
        ] {
            assert!(
                format!("{err}").contains("requires SRID 4326"),
                "unexpected error: {err}"
            );
        }
    }

    #[test]
    fn curved_measures_reject_shapes_they_cannot_measure() {
        let line = geom_from_text("LINESTRING(0 0,1 1)", Some(4326)).unwrap();
        let poly = unit_square_4326();
        let point = st_point(0.0, 0.0, Some(4326)).unwrap();

        for err in [
            st_length_spheroid(&poly).expect_err("polygon has no geodesic length"),
            st_length_spheroid(&point).expect_err("point has no geodesic length"),
        ] {
            assert!(
                format!("{err}").contains("LineString or MultiLineString"),
                "unexpected error: {err}"
            );
        }

        for err in [
            st_area_spheroid(&line).expect_err("line has no geodesic area"),
            st_perimeter_spheroid(&line).expect_err("line has no geodesic perimeter"),
            st_area_sphere(&point).expect_err("point has no spherical area"),
            st_perimeter_sphere(&point).expect_err("point has no spherical perimeter"),
        ] {
            assert!(
                format!("{err}").contains("Polygon or MultiPolygon"),
                "unexpected error: {err}"
            );
        }
    }

    #[test]
    fn curved_measures_reject_out_of_range_latitude() {
        // Karney returns NaN past the pole and Haversine a wrong finite
        // number, so both models have to refuse the vertex outright.
        let line = geom_from_text("LINESTRING(0 0, 10 95)", Some(4326)).unwrap();
        let poly = geom_from_text("POLYGON((0 0,1 0,1 95,0 95,0 0))", Some(4326)).unwrap();
        for err in [
            st_length_spheroid(&line).expect_err("out-of-range latitude must error"),
            st_area_spheroid(&poly).expect_err("out-of-range latitude must error"),
            st_perimeter_spheroid(&poly).expect_err("out-of-range latitude must error"),
            st_area_sphere(&poly).expect_err("out-of-range latitude must error"),
            st_perimeter_sphere(&poly).expect_err("out-of-range latitude must error"),
        ] {
            assert!(
                format!("{err}").contains("latitude"),
                "unexpected error: {err}"
            );
        }
    }

    #[test]
    fn curved_measures_of_empty_shapes_are_zero() {
        let empty_line = geom_from_text("LINESTRING EMPTY", Some(4326)).unwrap();
        let empty_poly = geom_from_text("POLYGON EMPTY", Some(4326)).unwrap();
        assert_eq!(st_length_spheroid(&empty_line).unwrap(), 0.0);
        assert_eq!(st_area_spheroid(&empty_poly).unwrap(), 0.0);
        assert_eq!(st_perimeter_spheroid(&empty_poly).unwrap(), 0.0);
        assert_eq!(st_area_sphere(&empty_poly).unwrap(), 0.0);
        assert_eq!(st_perimeter_sphere(&empty_poly).unwrap(), 0.0);
    }
}