oxigdal 0.1.4

Pure Rust geospatial data abstraction library — the Rust alternative to GDAL
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
//! Streaming / iterator APIs for large geospatial datasets.
//!
//! This module provides two iterator types and an extension trait:
//!
//! - [`FeatureStream`] — lazy iterator over vector features (WKB + properties)
//! - [`TileStream`] — iterator over raster tile coordinates at a given zoom level
//! - [`StreamingExt`] — extension trait on [`OpenedDataset`]
//!
//! # Tile coordinate conventions
//!
//! [`TileStream`] follows the Web Map Tile Service (WMTS / XYZ) slippy-map
//! convention:
//!
//! - Zoom level 0: one tile covering the whole world
//! - At zoom `z`, there are `2^z × 2^z` tiles
//! - Tile `(x, y)` covers the rectangle
//!   `[x/2^z … (x+1)/2^z] × [y/2^z … (y+1)/2^z]` in normalised coordinates
//!
//! # Examples
//!
//! ```rust,no_run
//! use oxigdal::open::open;
//! use oxigdal::streaming::StreamingExt;
//!
//! # fn main() -> oxigdal::Result<()> {
//! let ds = open("world.geojson")?;
//! let mut stream = ds.features()?;
//! while let Some(feat) = stream.next() {
//!     let feat = feat?;
//!     println!("feature has {} properties", feat.properties.len());
//! }
//! # Ok(())
//! # }
//! ```

use std::collections::HashMap;

use oxigdal_core::error::OxiGdalError;
use serde_json::Value as JsonValue;

use crate::{Result, open::OpenedDataset};

// ─── StreamingFeature ─────────────────────────────────────────────────────────

/// A single vector feature returned by a [`FeatureStream`].
///
/// The geometry is encoded as WKB (Well-Known Binary) bytes, which is a compact
/// binary representation understood by all major GIS tools.  If the feature has
/// no geometry (attribute-only), `geometry` is `None`.
///
/// Properties are stored as a `HashMap<String, serde_json::Value>` mirroring
/// the GeoJSON feature properties object.
#[derive(Debug, Clone)]
pub struct StreamingFeature {
    /// Optional WKB-encoded geometry bytes.
    ///
    /// `None` when the feature carries attribute data only.
    pub geometry: Option<Vec<u8>>,

    /// Feature attribute values keyed by field name.
    ///
    /// Values use `serde_json::Value` to represent any JSON-compatible type
    /// (string, number, boolean, null, array, object).
    pub properties: HashMap<String, JsonValue>,

    /// Optional feature identifier (from FID, `@id`, etc.)
    pub id: Option<String>,
}

impl StreamingFeature {
    /// Create a new feature with the given geometry and properties.
    pub fn new(geometry: Option<Vec<u8>>, properties: HashMap<String, JsonValue>) -> Self {
        Self {
            geometry,
            properties,
            id: None,
        }
    }

    /// Create a feature with an identifier.
    pub fn with_id(mut self, id: impl Into<String>) -> Self {
        self.id = Some(id.into());
        self
    }

    /// Return `true` if this feature carries a geometry.
    pub fn has_geometry(&self) -> bool {
        self.geometry.is_some()
    }

    /// Return the WKB geometry length in bytes, or 0 if no geometry.
    pub fn geometry_byte_len(&self) -> usize {
        self.geometry.as_ref().map_or(0, |g| g.len())
    }
}

// ─── FeatureStream ────────────────────────────────────────────────────────────

/// Lazy iterator over features in a vector dataset.
///
/// Each call to [`Iterator::next`] yields `Some(Result<StreamingFeature>)`.
/// Errors propagate naturally through the `Result` wrapper, allowing consumers
/// to decide whether to abort or skip on error.
///
/// Obtained via [`StreamingExt::features`].
pub struct FeatureStream {
    /// Internal buffer of pre-loaded features.
    ///
    /// In a real driver implementation this would be replaced with a cursor
    /// into the underlying file/database.  For now features are buffered in
    /// memory at construction time.
    inner: std::vec::IntoIter<StreamingFeature>,
    /// Total number of features this stream was created with.
    total_count: usize,
    /// How many features have been yielded so far.
    yielded: usize,
}

impl FeatureStream {
    /// Create a [`FeatureStream`] from a pre-built `Vec<StreamingFeature>`.
    ///
    /// Used by driver implementations and tests.
    pub fn from_vec(features: Vec<StreamingFeature>) -> Self {
        let total_count = features.len();
        Self {
            inner: features.into_iter(),
            total_count,
            yielded: 0,
        }
    }

