Skip to content

Commit 3699534

Browse files
Mavrick-Fclaude
andcommitted
fix(data): FlatGeobuf mixed points start the export again, streamed too
Review of #1778: the pre-scan also matched lines and polygons in a point layer, and a layer exported a chunk at a time still failed. The writer now settles a point layer's type from its first point and, should a point of the other kind follow, starts again (feeding the features again) with each feature's own type, as the GeoPackage writer does; nothing reaches the output before the last feature. On that run a line or polygon in a point layer is refused. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 7db213a commit 3699534

1 file changed

Lines changed: 79 additions & 15 deletions

File tree

‎crates/data/src/source/fgb.rs‎

Lines changed: 79 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -683,9 +683,7 @@ pub fn write(ds: &crate::Dataset) -> Result<Vec<u8>> {
683683
/// the file saying `crs`.
684684
pub fn write_in(ds: &crate::Dataset, crs: Crs) -> Result<Vec<u8>> {
685685
let mut out = Vec::new();
686-
let has =
687-
|multi: bool| ds.features.iter().filter_map(|f| f.geometry.as_ref()).any(|g| matches!(g, crate::Geometry::MultiPoint(_)) == multi);
688-
write_features_typed(&ds.name, ds.geometry_type, &ds.fields, crs, has(true) && has(false), &mut out, &mut |add| add(&ds.features))?;
686+
write_features(&ds.name, ds.geometry_type, &ds.fields, crs, &mut out, &mut |add| add(&ds.features))?;
689687
Ok(out)
690688
}
691689

@@ -705,6 +703,11 @@ fn writable(browser: bool) -> Result<()> {
705703
/// temporary file and only its index entry in memory, so a whole layer needn't be held. The
706704
/// writer needs that file whether or not it writes an index, and the web app has no files, so
707705
/// there a FlatGeobuf is refused rather than written.
706+
///
707+
/// A point layer's file takes the type of its first point. Should a later one be of the other
708+
/// kind (a multipoint after points, or a point after multipoints), the export starts again
709+
/// (feeding the features again) with each feature's type in the file, which a file of one type
710+
/// can't hold. Nothing reaches `out` before the last feature, so the first run leaves it empty.
708711
pub(crate) fn write_features(
709712
name: &str,
710713
geometry_type: GeometryType,
@@ -713,23 +716,29 @@ pub(crate) fn write_features(
713716
out: &mut dyn std::io::Write,
714717
feed: &mut dyn FnMut(&mut dyn FnMut(&[Feature]) -> Result<()>) -> Result<()>,
715718
) -> Result<usize> {
716-
write_features_typed(name, geometry_type, fields, crs, false, out, feed)
719+
for mixed_points in [false, true] {
720+
if let Some(left_out) = write_run(name, geometry_type, fields, crs, mixed_points, out, feed)? {
721+
return Ok(left_out);
722+
}
723+
}
724+
Err(DataError::Format("FlatGeobuf: the export didn't settle on a geometry type".into()))
717725
}
718726

719-
/// [`write_features`], each feature's geometry type in the file when `mixed_points`: a point
720-
/// layer holding both points and multipoints, which a file of one geometry type can't (its type
721-
/// is the first feature's). Otherwise the file has one type, as readers expect of a layer. A
722-
/// layer read in place isn't looked over first, so one that mixes them still fails.
727+
/// One run of [`write_features`], each feature's geometry type in the file when `mixed_points`:
728+
/// how many were left out, or `None` when a point layer turned out to mix points and
729+
/// multipoints and the export must start again so. With `mixed_points`, a point layer's
730+
/// geometry of another kind (a line, a polygon) is refused: a file of mixed types is read as
731+
/// the layer of its first feature's kind.
723732
#[allow(clippy::too_many_arguments)]
724-
fn write_features_typed(
733+
fn write_run(
725734
name: &str,
726735
geometry_type: GeometryType,
727736
fields: &[Field],
728737
crs: Crs,
729738
mixed_points: bool,
730739
out: &mut dyn std::io::Write,
731740
feed: &mut dyn FnMut(&mut dyn FnMut(&[Feature]) -> Result<()>) -> Result<()>,
732-
) -> Result<usize> {
741+
) -> Result<Option<usize>> {
733742
use flatgeobuf::geozero::wkb::Wkb;
734743
use flatgeobuf::{FgbCrs, FgbWriter, FgbWriterOptions, GeometryType as G};
735744
writable(cfg!(target_arch = "wasm32"))?;
@@ -743,7 +752,7 @@ fn write_features_typed(
743752
let code = i32::from(crs.epsg());
744753
let options = FgbWriterOptions {
745754
crs: FgbCrs { org: (code > 0).then_some("EPSG"), code, wkt: wkt.as_deref(), ..Default::default() },
746-
detect_type: !(mixed_points && geometry_type == GeometryType::Point),
755+
detect_type: !mixed_points,
747756
..Default::default()
748757
};
749758
let mut w = FgbWriter::create_with_options(name, ty, options).map_err(err)?;
@@ -756,14 +765,35 @@ fn write_features_typed(
756765
};
757766
w.add_column(&f.name, t, |_, c| c.nullable = true);
758767
}
759-
let mut left_out = 0;
760-
feed(&mut |features| {
768+
let (mut left_out, mut first_multi, mut again) = (0, None, false);
769+
let fed = feed(&mut |features| {
761770
for feat in features {
762771
crate::progress::step(1)?;
763772
let Some(g) = &feat.geometry else {
764773
left_out += 1;
765774
continue;
766775
};
776+
if geometry_type == GeometryType::Point {
777+
let multi = match g {
778+
crate::Geometry::Point(_) => Some(false),
779+
crate::Geometry::MultiPoint(_) => Some(true),
780+
_ => None,
781+
};
782+
match (multi, mixed_points) {
783+
(Some(m), false) if *first_multi.get_or_insert(m) != m => {
784+
again = true;
785+
// Stops the traversal; the export starts again.
786+
return Err(DataError::Format("FlatGeobuf: starting again".into()));
787+
}
788+
(None, true) => {
789+
return Err(DataError::Format(format!(
790+
"FlatGeobuf: feature {} of a point layer isn't a point or multipoint",
791+
feat.id
792+
)));
793+
}
794+
_ => {}
795+
}
796+
}
767797
let mut failed = None;
768798
w.add_feature_geom(Wkb(wkb::encode(g)), |out| {
769799
use flatgeobuf::geozero::PropertyProcessor;
@@ -786,9 +816,13 @@ fn write_features_typed(
786816
}
787817
}
788818
Ok(())
789-
})?;
819+
});
820+
if again {
821+
return Ok(None);
822+
}
823+
fed?;
790824
w.write(out).map_err(err)?;
791-
Ok(left_out)
825+
Ok(Some(left_out))
792826
}
793827

794828
#[cfg(test)]
@@ -822,4 +856,34 @@ mod write_tests {
822856
let header = flatgeobuf::FgbReader::open(std::io::Cursor::new(write_in(&points, Crs::LonLat).unwrap())).unwrap();
823857
assert_eq!(header.header().geometry_type(), flatgeobuf::GeometryType::Point);
824858
}
859+
860+
/// Fed a chunk at a time (a layer read in place), the multipoint arrives after the point
861+
/// has set the file's type: the export starts again and writes both. A line in a point layer
862+
/// isn't written into a file of mixed types, which would read back as a line layer.
863+
#[test]
864+
fn a_streamed_point_layer_mixing_points_and_multipoints_starts_again() {
865+
use crate::{Coord, Geometry};
866+
let chunks = [
867+
vec![Feature { id: 1, geometry: Some(Geometry::Point(Coord::new(1.0, 2.0))), attrs: vec![] }],
868+
vec![Feature { id: 2, geometry: Some(Geometry::MultiPoint(vec![Coord::new(3.0, 4.0), Coord::new(5.0, 6.0)])), attrs: vec![] }],
869+
];
870+
let mut runs = 0;
871+
let mut out = Vec::new();
872+
write_features("m", GeometryType::Point, &[], Crs::LonLat, &mut out, &mut |add| {
873+
runs += 1;
874+
chunks.iter().try_for_each(|c| add(c))
875+
})
876+
.unwrap();
877+
assert_eq!(runs, 2);
878+
let (back, _) = crate::io::read_bytes("m.fgb", &out).unwrap();
879+
let mut got: Vec<_> = back.features.iter().filter_map(|f| f.geometry.clone()).collect();
880+
got.sort_by_key(|g| matches!(g, Geometry::MultiPoint(_)));
881+
assert_eq!(got, chunks.iter().flatten().filter_map(|f| f.geometry.clone()).collect::<Vec<_>>());
882+
let line = Feature { id: 3, geometry: Some(Geometry::Line(vec![vec![Coord::new(0.0, 0.0), Coord::new(1.0, 1.0)]])), attrs: vec![] };
883+
let with_line = [chunks[0].clone(), chunks[1].clone(), vec![line]];
884+
let e = write_features("m", GeometryType::Point, &[], Crs::LonLat, &mut Vec::new(), &mut |add| {
885+
with_line.iter().try_for_each(|c| add(c))
886+
});
887+
assert!(matches!(&e, Err(DataError::Format(m)) if m.contains("feature 3 of a point layer isn't a point")), "{e:?}");
888+
}
825889
}

0 commit comments

Comments
 (0)