geolith 0.1.5

Shared library of the geolith builders: source readers, conflation, admin areas, tile encoding and the PMTiles and MBTiles writers
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
//! `GeoTIFF` digital elevation model reader.
//!
//! Reads the elevation raster plus the georeferencing tags written by
//! photogrammetry toolchains (`OpenDroneMap`, `Pix4D`, Agisoft) and GDAL:
//! `ModelPixelScale` (33550), `ModelTiepoint` (33922),
//! `ModelTransformation` (34264), `GeoKeyDirectory` (34735) and
//! `GDAL_NODATA` (42113).

use std::fs::File;
use std::io::BufReader;
use std::path::Path;

use crate::error::{GeolithError, Result};
use tiff::decoder::{Decoder, DecodingResult};
use tiff::tags::Tag;

use crate::terrain::crs::Crs;

/// `GeoTIFF` `ModelPixelScaleTag`.
const TAG_MODEL_PIXEL_SCALE: u16 = 33550;

/// `GeoTIFF` `ModelTiepointTag`.
const TAG_MODEL_TIEPOINT: u16 = 33922;

/// `GeoTIFF` `ModelTransformationTag`.
const TAG_MODEL_TRANSFORMATION: u16 = 34264;

/// `GeoTIFF` `GeoKeyDirectoryTag`.
const TAG_GEO_KEY_DIRECTORY: u16 = 34735;

/// GDAL nodata sentinel tag.
const TAG_GDAL_NODATA: u16 = 42113;

/// `GeoKey` id for `ProjectedCSTypeGeoKey`.
const GEO_KEY_PROJECTED_CS_TYPE: u16 = 3072;

/// `GeoKey` id for `GeographicTypeGeoKey`.
const GEO_KEY_GEOGRAPHIC_TYPE: u16 = 2048;

/// Affine mapping from pixel indices to projected coordinates.
///
/// Mirrors the GDAL geotransform convention: `origin` is the outer corner of
/// the top-left pixel, `pixel_width` is positive eastward and `pixel_height`
/// is positive downward (so projected northing decreases as row increases).
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct GeoTransform {
    /// Projected x of the top-left pixel corner.
    pub origin_x: f64,
    /// Projected y of the top-left pixel corner.
    pub origin_y: f64,
    /// Projected width of one pixel.
    pub pixel_width: f64,
    /// Projected height of one pixel, positive downward.
    pub pixel_height: f64,
}

impl GeoTransform {
    /// Projected coordinate at the centre of pixel `(col, row)`.
    #[must_use]
    pub fn pixel_center(&self, col: f64, row: f64) -> (f64, f64) {
        (
            self.origin_x + (col + 0.5) * self.pixel_width,
            self.origin_y - (row + 0.5) * self.pixel_height,
        )
    }

    /// Fractional pixel indices for a projected coordinate.
    #[must_use]
    pub fn to_pixel(&self, x: f64, y: f64) -> (f64, f64) {
        (
            (x - self.origin_x) / self.pixel_width - 0.5,
            (self.origin_y - y) / self.pixel_height - 0.5,
        )
    }
}

/// An elevation raster with its georeferencing.
#[derive(Debug, Clone)]
pub struct Dem {
    /// Raster width in pixels.
    pub width: u32,
    /// Raster height in pixels.
    pub height: u32,
    /// Elevation samples in row-major order; `NaN` marks nodata.
    pub values: Vec<f32>,
    /// Pixel-to-projected affine transform.
    pub transform: GeoTransform,
    /// Coordinate reference system of the projected coordinates.
    pub crs: Crs,
}