    /// Create an empty feature stream.
    pub fn empty() -> Self {
        Self::from_vec(Vec::new())
    }

    /// Return the total number of features this stream was seeded with.
    ///
    /// Note: for streaming sources where the total is unknown, this returns 0.
    pub fn total_count(&self) -> usize {
        self.total_count
    }

    /// Return the number of features that have been yielded so far.
    pub fn yielded_count(&self) -> usize {
        self.yielded
    }

    /// Return the number of remaining features, if known.
    pub fn remaining(&self) -> usize {
        self.total_count.saturating_sub(self.yielded)
    }
}

impl Iterator for FeatureStream {
    type Item = Result<StreamingFeature>;

    fn next(&mut self) -> Option<Self::Item> {
        match self.inner.next() {
            Some(feature) => {
                self.yielded += 1;
                Some(Ok(feature))
            }
            None => None,
        }
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = self.remaining();
        (remaining, Some(remaining))
    }
}

// ─── RasterTile ──────────────────────────────────────────────────────────────

/// A single raster tile at a specific zoom level and tile coordinate.
///
/// Follows the XYZ / WMTS slippy-map convention used by web mapping libraries
/// (Leaflet, MapLibre, OpenLayers, etc.).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RasterTile {
    /// Tile column index (0 … 2^zoom − 1, left to right)
    pub x: u32,
    /// Tile row index (0 … 2^zoom − 1, top to bottom)
    pub y: u32,
    /// Zoom level (0 = world overview, higher = more detail)
    pub zoom: u8,
    /// Raw tile image bytes (PNG, JPEG, WebP, etc.)
    pub data: Vec<u8>,
}

impl RasterTile {
    /// Return the number of tiles per axis at this zoom level: `2^zoom`.
    ///
    /// Saturates at [`u32::MAX`] for zoom ≥ 32 (which is never useful in
    /// practice, but avoids overflow).
    pub fn tiles_per_axis(zoom: u8) -> u32 {
        if zoom >= 32 { u32::MAX } else { 1u32 << zoom }
    }

    /// Return the normalised bounding box `(min_x, min_y, max_x, max_y)` for
    /// this tile, where coordinates are in the range `[0.0, 1.0]`.
    ///
    /// Useful for converting to geographic coordinates when combined with the
    /// dataset's [`crate::DatasetInfo::geotransform`].
    pub fn normalised_bbox(&self) -> (f64, f64, f64, f64) {
        let n = Self::tiles_per_axis(self.zoom) as f64;
        let min_x = self.x as f64 / n;
        let min_y = self.y as f64 / n;
        let max_x = (self.x + 1) as f64 / n;
        let max_y = (self.y + 1) as f64 / n;
        (min_x, min_y, max_x, max_y)
    }

    /// Return `true` if the tile data is non-empty.
    pub fn has_data(&self) -> bool {
        !self.data.is_empty()
    }
}

// ─── TileStream ───────────────────────────────────────────────────────────────

/// Iterator over raster tile coordinates at a fixed zoom level.
///
/// Tiles are yielded in row-major order: all columns for row 0, then row 1,
/// etc. (top-left to bottom-right).
///
/// The `data` field of each [`RasterTile`] is populated with empty bytes by
/// default.  Real raster data is filled in by the driver crate when the tiles
/// are actually read from disk.
///
/// Obtained via [`StreamingExt::tiles`].
pub struct TileStream {
    /// Fixed zoom level
    zoom: u8,
    /// Current tile column
    current_x: u32,
    /// Current tile row
    current_y: u32,
    /// Maximum tile column (exclusive)
    max_x: u32,
    /// Maximum tile row (exclusive)
    max_y: u32,
    /// Number of tiles yielded so far
    yielded: u64,
}

impl TileStream {
    /// Create a new [`TileStream`] that covers all tiles at the given `zoom`.
    ///
    /// At zoom `z`, there are `2^z × 2^z` tiles.
    pub fn full_zoom(zoom: u8) -> Self {
        let dim = RasterTile::tiles_per_axis(zoom);
        Self {
            zoom,
            current_x: 0,
            current_y: 0,
            max_x: dim,
            max_y: dim,
            yielded: 0,
        }
    }

    /// Create a [`TileStream`] covering a sub-rectangle of tiles at `zoom`.
    ///
    /// `x_range` and `y_range` are `(start, end)` half-open ranges
    /// (i.e., `start..end`).
    ///
    /// # Errors
    ///
    /// Returns [`OxiGdalError::OutOfBounds`] if the range exceeds `2^zoom`.
    pub fn from_range(zoom: u8, x_range: (u32, u32), y_range: (u32, u32)) -> Result<Self> {
        let dim = RasterTile::tiles_per_axis(zoom);
        let (x_start, x_end) = x_range;
        let (y_start, y_end) = y_range;

        if x_end > dim || y_end > dim {
            return Err(OxiGdalError::OutOfBounds {
                message: format!(
                    "tile range ({x_start}..{x_end}, {y_start}..{y_end}) exceeds 2^{zoom} = {dim}"
                ),
            });
        }
        if x_start >= x_end || y_start >= y_end {
            return Err(OxiGdalError::InvalidParameter {
                parameter: "tile_range",
                message: format!(
                    "empty or inverted tile range: x={x_start}..{x_end}, y={y_start}..{y_end}"
                ),
            });
        }

        Ok(Self {
            zoom,
            current_x: x_start,
            current_y: y_start,
            max_x: x_end,
            max_y: y_end,
            yielded: 0,
        })
    }

    /// Total number of tiles this stream will produce.
    ///
    /// Returns `(max_x - start_x) × (max_y - start_y)` which may be large for
    /// high zoom levels.
    pub fn total_tiles(&self) -> u64 {
        (self.max_x - self.current_x) as u64 * (self.max_y - self.current_y) as u64 + self.yielded
    }

    /// Number of tiles yielded so far.
    pub fn yielded_count(&self) -> u64 {
        self.yielded
    }

    /// Current zoom level.
    pub fn zoom(&self) -> u8 {
        self.zoom
    }
}

impl Iterator for TileStream {
    type Item = Result<RasterTile>;

    fn next(&mut self) -> Option<Self::Item> {
        if self.current_y >= self.max_y {
            return None;
        }

        let tile = RasterTile {
            x: self.current_x,
            y: self.current_y,
            zoom: self.zoom,
            data: Vec::new(), // populated by driver when reading from disk
        };

        // Advance column; wrap to next row when at max_x
        self.current_x += 1;
        if self.current_x >= self.max_x {
            self.current_x = 0; // reset column to start of range
            self.current_y += 1;
        }

        self.yielded += 1;
        Some(Ok(tile))
    }

    fn size_hint(&self) -> (usize, Option<usize>) {
        let remaining = (self.max_x.saturating_sub(self.current_x) as u64
            + (self.max_y.saturating_sub(self.current_y).saturating_sub(1)) as u64
                * (self.max_x as u64)) as usize;
        (remaining, Some(remaining))
    }
}

// ─── StreamingExt ─────────────────────────────────────────────────────────────

// ─── GeoJSON streaming helper ─────────────────────────────────────────────────

/// Stream features from a GeoJSON file path stored in `info.path`.
///
/// When the `geojson` feature is enabled and `info.path` points to a readable
/// FeatureCollection, this returns a [`FeatureStream`] with real feature data.
/// Properties are already `serde_json::Value` in the GeoJSON driver — no
/// conversion is needed.  Geometry is encoded as ISO WKB (little-endian) using
/// [`oxigdal_geojson::Geometry::to_wkb`].
///
/// Falls back to an empty stream when:
/// - `info.path` is `None` (e.g., programmatic dataset)
/// - the `geojson` feature is disabled
/// - the file is not a FeatureCollection (single Feature / Geometry)
fn stream_geojson_features(info: &crate::DatasetInfo) -> Result<FeatureStream> {
    #[cfg(feature = "geojson")]
    {
        let path = match &info.path {
            Some(p) => p.clone(),
            None => return Ok(FeatureStream::empty()),
        };

        let file = std::fs::File::open(&path).map_err(|e| {
            OxiGdalError::Io(oxigdal_core::error::IoError::Read {
                message: format!("cannot open GeoJSON for streaming '{path}': {e}"),
            })
        })?;

        use oxigdal_geojson::GeoJsonReader;
        let buf_reader = std::io::BufReader::new(file);
        let mut reader = GeoJsonReader::without_validation(buf_reader);

        // We load the FeatureCollection into memory; for very large files the
        // caller should use the oxigdal_streaming crate instead.
        let fc = match reader.read_feature_collection() {
            Ok(fc) => fc,
            Err(_) => return Ok(FeatureStream::empty()),
        };

        let features = fc
            .features
            .into_iter()
            .map(|f| {
                let geometry = f.geometry.and_then(|g| g.to_wkb());
                let properties: HashMap<String, JsonValue> =
                    f.properties.unwrap_or_default().into_iter().collect();
                let mut sf = StreamingFeature::new(geometry, properties);
                if let Some(id) = f.id {
                    sf = sf.with_id(id.as_string());
                }
                sf
            })
            .collect::<Vec<_>>();

        Ok(FeatureStream::from_vec(features))
    }

    #[cfg(not(feature = "geojson"))]
    {
        let _ = info;
        Ok(FeatureStream::empty())
    }
}