impl Dem {
    /// Read a `GeoTIFF` DEM from disk.
    ///
    /// `crs_override` replaces the CRS detected from the `GeoKeyDirectory`,
    /// which is required for `GeoTIFFs` written without geokeys.
    ///
    /// # Errors
    ///
    /// Returns [`GeolithError::GeoTiff`] when the file cannot be decoded or
    /// lacks georeferencing, and [`GeolithError::Crs`] when the embedded EPSG
    /// code is unsupported.
    pub fn open(path: &Path, crs_override: Option<Crs>) -> Result<Self> {
        let file = File::open(path)?;
        let mut decoder = Decoder::new(BufReader::new(file))
            .map_err(|e| GeolithError::GeoTiff(format!("{}: {e}", path.display())))?
            .with_limits(tiff::decoder::Limits::unlimited());

        let (width, height) = decoder
            .dimensions()
            .map_err(|e| GeolithError::GeoTiff(format!("{}: dimensions: {e}", path.display())))?;

        let transform = read_geo_transform(&mut decoder, path)?;
        let crs = match crs_override {
            Some(crs) => crs,
            None => read_crs(&mut decoder, path)?,
        };
        let nodata = read_nodata(&mut decoder);

        let image = decoder
            .read_image()
            .map_err(|e| GeolithError::GeoTiff(format!("{}: read_image: {e}", path.display())))?;
        let values = to_f32_samples(image, nodata, path)?;

        let expected = width as usize * height as usize;
        if values.len() != expected {
            return Err(GeolithError::GeoTiff(format!(
                "{}: expected {expected} samples for {width}x{height}, got {}",
                path.display(),
                values.len()
            )));
        }

        Ok(Self {
            width,
            height,
            values,
            transform,
            crs,
        })
    }

    /// Elevation at integer pixel `(col, row)`, or `None` outside the raster
    /// and at nodata pixels.
    #[must_use]
    pub fn value_at(&self, col: i64, row: i64) -> Option<f32> {
        if col < 0 || row < 0 || col >= i64::from(self.width) || row >= i64::from(self.height) {
            return None;
        }
        let index = row as usize * self.width as usize + col as usize;
        let value = self.values[index];
        if value.is_nan() { None } else { Some(value) }
    }

    /// Bilinearly interpolated elevation at a projected coordinate.
    ///
    /// Returns `None` when the sample falls outside the raster or when every
    /// contributing neighbour is nodata. Partial nodata neighbourhoods are
    /// resolved by renormalising over the valid corners, which keeps DEM
    /// edges and interior voids from punching holes into the output tiles.
    #[must_use]
    pub fn sample(&self, x: f64, y: f64) -> Option<f32> {
        let (fx, fy) = self.transform.to_pixel(x, y);
        let col0 = fx.floor();
        let row0 = fy.floor();
        let tx = fx - col0;
        let ty = fy - row0;
        let (col0, row0) = (col0 as i64, row0 as i64);

        let corners = [
            (col0, row0, (1.0 - tx) * (1.0 - ty)),
            (col0 + 1, row0, tx * (1.0 - ty)),
            (col0, row0 + 1, (1.0 - tx) * ty),
            (col0 + 1, row0 + 1, tx * ty),
        ];

        let mut total = 0.0_f64;
        let mut weight_sum = 0.0_f64;
        for (col, row, weight) in corners {
            if weight <= 0.0 {
                continue;
            }
            if let Some(value) = self.value_at(col, row) {
                total += f64::from(value) * weight;
                weight_sum += weight;
            }
        }

        if weight_sum <= 0.0 {
            return None;
        }
        Some((total / weight_sum) as f32)
    }

    /// Geographic bounds as `(min_lon, min_lat, max_lon, max_lat)`.
    ///
    /// The raster corners are projected to WGS84 and the extremes taken, which
    /// bounds rotated or skewed footprints correctly.
    #[must_use]
    pub fn wgs84_bounds(&self) -> (f64, f64, f64, f64) {
        let (w, h) = (f64::from(self.width), f64::from(self.height));
        let corners = [(0.0, 0.0), (w, 0.0), (0.0, h), (w, h)];

        let mut min_lon = f64::INFINITY;
        let mut min_lat = f64::INFINITY;
        let mut max_lon = f64::NEG_INFINITY;
        let mut max_lat = f64::NEG_INFINITY;

        for (col, row) in corners {
            let x = self.transform.origin_x + col * self.transform.pixel_width;
            let y = self.transform.origin_y - row * self.transform.pixel_height;
            let (lon, lat) = self.crs.to_wgs84(x, y);
            min_lon = min_lon.min(lon);
            min_lat = min_lat.min(lat);
            max_lon = max_lon.max(lon);
            max_lat = max_lat.max(lat);
        }

        (min_lon, min_lat, max_lon, max_lat)
    }