// ─── FlatGeobuf streaming helper ─────────────────────────────────────────────

/// Stream features from a FlatGeobuf file path stored in `info.path`.
///
/// When the `flatgeobuf` feature is enabled and `info.path` points to a valid
/// FlatGeobuf file, this returns a [`FeatureStream`] with real feature data.
/// Geometry is encoded as ISO WKB (little-endian) via
/// [`oxigdal_core::vector::Geometry::to_wkb`].
/// Properties are converted from [`oxigdal_core::vector::FieldValue`] via
/// [`oxigdal_core::vector::FieldValue::to_json_value`].
///
/// Falls back to an empty stream when:
/// - `info.path` is `None`
/// - the `flatgeobuf` feature is disabled
fn stream_flatgeobuf_features(info: &crate::DatasetInfo) -> Result<FeatureStream> {
    #[cfg(feature = "flatgeobuf")]
    {
        use oxigdal_core::error::IoError;
        use oxigdal_flatgeobuf::FlatGeobufReader;

        let path = match &info.path {
            Some(p) => p.clone(),
            None => return Ok(FeatureStream::empty()),
        };

        let file = std::fs::File::open(&path).map_err(|e| {
            OxiGdalError::Io(IoError::Read {
                message: format!("cannot open FlatGeobuf for streaming '{path}': {e}"),
            })
        })?;

        let mut reader = FlatGeobufReader::new(file).map_err(|e| OxiGdalError::Internal {
            message: e.to_string(),
        })?;

        let iter = reader.features().map_err(|e| OxiGdalError::Internal {
            message: e.to_string(),
        })?;

        let features = iter
            .filter_map(|result| {
                result
                    .map_err(|e| OxiGdalError::Internal {
                        message: e.to_string(),
                    })
                    .ok()
            })
            .map(|f| {
                let geometry = f.geometry.map(|g| g.to_wkb());
                let properties: HashMap<String, JsonValue> = f
                    .properties
                    .into_iter()
                    .map(|(k, v)| (k, v.to_json_value()))
                    .collect();
                StreamingFeature::new(geometry, properties)
            })
            .collect::<Vec<_>>();

        Ok(FeatureStream::from_vec(features))
    }

    #[cfg(not(feature = "flatgeobuf"))]
    {
        let _ = info;
        Ok(FeatureStream::empty())
    }
}

// ─── Shapefile streaming helper ───────────────────────────────────────────────

/// Stream features from a Shapefile path stored in `info.path`.
///
/// When the `shapefile` feature is enabled and `info.path` points to a valid
/// Shapefile, this returns a [`FeatureStream`] with real feature data.
/// `info.path` may carry the `.shp` extension; it is stripped before
/// passing to [`oxigdal_shapefile::ShapefileReader::open`], which appends
/// the correct per-file extensions itself.
/// Geometry is encoded as ISO WKB (little-endian).
/// Properties are converted from [`oxigdal_core::vector::FieldValue`] via
/// [`oxigdal_core::vector::FieldValue::to_json_value`].
///
/// Falls back to an empty stream when:
/// - `info.path` is `None`
/// - the `shapefile` feature is disabled
fn stream_shapefile_features(info: &crate::DatasetInfo) -> Result<FeatureStream> {
    #[cfg(feature = "shapefile")]
    {
        use oxigdal_core::error::IoError;
        use oxigdal_shapefile::ShapefileReader;

        let raw_path = match &info.path {
            Some(p) => p.clone(),
            None => return Ok(FeatureStream::empty()),
        };

        // ShapefileReader::open() expects a base path without extension
        // (it appends .shp, .dbf, .shx itself). Strip a trailing .shp
        // extension if present.
        let base_path = {
            let p = std::path::Path::new(&raw_path);
            match p.extension().and_then(|e| e.to_str()) {
                Some("shp") | Some("SHP") => p.with_extension("").to_string_lossy().into_owned(),
                _ => raw_path.clone(),
            }
        };

        let reader = ShapefileReader::open(&base_path).map_err(|e| {
            OxiGdalError::Io(IoError::Read {
                message: format!("cannot open Shapefile for streaming '{base_path}': {e}"),
            })
        })?;

        let shapefile_features = reader.read_features().map_err(|e| OxiGdalError::Internal {
            message: e.to_string(),
        })?;

        let features = shapefile_features
            .into_iter()
            .map(|sf| {
                let geometry = sf.geometry.map(|g| g.to_wkb());
                let properties: HashMap<String, JsonValue> = sf
                    .attributes
                    .into_iter()
                    .map(|(k, v)| (k, v.to_json_value()))
                    .collect();
                StreamingFeature::new(geometry, properties)
            })
            .collect::<Vec<_>>();

        Ok(FeatureStream::from_vec(features))
    }

    #[cfg(not(feature = "shapefile"))]
    {
        let _ = info;
        Ok(FeatureStream::empty())
    }
}