    /// Minimum and maximum valid elevation, or `None` when fully nodata.
    #[must_use]
    pub fn elevation_range(&self) -> Option<(f32, f32)> {
        let mut min = f32::INFINITY;
        let mut max = f32::NEG_INFINITY;
        let mut seen = false;
        for value in &self.values {
            if value.is_nan() {
                continue;
            }
            seen = true;
            min = min.min(*value);
            max = max.max(*value);
        }
        seen.then_some((min, max))
    }
}

/// Read the pixel-to-projected transform from the `GeoTIFF` tags.
pub fn read_geo_transform<R>(decoder: &mut Decoder<R>, path: &Path) -> Result<GeoTransform>
where
    R: std::io::Read + std::io::Seek,
{
    if let Ok(matrix) = decoder.get_tag_f64_vec(Tag::Unknown(TAG_MODEL_TRANSFORMATION))
        && matrix.len() >= 16
    {
        return Ok(GeoTransform {
            origin_x: matrix[3],
            origin_y: matrix[7],
            pixel_width: matrix[0],
            pixel_height: -matrix[5],
        });
    }

    let scale = decoder
        .get_tag_f64_vec(Tag::Unknown(TAG_MODEL_PIXEL_SCALE))
        .map_err(|e| {
            GeolithError::GeoTiff(format!(
                "{}: missing ModelPixelScale and ModelTransformation: {e}",
                path.display()
            ))
        })?;
    let tiepoint = decoder
        .get_tag_f64_vec(Tag::Unknown(TAG_MODEL_TIEPOINT))
        .map_err(|e| {
            GeolithError::GeoTiff(format!("{}: missing ModelTiepoint: {e}", path.display()))
        })?;

    if scale.len() < 2 || tiepoint.len() < 6 {
        return Err(GeolithError::GeoTiff(format!(
            "{}: malformed georeferencing tags (scale={}, tiepoint={})",
            path.display(),
            scale.len(),
            tiepoint.len()
        )));
    }

    Ok(GeoTransform {
        origin_x: tiepoint[3] - tiepoint[0] * scale[0],
        origin_y: tiepoint[4] + tiepoint[1] * scale[1],
        pixel_width: scale[0],
        pixel_height: scale[1],
    })
}

/// Resolve the CRS from the `GeoKeyDirectory`.
pub fn read_crs<R>(decoder: &mut Decoder<R>, path: &Path) -> Result<Crs>
where
    R: std::io::Read + std::io::Seek,
{
    let keys = decoder
        .get_tag_u32_vec(Tag::Unknown(TAG_GEO_KEY_DIRECTORY))
        .map_err(|e| {
            GeolithError::GeoTiff(format!(
                "{}: missing GeoKeyDirectory (pass --dem-crs to override): {e}",
                path.display()
            ))
        })?;

    let epsg = epsg_from_geo_keys(&keys).ok_or_else(|| {
        GeolithError::GeoTiff(format!(
            "{}: GeoKeyDirectory has no ProjectedCSType or GeographicType key \
             (pass --dem-crs to override)",
            path.display()
        ))
    })?;

    Crs::from_epsg(epsg)
}

/// Extract the EPSG code from a raw `GeoKeyDirectory` payload.
///
/// Layout per the `GeoTIFF` spec: a four-`u16` header
/// `[version, revision, minor, key_count]` followed by `key_count` entries of
/// `[key_id, tag_location, count, value_or_offset]`. Only entries with
/// `tag_location == 0` store their value inline, which is always the case for
/// the two CRS keys.
#[must_use]
fn epsg_from_geo_keys(keys: &[u32]) -> Option<u32> {
    if keys.len() < 4 {
        return None;
    }
    let count = keys[3] as usize;
    let mut geographic = None;

    for entry in 0..count {
        let base = 4 + entry * 4;
        if base + 3 >= keys.len() {
            break;
        }
        let (key_id, tag_location, value) = (keys[base], keys[base + 1], keys[base + 3]);
        if tag_location != 0 {
            continue;
        }
        match u16::try_from(key_id) {
            Ok(GEO_KEY_PROJECTED_CS_TYPE) => return Some(value),
            Ok(GEO_KEY_GEOGRAPHIC_TYPE) => geographic = Some(value),
            _ => {}
        }
    }

    geographic
}

/// Read the GDAL nodata sentinel, if present.
pub fn read_nodata<R>(decoder: &mut Decoder<R>) -> Option<f64>
where
    R: std::io::Read + std::io::Seek,
{
    let raw = decoder
        .get_tag_ascii_string(Tag::Unknown(TAG_GDAL_NODATA))
        .ok()?;
    raw.trim().trim_end_matches('\0').parse::<f64>().ok()
}

/// Convert a decoded TIFF band to `f32` samples, mapping nodata to `NaN`.
pub fn to_f32_samples(image: DecodingResult, nodata: Option<f64>, path: &Path) -> Result<Vec<f32>> {
    let mut values: Vec<f32> = match image {
        DecodingResult::F32(v) => v,
        DecodingResult::F64(v) => v.into_iter().map(|x| x as f32).collect(),
        DecodingResult::I8(v) => v.into_iter().map(f32::from).collect(),
        DecodingResult::U8(v) => v.into_iter().map(f32::from).collect(),
        DecodingResult::I16(v) => v.into_iter().map(f32::from).collect(),
        DecodingResult::U16(v) => v.into_iter().map(f32::from).collect(),
        DecodingResult::I32(v) => v.into_iter().map(|x| x as f32).collect(),
        DecodingResult::U32(v) => v.into_iter().map(|x| x as f32).collect(),
        DecodingResult::I64(v) => v.into_iter().map(|x| x as f32).collect(),
        DecodingResult::U64(v) => v.into_iter().map(|x| x as f32).collect(),
        other => {
            return Err(GeolithError::GeoTiff(format!(
                "{}: unsupported sample format {other:?}",
                path.display()
            )));
        }
    };

    if let Some(sentinel) = nodata {
        let sentinel = sentinel as f32;
        for value in &mut values {
            if *value == sentinel {
                *value = f32::NAN;
            }
        }
    }

    Ok(values)
}

#[cfg(test)]
mod tests {
    use super::*;

    fn test_dem() -> Dem {
        Dem {
            width: 2,
            height: 2,
            values: vec![0.0, 100.0, 200.0, 300.0],
            transform: GeoTransform {
                origin_x: 1000.0,
                origin_y: 2000.0,
                pixel_width: 10.0,
                pixel_height: 10.0,
            },
            crs: Crs::Wgs84,
        }
    }

    #[test]
    fn pixel_center_and_to_pixel_are_inverse() {
        let t = test_dem().transform;
        let (x, y) = t.pixel_center(3.0, 7.0);
        let (col, row) = t.to_pixel(x, y);
        assert!((col - 3.0).abs() < 1e-9, "col: {col}");
        assert!((row - 7.0).abs() < 1e-9, "row: {row}");
    }

    #[test]
    fn value_at_returns_none_outside_raster() {
        let dem = test_dem();
        assert_eq!(dem.value_at(0, 0), Some(0.0));
        assert_eq!(dem.value_at(1, 1), Some(300.0));
        assert_eq!(dem.value_at(-1, 0), None);
        assert_eq!(dem.value_at(0, -1), None);
        assert_eq!(dem.value_at(2, 0), None);
        assert_eq!(dem.value_at(0, 2), None);
    }

    #[test]
    fn value_at_treats_nan_as_nodata() {
        let mut dem = test_dem();
        dem.values[0] = f32::NAN;
        assert_eq!(dem.value_at(0, 0), None);
    }