/// Extension trait that adds streaming iterators to [`OpenedDataset`].
///
/// Import this trait to call `.features()` and `.tiles()` on an opened dataset.
///
/// ```rust,no_run
/// use oxigdal::open::open;
/// use oxigdal::streaming::StreamingExt;
///
/// # fn main() -> oxigdal::Result<()> {
/// let ds = open("world.geojson")?;
/// let count = ds.features()?.count();
/// println!("{count} features");
/// # Ok(())
/// # }
/// ```
pub trait StreamingExt {
    /// Return a streaming iterator over vector features in this dataset.
    ///
    /// # Errors
    ///
    /// Returns [`OxiGdalError::NotSupported`] when called on a raster-only
    /// dataset.
    fn features(&self) -> Result<FeatureStream>;

    /// Return an iterator over tile coordinates at the given `zoom` level.
    ///
    /// The data field of each returned [`RasterTile`] will be empty — actual
    /// pixel data is filled in by the driver crate.
    ///
    /// # Errors
    ///
    /// Returns [`OxiGdalError::NotSupported`] when called on a vector-only
    /// dataset.
    fn tiles(&self, zoom: u8) -> Result<TileStream>;
}

impl StreamingExt for OpenedDataset {
    fn features(&self) -> Result<FeatureStream> {
        match self {
            OpenedDataset::GeoJson(info) => stream_geojson_features(info),
            OpenedDataset::Shapefile(info) => stream_shapefile_features(info),
            OpenedDataset::FlatGeobuf(info) => stream_flatgeobuf_features(info),
            OpenedDataset::GeoPackage(_)
            | OpenedDataset::GeoParquet(_)
            | OpenedDataset::Stac(_)
            | OpenedDataset::Unknown(_) => {
                // TODO: wire real feature streaming for GeoPackage / GeoParquet / STAC
                Ok(FeatureStream::empty())
            }
            other => Err(OxiGdalError::NotSupported {
                operation: format!(
                    "features() is not supported for raster format '{}'",
                    other.format().driver_name()
                ),
            }),
        }
    }