    #[test]
    fn sample_at_pixel_center_returns_exact_value() {
        let dem = test_dem();
        let (x, y) = dem.transform.pixel_center(0.0, 0.0);
        let sampled = dem.sample(x, y).expect("inside raster");
        assert!((sampled - 0.0).abs() < 1e-4, "got {sampled}");

        let (x, y) = dem.transform.pixel_center(1.0, 1.0);
        let sampled = dem.sample(x, y).expect("inside raster");
        assert!((sampled - 300.0).abs() < 1e-4, "got {sampled}");
    }

    #[test]
    fn sample_midpoint_interpolates_all_four_corners() {
        let dem = test_dem();
        let (x0, y0) = dem.transform.pixel_center(0.0, 0.0);
        let (x1, y1) = dem.transform.pixel_center(1.0, 1.0);
        let sampled = dem
            .sample((x0 + x1) / 2.0, (y0 + y1) / 2.0)
            .expect("inside raster");
        assert!((sampled - 150.0).abs() < 1e-3, "got {sampled}");
    }

    #[test]
    fn sample_renormalises_over_partial_nodata() {
        let mut dem = test_dem();
        dem.values[3] = f32::NAN;
        let (x0, y0) = dem.transform.pixel_center(0.0, 0.0);
        let (x1, y1) = dem.transform.pixel_center(1.0, 1.0);
        let sampled = dem
            .sample((x0 + x1) / 2.0, (y0 + y1) / 2.0)
            .expect("three valid corners remain");
        assert!((sampled - 100.0).abs() < 1e-3, "got {sampled}");
    }

    #[test]
    fn sample_returns_none_when_fully_nodata() {
        let mut dem = test_dem();
        dem.values = vec![f32::NAN; 4];
        let (x, y) = dem.transform.pixel_center(0.0, 0.0);
        assert_eq!(dem.sample(x, y), None);
    }

    #[test]
    fn sample_outside_raster_is_none() {
        let dem = test_dem();
        assert_eq!(dem.sample(0.0, 0.0), None);
        assert_eq!(dem.sample(100_000.0, 100_000.0), None);
    }

    #[test]
    fn elevation_range_skips_nodata() {
        let mut dem = test_dem();
        dem.values[1] = f32::NAN;
        let (min, max) = dem.elevation_range().expect("valid samples remain");
        assert!((min - 0.0).abs() < 1e-6);
        assert!((max - 300.0).abs() < 1e-6);
    }

    #[test]
    fn elevation_range_is_none_when_fully_nodata() {
        let mut dem = test_dem();
        dem.values = vec![f32::NAN; 4];
        assert_eq!(dem.elevation_range(), None);
    }

    #[test]
    fn wgs84_bounds_cover_all_corners() {
        let dem = test_dem();
        let (min_lon, min_lat, max_lon, max_lat) = dem.wgs84_bounds();
        assert!(min_lon < max_lon, "{min_lon} < {max_lon}");
        assert!(min_lat < max_lat, "{min_lat} < {max_lat}");
    }

    #[test]
    fn epsg_from_geo_keys_falls_back_to_geographic() {
        let keys = vec![1, 1, 0, 1, u32::from(GEO_KEY_GEOGRAPHIC_TYPE), 0, 1, 4326];
        assert_eq!(epsg_from_geo_keys(&keys), Some(4326));
    }

    #[test]
    fn epsg_from_geo_keys_prefers_projected_over_geographic() {
        let keys = vec![
            1,
            1,
            0,
            2,
            u32::from(GEO_KEY_GEOGRAPHIC_TYPE),
            0,
            1,
            4326,
            u32::from(GEO_KEY_PROJECTED_CS_TYPE),
            0,
            1,
            32_632,
        ];
        assert_eq!(epsg_from_geo_keys(&keys), Some(32_632));
        let projected_only = vec![
            1,
            1,
            0,
            1,
            u32::from(GEO_KEY_PROJECTED_CS_TYPE),
            0,
            1,
            32_633,
        ];
        assert_eq!(epsg_from_geo_keys(&projected_only), Some(32_633));
    }

    #[test]
    fn epsg_from_geo_keys_ignores_indirect_values() {
        let keys = vec![
            1,
            1,
            0,
            1,
            u32::from(GEO_KEY_PROJECTED_CS_TYPE),
            34_737,
            1,
            0,
        ];
        assert_eq!(epsg_from_geo_keys(&keys), None);
    }

    #[test]
    fn epsg_from_geo_keys_handles_truncated_input() {
        assert_eq!(epsg_from_geo_keys(&[]), None);
        assert_eq!(epsg_from_geo_keys(&[1, 1, 0]), None);
        assert_eq!(epsg_from_geo_keys(&[1, 1, 0, 5, 3072]), None);
    }

    #[test]
    fn to_f32_samples_maps_nodata_to_nan() {
        let decoded = DecodingResult::I16(vec![10, -32_768, 30]);
        let values = to_f32_samples(decoded, Some(-32_768.0), Path::new("t.tif")).expect("convert");
        assert!((values[0] - 10.0).abs() < 1e-6);
        assert!(values[1].is_nan(), "sentinel becomes nodata");
        assert!((values[2] - 30.0).abs() < 1e-6);
    }

    #[test]
    fn to_f32_samples_without_nodata_keeps_all_values() {
        let decoded = DecodingResult::F32(vec![1.5, 2.5]);
        let values = to_f32_samples(decoded, None, Path::new("t.tif")).expect("convert");
        assert_eq!(values, vec![1.5, 2.5]);
    }

    #[test]
    fn geo_transform_from_transformation_matrix_negates_row_step() {
        let t = GeoTransform {
            origin_x: 10.0,
            origin_y: 20.0,
            pixel_width: 2.0,
            pixel_height: 2.0,
        };
        let (x, y) = t.pixel_center(0.0, 1.0);
        assert!((x - 11.0).abs() < 1e-9, "x: {x}");
        assert!((y - 17.0).abs() < 1e-9, "northing decreases downward: {y}");
    }

    #[test]
    fn to_f32_samples_converts_every_integer_width() {
        let cases: Vec<(DecodingResult, f32)> = vec![
            (DecodingResult::I8(vec![-5]), -5.0),
            (DecodingResult::U8(vec![250]), 250.0),
            (DecodingResult::I16(vec![-3000]), -3000.0),
            (DecodingResult::U16(vec![60_000]), 60_000.0),
            (DecodingResult::I32(vec![-100_000]), -100_000.0),
            (DecodingResult::U32(vec![100_000]), 100_000.0),
            (DecodingResult::I64(vec![-1_000_000]), -1_000_000.0),
            (DecodingResult::U64(vec![1_000_000]), 1_000_000.0),
            (DecodingResult::F64(vec![1234.5]), 1234.5),
        ];
        for (decoded, expected) in cases {
            let label = format!("{decoded:?}");
            let values = to_f32_samples(decoded, None, Path::new("t.tif")).expect("convert");
            assert!(
                (values[0] - expected).abs() < 1e-3,
                "{label}: got {}",
                values[0]
            );
        }
    }

    #[test]
    fn epsg_from_geo_keys_skips_unrelated_keys() {
        let keys = vec![
            1,
            1,
            0,
            2,
            1024,
            0,
            1,
            1,
            u32::from(GEO_KEY_PROJECTED_CS_TYPE),
            0,
            1,
            32_633,
        ];
        assert_eq!(
            epsg_from_geo_keys(&keys),
            Some(32_633),
            "a leading non-CRS key must not stop the scan"
        );
    }

    #[test]
    fn to_f32_samples_rejects_an_unsupported_sample_format() {
        let decoded = DecodingResult::F16(vec![half::f16::from_f32(1.0)]);
        let err = to_f32_samples(decoded, None, Path::new("t.tif"))
            .expect_err("f16 has no conversion arm");
        assert!(
            format!("{err}").contains("unsupported sample format"),
            "{err}"
        );
    }
}