    fn tiles(&self, zoom: u8) -> Result<TileStream> {
        match self {
            OpenedDataset::GeoTiff(_)
            | OpenedDataset::Jpeg2000(_)
            | OpenedDataset::NetCdf(_)
            | OpenedDataset::Hdf5(_)
            | OpenedDataset::Zarr(_)
            | OpenedDataset::Grib(_)
            | OpenedDataset::Vrt(_)
            | OpenedDataset::Unknown(_) => Ok(TileStream::full_zoom(zoom)),
            other => Err(OxiGdalError::NotSupported {
                operation: format!(
                    "tiles() is not supported for vector format '{}'",
                    other.format().driver_name()
                ),
            }),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::open::open;
    use std::io::Write;

    fn make_temp_file(name: &str, content: &[u8]) -> std::path::PathBuf {
        let dir = std::env::temp_dir();
        let path = dir.join(name);
        let mut f = std::fs::File::create(&path).expect("create");
        f.write_all(content).expect("write");
        path
    }

    // ── FeatureStream ─────────────────────────────────────────────────────────

    #[test]
    fn test_feature_stream_empty() {
        let stream = FeatureStream::empty();
        assert_eq!(stream.total_count(), 0);
        assert_eq!(stream.remaining(), 0);
    }

    #[test]
    fn test_feature_stream_from_vec_yields_all() {
        let features = vec![
            StreamingFeature::new(None, HashMap::new()),
            StreamingFeature::new(None, HashMap::new()),
            StreamingFeature::new(None, HashMap::new()),
        ];
        let mut stream = FeatureStream::from_vec(features);
        assert_eq!(stream.total_count(), 3);
        assert_eq!(stream.yielded_count(), 0);

        let first = stream.next().expect("has first").expect("no error");
        assert!(first.geometry.is_none());
        assert_eq!(stream.yielded_count(), 1);
        assert_eq!(stream.remaining(), 2);

        stream.next().expect("second").expect("no error");
        stream.next().expect("third").expect("no error");
        assert!(stream.next().is_none(), "stream exhausted");
    }

    #[test]
    fn test_feature_stream_with_properties() {
        let mut props = HashMap::new();
        props.insert("name".to_string(), JsonValue::String("Tokyo".to_string()));
        props.insert(
            "pop".to_string(),
            JsonValue::Number(serde_json::Number::from(9_273_000u64)),
        );

        let feature = StreamingFeature::new(None, props);
        assert_eq!(feature.properties["name"], "Tokyo");
        assert!(!feature.has_geometry());
        assert_eq!(feature.geometry_byte_len(), 0);
    }

    #[test]
    fn test_feature_stream_with_geometry() {
        // Minimal WKB point: byte order (1) + geometry type (1=Point) + x + y
        let wkb: Vec<u8> = vec![
            0x01, // little-endian
            0x01, 0x00, 0x00, 0x00, // WKBPoint
            0x00, 0x00, 0x00, 0x00, 0x00, 0x40, 0x5E, 0x40, // x = 120.0
            0x00, 0x00, 0x00, 0x00, 0x00, 0x80, 0x35, 0x40, // y = 35.0
        ];
        let feature = StreamingFeature::new(Some(wkb.clone()), HashMap::new());
        assert!(feature.has_geometry());
        assert_eq!(feature.geometry_byte_len(), wkb.len());
    }

    #[test]
    fn test_feature_with_id() {
        let feature = StreamingFeature::new(None, HashMap::new()).with_id("feature-001");
        assert_eq!(feature.id.as_deref(), Some("feature-001"));
    }

    #[test]
    fn test_feature_stream_size_hint() {
        let features = vec![
            StreamingFeature::new(None, HashMap::new()),
            StreamingFeature::new(None, HashMap::new()),
        ];
        let mut stream = FeatureStream::from_vec(features);
        assert_eq!(stream.size_hint(), (2, Some(2)));
        stream.next();
        assert_eq!(stream.size_hint(), (1, Some(1)));
    }

    // ── RasterTile ────────────────────────────────────────────────────────────

    #[test]
    fn test_raster_tile_tiles_per_axis() {
        assert_eq!(RasterTile::tiles_per_axis(0), 1);
        assert_eq!(RasterTile::tiles_per_axis(1), 2);
        assert_eq!(RasterTile::tiles_per_axis(8), 256);
        assert_eq!(RasterTile::tiles_per_axis(16), 65_536);
    }

    #[test]
    fn test_raster_tile_normalised_bbox_zoom0() {
        let tile = RasterTile {
            x: 0,
            y: 0,
            zoom: 0,
            data: vec![],
        };
        let (min_x, min_y, max_x, max_y) = tile.normalised_bbox();
        assert!((min_x - 0.0).abs() < 1e-9);
        assert!((min_y - 0.0).abs() < 1e-9);
        assert!((max_x - 1.0).abs() < 1e-9);
        assert!((max_y - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_raster_tile_normalised_bbox_zoom1() {
        let tile = RasterTile {
            x: 1,
            y: 0,
            zoom: 1,
            data: vec![],
        };
        let (min_x, _min_y, max_x, _max_y) = tile.normalised_bbox();
        assert!((min_x - 0.5).abs() < 1e-9);
        assert!((max_x - 1.0).abs() < 1e-9);
    }

    #[test]
    fn test_raster_tile_has_data() {
        let empty_tile = RasterTile {
            x: 0,
            y: 0,
            zoom: 1,
            data: vec![],
        };
        assert!(!empty_tile.has_data());

        let data_tile = RasterTile {
            x: 0,
            y: 0,
            zoom: 1,
            data: vec![0xFF],
        };
        assert!(data_tile.has_data());
    }

    // ── TileStream ────────────────────────────────────────────────────────────

    #[test]
    fn test_tile_stream_zoom0_yields_one_tile() {
        let mut stream = TileStream::full_zoom(0);
        assert_eq!(stream.zoom(), 0);
        let tile = stream.next().expect("has tile").expect("no error");
        assert_eq!((tile.x, tile.y, tile.zoom), (0, 0, 0));
        assert!(stream.next().is_none(), "only one tile at zoom 0");
    }

    #[test]
    fn test_tile_stream_zoom1_yields_four_tiles() {
        let stream = TileStream::full_zoom(1);
        let tiles: Vec<_> = stream.map(|t| t.expect("ok")).collect();
        assert_eq!(tiles.len(), 4, "2^1 × 2^1 = 4 tiles");
    }

    #[test]
    fn test_tile_stream_row_major_order() {
        let stream = TileStream::full_zoom(1);
        let tiles: Vec<_> = stream.map(|t| t.expect("ok")).collect();
        assert_eq!((tiles[0].x, tiles[0].y), (0, 0));
        assert_eq!((tiles[1].x, tiles[1].y), (1, 0));
        assert_eq!((tiles[2].x, tiles[2].y), (0, 1));
        assert_eq!((tiles[3].x, tiles[3].y), (1, 1));
    }

    #[test]
    fn test_tile_stream_zoom2_total() {
        let stream = TileStream::full_zoom(2);
        assert_eq!(stream.count(), 16, "2^2 × 2^2 = 16");
    }

    #[test]
    fn test_tile_stream_from_range_valid() {
        let stream = TileStream::from_range(3, (0, 2), (0, 2)).expect("valid range");
        let tiles: Vec<_> = stream.map(|t| t.expect("ok")).collect();
        assert_eq!(tiles.len(), 4, "2×2 sub-range");
    }

    #[test]
    fn test_tile_stream_from_range_out_of_bounds() {
        let result = TileStream::from_range(1, (0, 5), (0, 2));
        assert!(result.is_err(), "5 exceeds 2^1=2");
    }

    #[test]
    fn test_tile_stream_from_range_empty_range_error() {
        let result = TileStream::from_range(2, (1, 1), (0, 2));
        assert!(result.is_err(), "empty range start==end should fail");
    }

    #[test]
    fn test_tile_stream_yielded_count() {
        let mut stream = TileStream::full_zoom(1);
        assert_eq!(stream.yielded_count(), 0);
        stream.next();
        assert_eq!(stream.yielded_count(), 1);
        stream.next();
        assert_eq!(stream.yielded_count(), 2);
    }

    // ── StreamingExt on OpenedDataset ─────────────────────────────────────────

    #[test]
    fn test_streaming_ext_features_on_vector() {
        let path = make_temp_file("stream_ext_geojson.geojson", b"{}");
        let ds = open(&path).expect("open");
        let stream_result = ds.features();
        assert!(
            stream_result.is_ok(),
            "features() on GeoJSON should succeed"
        );
    }

    #[test]
    fn test_streaming_ext_features_on_raster_errors() {
        // Write a minimal TIFF LE header
        let bytes = [0x49u8, 0x49, 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00];
        let path = make_temp_file("stream_ext_tiff.tif", &bytes);
        let ds = open(&path).expect("open tiff");
        let result = ds.features();
        assert!(result.is_err(), "features() on raster dataset should error");
    }

    #[test]
    fn test_streaming_ext_tiles_on_raster() {
        let bytes = [0x49u8, 0x49, 0x2A, 0x00, 0x00, 0x00, 0x00, 0x00];
        let path = make_temp_file("stream_ext_tiles_tiff.tif", &bytes);
        let ds = open(&path).expect("open tiff");
        let result = ds.tiles(2);
        assert!(result.is_ok(), "tiles() on raster should succeed");
        let stream = result.expect("stream");
        assert_eq!(stream.zoom(), 2);
    }

    #[test]
    fn test_streaming_ext_tiles_on_vector_errors() {
        let path = make_temp_file("stream_ext_tiles_geojson.geojson", b"{}");
        let ds = open(&path).expect("open");
        let result = ds.tiles(2);
        assert!(result.is_err(), "tiles() on vector should error");
    }

    // ── integration: feature stream from opened dataset ───────────────────────

    #[test]
    fn test_feature_stream_collect_empty() {
        // `{}` is not a FeatureCollection, so the reader returns empty
        let path = make_temp_file("stream_collect_empty.geojson", b"{}");
        let ds = open(&path).expect("open");
        let features: Vec<_> = ds
            .features()
            .expect("features")
            .collect::<Result<Vec<_>>>()
            .expect("collect");
        assert_eq!(
            features.len(),
            0,
            "non-FeatureCollection GeoJSON returns no features"
        );
    }

    // ── GeoJSON real feature streaming ────────────────────────────────────────

    #[cfg(feature = "geojson")]
    #[test]
    fn test_geojson_streaming_feature_collection_count() {
        let content = br#"{"type":"FeatureCollection","features":[
            {"type":"Feature","geometry":{"type":"Point","coordinates":[139.7,35.7]},"properties":{"name":"Tokyo"}},
            {"type":"Feature","geometry":{"type":"Point","coordinates":[2.35,48.85]},"properties":{"name":"Paris"}}
        ]}"#;
        let path = make_temp_file("stream_fc_count.geojson", content);
        let ds = open(&path).expect("open");
        let features: Vec<_> = ds
            .features()
            .expect("features")
            .collect::<Result<Vec<_>>>()
            .expect("collect");
        assert_eq!(features.len(), 2, "should stream 2 features");
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_geojson_streaming_properties_present() {
        let content = br#"{"type":"FeatureCollection","features":[
            {"type":"Feature","geometry":null,"properties":{"city":"Berlin","pop":3600000}}
        ]}"#;
        let path = make_temp_file("stream_props.geojson", content);
        let ds = open(&path).expect("open");
        let mut stream = ds.features().expect("features");
        let feat = stream.next().expect("first feature").expect("no error");
        assert_eq!(feat.properties["city"], serde_json::json!("Berlin"));
        assert_eq!(feat.properties["pop"], serde_json::json!(3600000));
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_geojson_streaming_geometry_wkb() {
        let content = br#"{"type":"FeatureCollection","features":[
            {"type":"Feature","geometry":{"type":"Point","coordinates":[139.7,35.7]},"properties":{}}
        ]}"#;
        let path = make_temp_file("stream_wkb.geojson", content);
        let ds = open(&path).expect("open");
        let mut stream = ds.features().expect("features");
        let feat = stream.next().expect("first feature").expect("no error");
        assert!(
            feat.has_geometry(),
            "Point feature should have WKB geometry"
        );
        // WKB Point: 1 byte order + 4 type + 8 x + 8 y = 21 bytes
        assert_eq!(feat.geometry_byte_len(), 21, "WKB Point should be 21 bytes");
        // Verify byte-order flag (0x01 = LE) and geometry type (0x01000000 = Point)
        let wkb = feat.geometry.as_ref().expect("geometry");
        assert_eq!(wkb[0], 0x01, "little-endian byte-order flag");
        assert_eq!(&wkb[1..5], &1u32.to_le_bytes(), "WKB type = Point (1)");
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_geojson_streaming_null_geometry_is_none() {
        let content = br#"{"type":"FeatureCollection","features":[
            {"type":"Feature","geometry":null,"properties":{"note":"no geom"}}
        ]}"#;
        let path = make_temp_file("stream_null_geom.geojson", content);
        let ds = open(&path).expect("open");
        let mut stream = ds.features().expect("features");
        let feat = stream.next().expect("first feature").expect("no error");
        assert!(!feat.has_geometry(), "null geometry should produce None");
    }

    #[cfg(feature = "geojson")]
    #[test]
    fn test_geojson_streaming_feature_id() {
        let content = br#"{"type":"FeatureCollection","features":[
            {"type":"Feature","id":"feat-001","geometry":null,"properties":{}}
        ]}"#;
        let path = make_temp_file("stream_id.geojson", content);
        let ds = open(&path).expect("open");
        let mut stream = ds.features().expect("features");
        let feat = stream.next().expect("first feature").expect("no error");
        assert_eq!(feat.id.as_deref(), Some("feat-001"));
    }

    #[test]
    fn test_tile_stream_all_coordinates_in_range() {
        let zoom = 3u8;
        let dim = RasterTile::tiles_per_axis(zoom);
        let stream = TileStream::full_zoom(zoom);
        for tile_result in stream {
            let tile = tile_result.expect("ok");
            assert!(tile.x < dim, "x={} should be < {dim}", tile.x);
            assert!(tile.y < dim, "y={} should be < {dim}", tile.y);
        }
    }
}