Skip to main content

oxigeo_geotiff/
lib.rs

1//! OxiGeo GeoTIFF Driver - Pure Rust GeoTIFF/COG Support
2//!
3//! This crate provides a pure Rust implementation of GeoTIFF and Cloud Optimized
4//! GeoTIFF (COG) reading and writing capabilities.
5//!
6//! # Features
7//!
8//! - `std` (default) - Enable standard library support
9//! - `async` - Enable async I/O support
10//! - `deflate` (default) - DEFLATE/zlib compression
11//! - `lzw` (default) - LZW compression
12//! - `zstd` - ZSTD compression
13//! - `jpeg` - JPEG compression (planned)
14//! - `webp` - WebP compression (pure Rust via `image-webp`; encoder is lossless VP8L only)
15//! - `parallel` - Decode a band/window's tiles across rayon workers (off by
16//!   default: this crate targets `wasm32-unknown-unknown`, which has no threads)
17//!
18//! # Example
19//!
20//! ```ignore
21//! use oxigeo_geotiff::cog::CogReader;
22//! use oxigeo_core::io::FileDataSource;
23//!
24//! let source = FileDataSource::open("image.tif")?;
25//! let reader = CogReader::open(source)?;
26//!
27//! println!("Image size: {}x{}", reader.width(), reader.height());
28//! println!("Tile size: {:?}", reader.tile_size());
29//! println!("Overview count: {}", reader.overview_count());
30//!
31//! // Read a tile
32//! let tile_data = reader.read_tile(0, 0, 0)?;
33//! ```
34//!
35//! # Byte order of decoded samples
36//!
37//! **Every entry point that yields decoded pixel samples returns them in the
38//! *host's* byte order**, whatever the file's `II`/`MM` header says. This is the
39//! contract GDAL's `RasterIO` has always had, and it is what the rest of the
40//! workspace assumes: [`oxigeo_core::buffer::RasterBuffer`] carries no byte-order
41//! field and all of its accessors (`get_pixel`, `get_u16`…`get_f64`, `as_slice`)
42//! and [`oxigeo_core::buffer::convert_raw_into`] are native-endian. Before
43//! cool-japan/oxigeo#14 the driver handed back samples in the *file's* order, so
44//! every numeric value read from a big-endian (`MM`) GeoTIFF anywhere in the
45//! workspace was silently byte-reversed.
46//!
47//! ## Which APIs normalise
48//!
49//! Normalising (samples come back native-endian):
50//!
51//! * [`GeoTiffReader::read_band`], [`GeoTiffReader::read_band_into`],
52//!   [`GeoTiffReader::read_band_into_typed`]
53//! * [`GeoTiffReader::read_window`], [`GeoTiffReader::read_window_into`],
54//!   [`GeoTiffReader::read_window_into_typed`]
55//! * [`GeoTiffReader::read_tile`], [`GeoTiffReader::read_tile_buffer`],
56//!   [`GeoTiffReader::read_tile_band_buffer`]
57//! * [`CogReader::read_tile`], [`CogReader::read_tile_into`]
58//!
59//! **Not** normalising, by design:
60//!
61//! * [`CogReader::read_tile_raw`] — returns the block's *compressed* bytes
62//!   exactly as stored; there are no samples to normalise.
63//! * [`compression`] and [`compression::apply_predictor_reverse`] — the predictor
64//!   is defined on file-order samples (TIFF 6.0 §14 / TN3) and therefore runs
65//!   *before* normalisation. Callers driving the codec layer by hand own the
66//!   conversion.
67//! * The [`writer`] module, which takes native-order samples and emits them in
68//!   the byte order its options declare.
69//!
70//! ## Scope and limits
71//!
72//! Normalisation swaps samples of 2, 4 and 8 bytes. Sub-byte `BitsPerSample`
73//! (which the reader reports as `bytes_per_sample == 0`), 1-byte samples and any
74//! other width (e.g. a 24-bit `BitsPerSample`, which rounds to 3) are passed
75//! through untouched — for widths under two bytes there is nothing to swap, and
76//! for exotic widths there is no defined sample order to swap *to*. `Lerc`
77//! blocks are also passed through: this crate's LERC decoder emits native-order
78//! samples already (`lerc_codec::serialize_native`), so swapping them would
79//! corrupt data rather than fix it.
80//!
81//! ## Codec/predictor combinations that are refused
82//!
83//! A `Lerc` block carrying a `Predictor` tag is rejected outright rather than
84//! decoded (see `reject_undefined_predictor`): no encoder defines that
85//! combination — libtiff's LERC codec ignores tag 317 entirely and GDAL refuses
86//! `PREDICTOR` for LERC — so a decoder cannot know whether a predictor was ever
87//! applied. Reversing one anyway, which is what the driver used to do, corrupts
88//! every sample of the block with no error raised.
89//!
90//! A file whose byte order already matches the host — every real-world
91//! little-endian GeoTIFF on every target this crate supports — pays a single
92//! predictable branch per decoded block and no per-sample work at all.
93
94#![warn(clippy::all)]
95// Pedantic disabled to reduce noise - default clippy::all is sufficient
96// #![warn(clippy::pedantic)]
97#![deny(clippy::unwrap_used)]
98#![allow(clippy::module_name_repetitions)]
99// Allow dead code for internal writer components
100#![allow(dead_code)]
101// Allow expect() for internal invariant checks
102#![allow(clippy::expect_used)]
103// Allow too many arguments for complex geospatial operations
104#![allow(clippy::too_many_arguments)]
105// Allow clamp patterns for raster data normalization
106#![allow(clippy::manual_clamp)]
107// Allow push after creation for buffer building patterns
108#![allow(clippy::vec_init_then_push)]
109// Allow partial documentation during development
110#![allow(missing_docs)]
111
112pub mod adaptive_tiling;
113pub mod band_algebra;
114pub mod band_read;
115pub mod cog;
116pub mod color_space;
117pub mod compression;
118pub mod geokeys;
119pub mod jpeg_codec;
120pub mod lerc_codec;
121pub mod overviews;
122pub mod tiff;
123pub mod writer;
124
125// Re-export commonly used types
126pub use cog::CogReader;
127pub use geokeys::{GeoKey, GeoKeyDirectory, ModelType, RasterType};
128pub use tiff::{
129    ByteOrderType, Compression, ImageInfo, PhotometricInterpretation, TiffFile, TiffHeader, TiffTag,
130};
131pub use writer::{
132    CogWriter, CogWriterOptions, GeoTiffWriter, GeoTiffWriterOptions, OverviewResampling,
133    WriterConfig,
134};
135
136use crate::tiff::Predictor;
137use oxigeo_core::buffer::RasterBuffer;
138use oxigeo_core::error::{FormatError, OxiGeoError, Result};
139use oxigeo_core::io::DataSource;
140use oxigeo_core::types::{
141    ColorInterpretation, GeoTransform, NoDataValue, RasterDataType, RasterMetadata,
142};
143
144/// Upper sanity bound (in bytes) on a single decoded raster band buffer.
145///
146/// Band dimensions come from untrusted IFD tags; this cap keeps a malformed or
147/// hostile header from driving [`GeoTiff::read_band`] into a multi-gigabyte
148/// allocation (OOM / denial of service). 4 GiB comfortably accommodates any
149/// realistic single-band read while bounding a hostile request to a survivable
150/// size.
151///
152/// 4 GiB does not fit in a 32-bit `usize` (`wasm32`, 32-bit ARM/x86), so on
153/// those targets the cap becomes a quarter of the address space (1 GiB) — still
154/// far past any realistic band, and the largest bound that could plausibly be
155/// allocated there anyway.
156const MAX_BAND_BYTES: usize = {
157    const FOUR_GIB: u64 = 4 * 1024 * 1024 * 1024;
158    if FOUR_GIB <= usize::MAX as u64 {
159        FOUR_GIB as usize
160    } else {
161        usize::MAX / 4
162    }
163};
164
165/// Computes the size of a full raster band buffer from untrusted dimensions,
166/// rejecting values that overflow `usize` or exceed [`MAX_BAND_BYTES`].
167///
168/// Extracted so the memory-safety guard on [`GeoTiff::read_band`] can be unit
169/// tested without a crafted TIFF: a hostile `width`/`height`/sample count must
170/// yield a typed error rather than a wrapping (then out-of-bounds) or
171/// multi-gigabyte allocation.
172fn checked_band_bytes(
173    width: usize,
174    height: usize,
175    bytes_per_sample: usize,
176    samples_per_pixel: usize,
177) -> Result<usize> {
178    let band_bytes = width
179        .checked_mul(height)
180        .and_then(|v| v.checked_mul(bytes_per_sample))
181        .and_then(|v| v.checked_mul(samples_per_pixel))
182        .ok_or_else(|| {
183            OxiGeoError::Format(FormatError::InvalidHeader {
184                message: format!(
185                    "raster dimensions overflow usize: {width}x{height} x {bytes_per_sample} \
186                     bytes x {samples_per_pixel} samples"
187                ),
188            })
189        })?;
190    if band_bytes > MAX_BAND_BYTES {
191        return Err(OxiGeoError::Format(FormatError::InvalidHeader {
192            message: format!(
193                "raster band size ({band_bytes} bytes) exceeds the maximum supported \
194                 ({MAX_BAND_BYTES} bytes); refusing to allocate (possible malformed or \
195                 hostile header)"
196            ),
197        }));
198    }
199    Ok(band_bytes)
200}
201
202// ---------------------------------------------------------------------------
203// Byte-order normalisation (cool-japan/oxigeo#14)
204// ---------------------------------------------------------------------------
205
206/// Whether the samples a codec has just produced still need swapping to reach
207/// the host's byte order.
208///
209/// See the crate-level *Byte order of decoded samples* section for the contract
210/// this enforces. Three things make the answer `false`:
211///
212/// * the sample width is not 2, 4 or 8 bytes — sub-byte `BitsPerSample` (which
213///   the reader reports as `0`), single-byte samples, and exotic widths such as
214///   a 24-bit `BitsPerSample` have no swap to perform or no defined one;
215/// * the codec is `Lerc`, whose decoder in this crate already emits native-order
216///   samples (`lerc_codec::serialize_native`), so a swap would *introduce* the
217///   corruption it is meant to remove;
218/// * the file's byte order already matches the host's — the case for every
219///   real-world little-endian GeoTIFF on every target this crate supports, which
220///   is why this is one branch per block and no per-sample work.
221///
222/// The host side is `cfg!(target_endian = ..)`, so a big-endian host reading an
223/// `II` file is handled by the same rule, symmetrically.
224const fn decoded_needs_native_swap(
225    byte_order: ByteOrderType,
226    bytes_per_sample: usize,
227    compression: Compression,
228) -> bool {
229    if !matches!(bytes_per_sample, 2 | 4 | 8) {
230        return false;
231    }
232    if matches!(compression, Compression::Lerc) {
233        return false;
234    }
235    match byte_order {
236        ByteOrderType::LittleEndian => cfg!(target_endian = "big"),
237        ByteOrderType::BigEndian => cfg!(target_endian = "little"),
238    }
239}
240
241/// Rejects a `Compression`/`Predictor` pair whose decode is not defined, so a
242/// file carrying one fails loudly instead of decoding to wrong pixels.
243///
244/// Exactly one pair qualifies today: **`Lerc` with any predictor**.
245///
246/// * libtiff's LERC codec (`tif_lerc.c`) never calls `TIFFPredictorInit`, so it
247///   neither applies tag 317 when writing nor reverses it when reading — to
248///   libtiff the predictor does not exist for LERC.
249/// * GDAL gates its `PREDICTOR` creation option on `GTIFFSupportsPredictor()`,
250///   which covers LZW/DEFLATE/ZSTD and excludes LERC, so `COMPRESS=LERC` never
251///   writes a predictor tag.
252/// * This crate cannot write LERC at all ([`compression::compress`] returns a
253///   typed "not implemented" error) and neither [`cog::analyze_for_cog`] nor
254///   [`cog::CogConverter`] can select it.
255///
256/// No encoder therefore produces a predicted LERC block, and a decoder that
257/// meets both tags cannot tell whether a predictor was applied. The driver used
258/// to reverse one regardless, over samples the LERC decoder had already put in
259/// *host* order using the *file's* declared order — two independent errors, both
260/// silent. An explicit `Err` is the only honest answer: the block is real, its
261/// interpretation is not knowable.
262///
263/// One comparison per decoded block, short-circuited on the overwhelmingly
264/// common `Predictor::None`; nothing per sample.
265///
266/// # Errors
267/// Returns [`OxiGeoError::NotSupported`] for `Lerc` plus any predictor.
268fn reject_undefined_predictor(compression: Compression, predictor: Predictor) -> Result<()> {
269    if matches!(predictor, Predictor::None) || !matches!(compression, Compression::Lerc) {
270        return Ok(());
271    }
272    Err(
273        OxiGeoError::not_supported_builder("a TIFF Predictor combined with LERC compression")
274            .with_operation("decode block")
275            .with_parameter("compression", "LERC (34887)")
276            .with_parameter("predictor", format!("{predictor:?} ({})", predictor as u16))
277            .with_suggestion(
278                "No encoder defines this combination (libtiff's LERC codec ignores tag 317 and \
279                 GDAL refuses PREDICTOR for LERC), so the block's pixels cannot be reconstructed \
280                 unambiguously. Re-encode the file without the Predictor tag, or with a codec \
281                 that defines it (LZW, DEFLATE, ZSTD).",
282            )
283            .build(),
284    )
285}
286
287/// Reverses every `N`-byte sample of `data` in place.
288///
289/// A trailing partial sample (which only a malformed block can produce) is left
290/// alone rather than half-swapped.
291fn swap_sample_bytes<const N: usize>(data: &mut [u8]) {
292    for chunk in data.chunks_exact_mut(N) {
293        let mut sample = [0u8; N];
294        sample.copy_from_slice(chunk);
295        sample.reverse();
296        chunk.copy_from_slice(&sample);
297    }
298}
299
300/// Converts one decoded block from the file's byte order to the host's, in place.
301///
302/// **Ordering matters.** This must run *after*
303/// [`compression::apply_predictor_reverse`]: both TIFF predictors are defined on
304/// file-order data — horizontal differencing reads and writes whole samples with
305/// `byte_order`, and the floating-point predictor de-interleaves byte planes
306/// whose most-significant plane is first on disk — so a block is not even a
307/// sample array until the predictor has been reversed. Swapping first produces
308/// pixels that look plausible and are wrong, which is exactly the failure class
309/// #14 exists to eliminate.
310///
311/// A no-op unless [`decoded_needs_native_swap`] says otherwise, so the common
312/// little-endian-file/little-endian-host case costs one branch per block.
313fn normalize_samples_to_native(
314    data: &mut [u8],
315    bytes_per_sample: usize,
316    byte_order: ByteOrderType,
317    compression: Compression,
318) {
319    if !decoded_needs_native_swap(byte_order, bytes_per_sample, compression) {
320        return;
321    }
322    match bytes_per_sample {
323        2 => swap_sample_bytes::<2>(data),
324        4 => swap_sample_bytes::<4>(data),
325        8 => swap_sample_bytes::<8>(data),
326        // Unreachable: `decoded_needs_native_swap` already rejected every other
327        // width. Kept total rather than panicking.
328        _ => {}
329    }
330}
331
332/// Generates WKT string from GeoKeys
333///
334/// # Arguments
335/// * `geo_keys` - Optional reference to GeoKeyDirectory
336///
337/// # Returns
338/// WKT string if CRS information is available
339fn parse_geokeys_to_wkt(geo_keys: Option<&GeoKeyDirectory>) -> Option<String> {
340    let geo_keys = geo_keys?;
341    let epsg_code = geo_keys.epsg_code()?;
342
343    // Generate WKT based on EPSG code
344    // For comprehensive WKT, we'd need a full EPSG database, but we can handle common cases
345    Some(match epsg_code {
346        // WGS 84
347        4326 => {
348            r#"GEOGCS["WGS 84",
349    DATUM["WGS_1984",
350        SPHEROID["WGS 84",6378137,298.257223563,
351            AUTHORITY["EPSG","7030"]],
352        AUTHORITY["EPSG","6326"]],
353    PRIMEM["Greenwich",0,
354        AUTHORITY["EPSG","8901"]],
355    UNIT["degree",0.0174532925199433,
356        AUTHORITY["EPSG","9122"]],
357    AXIS["Latitude",NORTH],
358    AXIS["Longitude",EAST],
359    AUTHORITY["EPSG","4326"]]"#
360                .to_string()
361        }
362        // WGS 84 / Pseudo-Mercator (Web Mercator)
363        3857 => {
364            r#"PROJCS["WGS 84 / Pseudo-Mercator",
365    GEOGCS["WGS 84",
366        DATUM["WGS_1984",
367            SPHEROID["WGS 84",6378137,298.257223563,
368                AUTHORITY["EPSG","7030"]],
369            AUTHORITY["EPSG","6326"]],
370        PRIMEM["Greenwich",0,
371            AUTHORITY["EPSG","8901"]],
372        UNIT["degree",0.0174532925199433,
373            AUTHORITY["EPSG","9122"]],
374        AUTHORITY["EPSG","4326"]],
375    PROJECTION["Mercator_1SP"],
376    PARAMETER["central_meridian",0],
377    PARAMETER["scale_factor",1],
378    PARAMETER["false_easting",0],
379    PARAMETER["false_northing",0],
380    UNIT["metre",1,
381        AUTHORITY["EPSG","9001"]],
382    AXIS["Easting",EAST],
383    AXIS["Northing",NORTH],
384    EXTENSION["PROJ4","+proj=merc +a=6378137 +b=6378137 +lat_ts=0 +lon_0=0 +x_0=0 +y_0=0 +k=1 +units=m +nadgrids=@null +wktext +no_defs"],
385    AUTHORITY["EPSG","3857"]]"#
386                .to_string()
387        }
388        // WGS 84 / UTM zones (Northern Hemisphere: 32601-32660)
389        32601..=32660 => {
390            let zone = epsg_code - 32600;
391            format!(
392                r#"PROJCS["WGS 84 / UTM zone {}N",
393    GEOGCS["WGS 84",
394        DATUM["WGS_1984",
395            SPHEROID["WGS 84",6378137,298.257223563,
396                AUTHORITY["EPSG","7030"]],
397            AUTHORITY["EPSG","6326"]],
398        PRIMEM["Greenwich",0,
399            AUTHORITY["EPSG","8901"]],
400        UNIT["degree",0.0174532925199433,
401            AUTHORITY["EPSG","9122"]],
402        AUTHORITY["EPSG","4326"]],
403    PROJECTION["Transverse_Mercator"],
404    PARAMETER["latitude_of_origin",0],
405    PARAMETER["central_meridian",{}],
406    PARAMETER["scale_factor",0.9996],
407    PARAMETER["false_easting",500000],
408    PARAMETER["false_northing",0],
409    UNIT["metre",1,
410        AUTHORITY["EPSG","9001"]],
411    AXIS["Easting",EAST],
412    AXIS["Northing",NORTH],
413    AUTHORITY["EPSG","{}""]]"#,
414                zone,
415                zone as i32 * 6 - 183,
416                epsg_code
417            )
418        }
419        // WGS 84 / UTM zones (Southern Hemisphere: 32701-32760)
420        32701..=32760 => {
421            let zone = epsg_code - 32700;
422            format!(
423                r#"PROJCS["WGS 84 / UTM zone {}S",
424    GEOGCS["WGS 84",
425        DATUM["WGS_1984",
426            SPHEROID["WGS 84",6378137,298.257223563,
427                AUTHORITY["EPSG","7030"]],
428            AUTHORITY["EPSG","6326"]],
429        PRIMEM["Greenwich",0,
430            AUTHORITY["EPSG","8901"]],
431        UNIT["degree",0.0174532925199433,
432            AUTHORITY["EPSG","9122"]],
433        AUTHORITY["EPSG","4326"]],
434    PROJECTION["Transverse_Mercator"],
435    PARAMETER["latitude_of_origin",0],
436    PARAMETER["central_meridian",{}],
437    PARAMETER["scale_factor",0.9996],
438    PARAMETER["false_easting",500000],
439    PARAMETER["false_northing",10000000],
440    UNIT["metre",1,
441        AUTHORITY["EPSG","9001"]],
442    AXIS["Easting",EAST],
443    AXIS["Northing",NORTH],
444    AUTHORITY["EPSG","{}""]]"#,
445                zone,
446                zone as i32 * 6 - 183,
447                epsg_code
448            )
449        }
450        // NAD83
451        4269 => {
452            r#"GEOGCS["NAD83",
453    DATUM["North_American_Datum_1983",
454        SPHEROID["GRS 1980",6378137,298.257222101,
455            AUTHORITY["EPSG","7019"]],
456        AUTHORITY["EPSG","6269"]],
457    PRIMEM["Greenwich",0,
458        AUTHORITY["EPSG","8901"]],
459    UNIT["degree",0.0174532925199433,
460        AUTHORITY["EPSG","9122"]],
461    AXIS["Latitude",NORTH],
462    AXIS["Longitude",EAST],
463    AUTHORITY["EPSG","4269"]]"#
464                .to_string()
465        }
466        // NAD27
467        4267 => {
468            r#"GEOGCS["NAD27",
469    DATUM["North_American_Datum_1927",
470        SPHEROID["Clarke 1866",6378206.4,294.978698213898,
471            AUTHORITY["EPSG","7008"]],
472        AUTHORITY["EPSG","6267"]],
473    PRIMEM["Greenwich",0,
474        AUTHORITY["EPSG","8901"]],
475    UNIT["degree",0.0174532925199433,
476        AUTHORITY["EPSG","9122"]],
477    AXIS["Latitude",NORTH],
478    AXIS["Longitude",EAST],
479    AUTHORITY["EPSG","4267"]]"#
480                .to_string()
481        }
482        // For other EPSG codes, use a simple reference
483        _ => format!("EPSG:{}", epsg_code),
484    })
485}
486
487/// Parses color interpretation from photometric interpretation
488///
489/// # Arguments
490/// * `photometric` - The photometric interpretation from TIFF
491/// * `samples_per_pixel` - Number of samples (bands) per pixel
492///
493/// # Returns
494/// Vector of color interpretations for each band
495fn parse_photometric_interpretation(
496    photometric: PhotometricInterpretation,
497    samples_per_pixel: u16,
498) -> Vec<ColorInterpretation> {
499    match photometric {
500        PhotometricInterpretation::WhiteIsZero | PhotometricInterpretation::BlackIsZero => {
501            // Grayscale - might have alpha channel
502            if samples_per_pixel == 1 {
503                vec![ColorInterpretation::Gray]
504            } else if samples_per_pixel == 2 {
505                vec![ColorInterpretation::Gray, ColorInterpretation::Alpha]
506            } else {
507                // Multiple grayscale bands
508                vec![ColorInterpretation::Gray; samples_per_pixel as usize]
509            }
510        }
511        PhotometricInterpretation::Rgb => {
512            // RGB or RGBA
513            match samples_per_pixel {
514                1 => vec![ColorInterpretation::Red],
515                2 => vec![ColorInterpretation::Red, ColorInterpretation::Green],
516                3 => vec![
517                    ColorInterpretation::Red,
518                    ColorInterpretation::Green,
519                    ColorInterpretation::Blue,
520                ],
521                4 => vec![
522                    ColorInterpretation::Red,
523                    ColorInterpretation::Green,
524                    ColorInterpretation::Blue,
525                    ColorInterpretation::Alpha,
526                ],
527                _ => {
528                    // More than 4 bands - treat extras as undefined
529                    let mut interp = vec![
530                        ColorInterpretation::Red,
531                        ColorInterpretation::Green,
532                        ColorInterpretation::Blue,
533                    ];
534                    if samples_per_pixel > 3 {
535                        interp.push(ColorInterpretation::Alpha);
536                    }
537                    for _ in 4..samples_per_pixel {
538                        interp.push(ColorInterpretation::Undefined);
539                    }
540                    interp
541                }
542            }
543        }
544        PhotometricInterpretation::Palette => {
545            // Palette color - index plus optional alpha
546            if samples_per_pixel == 1 {
547                vec![ColorInterpretation::PaletteIndex]
548            } else if samples_per_pixel == 2 {
549                vec![
550                    ColorInterpretation::PaletteIndex,
551                    ColorInterpretation::Alpha,
552                ]
553            } else {
554                vec![ColorInterpretation::PaletteIndex; samples_per_pixel as usize]
555            }
556        }
557        PhotometricInterpretation::Cmyk => {
558            // CMYK
559            match samples_per_pixel {
560                1 => vec![ColorInterpretation::Cyan],
561                2 => vec![ColorInterpretation::Cyan, ColorInterpretation::Magenta],
562                3 => vec![
563                    ColorInterpretation::Cyan,
564                    ColorInterpretation::Magenta,
565                    ColorInterpretation::Yellow,
566                ],
567                4 => vec![
568                    ColorInterpretation::Cyan,
569                    ColorInterpretation::Magenta,
570                    ColorInterpretation::Yellow,
571                    ColorInterpretation::Black,
572                ],
573                _ => {
574                    // More than 4 bands - treat extras as undefined
575                    let mut interp = vec![
576                        ColorInterpretation::Cyan,
577                        ColorInterpretation::Magenta,
578                        ColorInterpretation::Yellow,
579                        ColorInterpretation::Black,
580                    ];
581                    for _ in 4..samples_per_pixel {
582                        interp.push(ColorInterpretation::Undefined);
583                    }
584                    interp
585                }
586            }
587        }
588        PhotometricInterpretation::YCbCr => {
589            // YCbCr
590            match samples_per_pixel {
591                1 => vec![ColorInterpretation::YCbCrY],
592                2 => vec![ColorInterpretation::YCbCrY, ColorInterpretation::YCbCrCb],
593                3 => vec![
594                    ColorInterpretation::YCbCrY,
595                    ColorInterpretation::YCbCrCb,
596                    ColorInterpretation::YCbCrCr,
597                ],
598                _ => {
599                    // More than 3 bands - add alpha or undefined
600                    let mut interp = vec![
601                        ColorInterpretation::YCbCrY,
602                        ColorInterpretation::YCbCrCb,
603                        ColorInterpretation::YCbCrCr,
604                    ];
605                    if samples_per_pixel > 3 {
606                        interp.push(ColorInterpretation::Alpha);
607                    }
608                    for _ in 4..samples_per_pixel {
609                        interp.push(ColorInterpretation::Undefined);
610                    }
611                    interp
612                }
613            }
614        }
615        // For other photometric interpretations (TransparencyMask, CIE Lab, etc.)
616        _ => vec![ColorInterpretation::Undefined; samples_per_pixel as usize],
617    }
618}
619
620/// GeoTIFF reader (high-level API)
621pub struct GeoTiffReader<S: DataSource> {
622    cog_reader: CogReader<S>,
623    geo_transform: Option<GeoTransform>,
624    nodata: NoDataValue,
625}
626
627impl<S: DataSource> GeoTiffReader<S> {
628    /// Opens a GeoTIFF file
629    ///
630    /// # Minimum size
631    ///
632    /// There is no fixed byte floor. The header parser needs
633    /// [`TiffHeader::MIN_HEADER_SIZE`] bytes for a classic TIFF and
634    /// [`TiffHeader::BIGTIFF_HEADER_SIZE`] for a BigTIFF, and a source with
635    /// fewer than that is reported as a too-short header rather than as an
636    /// unknown format or an I/O failure. Passing the header is not enough to
637    /// open a file, though: the first IFD still has to parse and still has to
638    /// carry the mandatory image tags, so a header-only stub is rejected — just
639    /// with an error naming what is actually missing.
640    ///
641    /// # Errors
642    /// Returns an error if the file cannot be opened or parsed
643    pub fn open(source: S) -> Result<Self> {
644        let cog_reader = CogReader::open(source)?;
645
646        // Extract geotransform
647        let geo_transform = cog_reader.geo_transform()?;
648
649        // Extract nodata
650        let nodata = cog_reader.nodata()?;
651
652        Ok(Self {
653            cog_reader,
654            geo_transform,
655            nodata,
656        })
657    }
658
659    /// Returns the image width
660    #[must_use]
661    pub fn width(&self) -> u64 {
662        self.cog_reader.width()
663    }
664
665    /// Returns the image height
666    #[must_use]
667    pub fn height(&self) -> u64 {
668        self.cog_reader.height()
669    }
670
671    /// Returns the number of bands
672    #[must_use]
673    pub fn band_count(&self) -> u32 {
674        u32::from(self.cog_reader.primary_info().samples_per_pixel)
675    }
676
677    /// Returns the data type
678    #[must_use]
679    pub fn data_type(&self) -> Option<RasterDataType> {
680        self.cog_reader.primary_info().data_type()
681    }
682
683    /// Returns the tile size
684    #[must_use]
685    pub fn tile_size(&self) -> Option<(u32, u32)> {
686        self.cog_reader.tile_size()
687    }
688
689    /// Returns the number of overview levels
690    #[must_use]
691    pub fn overview_count(&self) -> usize {
692        self.cog_reader.overview_count()
693    }
694
695    /// Returns the GeoTransform
696    #[must_use]
697    pub fn geo_transform(&self) -> Option<&GeoTransform> {
698        self.geo_transform.as_ref()
699    }
700
701    /// Returns the NoData value
702    #[must_use]
703    pub const fn nodata(&self) -> NoDataValue {
704        self.nodata
705    }
706
707    /// Returns the EPSG code
708    #[must_use]
709    pub fn epsg_code(&self) -> Option<u32> {
710        self.cog_reader.epsg_code()
711    }
712
713    /// Returns the compression scheme
714    #[must_use]
715    pub fn compression(&self) -> Compression {
716        self.cog_reader.primary_info().compression
717    }
718
719    /// Returns the byte order declared by the file's header (`II` or `MM`).
720    ///
721    /// This is a property of the *file*, not of the data this reader hands out:
722    /// every read API that yields decoded samples normalises them to the host's
723    /// byte order (see the crate-level *Byte order of decoded samples* section),
724    /// so callers never need this to interpret pixels. It is exposed for
725    /// reporting, for round-tripping a file's on-disk layout through
726    /// [`writer::GeoTiffWriterOptions`], and so that nothing has to re-parse the
727    /// TIFF header out of the [`DataSource`] to find out — which is what a
728    /// downstream crate had to do before cool-japan/oxigeo#14.
729    #[must_use]
730    pub fn byte_order(&self) -> ByteOrderType {
731        self.cog_reader.tiff().byte_order()
732    }
733
734    /// Returns the number of tiles in X and Y directions
735    #[must_use]
736    pub fn tile_count(&self) -> (u32, u32) {
737        self.cog_reader.tile_count()
738    }
739
740    /// Reads a tile
741    ///
742    /// Samples come back in the **host's** byte order regardless of the file's
743    /// `II`/`MM` header; see [`CogReader::read_tile`] and the crate-level
744    /// *Byte order of decoded samples* section. On a planar
745    /// (`PlanarConfiguration = 2`) raster a block holds one band and `tile_y`
746    /// indexes the plane-major block grid — see [`CogReader::tile_decoded_size`].
747    ///
748    /// # Errors
749    /// Returns an error if the tile cannot be read, or if its codec/predictor
750    /// combination has no defined reversal (LERC plus a `Predictor` tag), which
751    /// is refused rather than decoded to wrong pixels.
752    pub fn read_tile(&self, level: usize, tile_x: u32, tile_y: u32) -> Result<Vec<u8>> {
753        self.cog_reader.read_tile(level, tile_x, tile_y)
754    }
755
756    /// Returns the pixel dimensions `(width, height)` of one resolution level.
757    ///
758    /// `level` is `0` for full resolution and `1..=`[`Self::overview_count`] for
759    /// the overviews. The values are read from the level's **own** IFD
760    /// (`ImageWidth`/`ImageLength`), so they are the dimensions actually stored
761    /// rather than the `ceil(full / 2^level)` a caller would otherwise have to
762    /// infer — an inference that only holds for a strict power-of-two pyramid
763    /// and silently mis-describes every overview of a raster built with any
764    /// other decimation factor (cool-japan/oxigeo#14).
765    ///
766    /// Pair it with [`Self::band_byte_len`] / [`Self::band_pixel_count`], which
767    /// give only the product, when you need to clamp a window or shape a
768    /// [`RasterBuffer`] for `level > 0`.
769    ///
770    /// # Errors
771    /// Returns [`OxiGeoError::OutOfBounds`] if `level` names no overview, or a
772    /// format error if the level's IFD declares no dimensions.
773    ///
774    /// # Examples
775    /// ```ignore
776    /// let (w, h) = reader.level_size(1)?; // the first overview's real size
777    /// ```
778    pub fn level_size(&self, level: usize) -> Result<(u64, u64)> {
779        let info = self.level_info(level)?;
780        Ok((info.width, info.height))
781    }
782
783    /// Resolves the [`ImageInfo`] describing `level`.
784    ///
785    /// Level 0 is the primary image. `CogReader` parses the overview IFDs but
786    /// does not expose them, so an overview's own tags are read straight from
787    /// its IFD here; they are all single-valued and therefore stored inline, so
788    /// no data source is needed. Tags absent from the overview IFD are inherited
789    /// from the full-resolution image, which is what overviews always share.
790    ///
791    /// This mirrors `band_read::LevelGeometry::resolve`, the read engine's
792    /// equivalent; the two must agree, and the buffer-length checks in
793    /// [`Self::read_window_into`] surface it as a typed error if they ever do
794    /// not.
795    fn level_info(&self, level: usize) -> Result<ImageInfo> {
796        let primary = self.cog_reader.primary_info();
797        if level == 0 {
798            return Ok(primary.clone());
799        }
800        let out_of_bounds = || OxiGeoError::OutOfBounds {
801            message: format!("Overview level {level} out of bounds"),
802        };
803        if level > self.cog_reader.overview_count() {
804            return Err(out_of_bounds());
805        }
806
807        let byte_order = self.cog_reader.tiff().byte_order();
808        // Through the reader's level → IFD map, not `ifds[level]`: levels skip
809        // GDAL internal masks, so on a masked file the raw chain index names a
810        // different image and `level_size` would report the mask's dimensions
811        // for a level whose tiles come from the real overview.
812        let ifd = self.cog_reader.level_ifd(level).ok_or_else(out_of_bounds)?;
813        let scalar = |tag: TiffTag| ifd.get_entry(tag).and_then(|e| e.get_u64(byte_order).ok());
814
815        let mut info = primary.clone();
816        info.width =
817            scalar(TiffTag::ImageWidth).ok_or(OxiGeoError::Format(FormatError::MissingTag {
818                tag: "ImageWidth",
819            }))?;
820        info.height =
821            scalar(TiffTag::ImageLength).ok_or(OxiGeoError::Format(FormatError::MissingTag {
822                tag: "ImageLength",
823            }))?;
824        // Layout tags are per-level: an overview may be striped even when the
825        // full-resolution image is tiled, so these are never inherited.
826        info.tile_width = scalar(TiffTag::TileWidth).and_then(|v| u32::try_from(v).ok());
827        info.tile_height = scalar(TiffTag::TileLength).and_then(|v| u32::try_from(v).ok());
828        info.rows_per_strip = scalar(TiffTag::RowsPerStrip).and_then(|v| u32::try_from(v).ok());
829        if let Some(v) = scalar(TiffTag::SamplesPerPixel) {
830            info.samples_per_pixel = v as u16;
831        }
832        if let Some(v) = scalar(TiffTag::BitsPerSample) {
833            info.bits_per_sample = vec![v as u16];
834        }
835        Ok(info)
836    }
837
838    /// Reads band 0 of one tile (or strip) as a [`RasterBuffer`].
839    ///
840    /// Shorthand for [`Self::read_tile_band_buffer`] with `band = 0`; see there
841    /// for the buffer's exact geometry and for multi-band files, which a
842    /// single-band [`RasterBuffer`] cannot represent in one go.
843    ///
844    /// # Errors
845    /// Returns an error if `level` names no overview, if the block coordinates
846    /// are out of range, or if the block cannot be read or decoded.
847    pub fn read_tile_buffer(&self, level: usize, tile_x: u32, tile_y: u32) -> Result<RasterBuffer> {
848        self.read_tile_band_buffer(level, 0, tile_x, tile_y)
849    }
850
851    /// Reads one band of one tile (or strip) as a [`RasterBuffer`].
852    ///
853    /// The band selector matches the rest of the read API
854    /// ([`Self::read_band`], [`Self::read_window`]): `level` first, then a
855    /// zero-based `band`. Both arguments are honoured — the block geometry comes
856    /// from the requested **level's own IFD**, not from the full-resolution
857    /// image, and the requested band is de-interleaved (chunky) or
858    /// plane-selected (planar) exactly as [`Self::read_band`] does it.
859    ///
860    /// The returned buffer is one full block: `tile_width × tile_height` for a
861    /// tiled level, or `image_width × rows_in_this_strip` for a striped one. A
862    /// block that overhangs the raster edge is padded with zeros, so the buffer
863    /// is always the block's nominal size and a tile mosaic stays aligned.
864    ///
865    /// Its samples are in the **host's** byte order, which is what
866    /// [`RasterBuffer`]'s accessors assume; see the crate-level *Byte order of
867    /// decoded samples* section.
868    ///
869    /// Before cool-japan/oxigeo#14 this method handed `RasterBuffer::new` a
870    /// whole chunky block (`tw·th·bps·spp` bytes) while claiming `tw·th`
871    /// pixels, so it could not succeed at all on a `SamplesPerPixel > 1` file,
872    /// and it took the tile dimensions from the primary IFD whatever `level`
873    /// said.
874    ///
875    /// # Errors
876    /// Returns an error if `band` is out of range for the level, if `level`
877    /// names no overview, if `(tile_x, tile_y)` is out of range, if the level
878    /// declares zero-sized blocks or an unsupported sample type, or if a block
879    /// cannot be read or decoded.
880    pub fn read_tile_band_buffer(
881        &self,
882        level: usize,
883        band: usize,
884        tile_x: u32,
885        tile_y: u32,
886    ) -> Result<RasterBuffer> {
887        let info = self.level_info(level)?;
888
889        let band_count = info.samples_per_pixel as usize;
890        if band >= band_count {
891            return Err(OxiGeoError::invalid_parameter_builder(
892                "band",
893                "band index is out of range for this raster",
894            )
895            .with_operation("read_tile_band_buffer")
896            .with_parameter("band", band.to_string())
897            .with_parameter("band_count", band_count.to_string())
898            .with_parameter("level", level.to_string())
899            .with_suggestion("Band indices are zero-based; use GeoTiffReader::band_count()")
900            .build());
901        }
902
903        let data_type =
904            info.data_type()
905                .ok_or(OxiGeoError::Format(FormatError::InvalidDataType {
906                    type_id: 0,
907                }))?;
908        let bytes_per_sample = data_type.size_bytes() as u64;
909
910        // Block geometry, from this level's own tags. A striped level's "tile"
911        // is a strip: full image width, `RowsPerStrip` rows.
912        let (block_width, block_height) = if info.is_tiled() {
913            (
914                u64::from(info.tile_width.unwrap_or_default()),
915                u64::from(info.tile_height.unwrap_or_default()),
916            )
917        } else {
918            (
919                info.width,
920                u64::from(info.rows_per_strip.unwrap_or(info.height as u32)),
921            )
922        };
923        if block_width == 0 || block_height == 0 {
924            return Err(OxiGeoError::Format(FormatError::InvalidHeader {
925                message: format!(
926                    "level {level} declares zero-sized blocks ({block_width}x{block_height})"
927                ),
928            }));
929        }
930
931        // Safe now that both divisors are non-zero.
932        let (blocks_across, blocks_down) = (info.tiles_across(), info.tiles_down());
933        if tile_x >= blocks_across || tile_y >= blocks_down {
934            return Err(OxiGeoError::OutOfBounds {
935                message: format!(
936                    "Tile/strip ({tile_x}, {tile_y}) out of bounds at level {level} \
937                     ({blocks_across}x{blocks_down} blocks)"
938                ),
939            });
940        }
941
942        let x0 = u64::from(tile_x) * block_width;
943        let y0 = u64::from(tile_y) * block_height;
944        // Tiles keep their nominal height (the overhang is padding); the last
945        // strip of a striped level is genuinely shorter.
946        let rows = if info.is_tiled() {
947            block_height
948        } else {
949            block_height.min(info.height.saturating_sub(y0))
950        };
951        let valid_width = block_width.min(info.width.saturating_sub(x0));
952        let valid_height = rows.min(info.height.saturating_sub(y0));
953
954        let to_usize = |v: u64| {
955            usize::try_from(v).map_err(|_| {
956                OxiGeoError::Format(FormatError::InvalidHeader {
957                    message: format!("block size {v} does not fit in usize on this target"),
958                })
959            })
960        };
961        // Bounds the allocation against hostile IFD dimensions, exactly as the
962        // whole-band read does.
963        let buffer_len = checked_band_bytes(
964            to_usize(block_width)?,
965            to_usize(rows)?,
966            to_usize(bytes_per_sample)?,
967            1,
968        )?;
969        let mut data = vec![0u8; buffer_len];
970
971        if valid_width > 0 && valid_height > 0 {
972            let row_bytes = to_usize(valid_width * bytes_per_sample)?;
973            let dst_stride = to_usize(block_width * bytes_per_sample)?;
974            if valid_width == block_width {
975                // The valid region is a contiguous prefix of the block buffer.
976                let len = row_bytes * to_usize(valid_height)?;
977                self.read_window_into(
978                    level,
979                    band,
980                    x0,
981                    y0,
982                    valid_width,
983                    valid_height,
984                    &mut data[..len],
985                )?;
986            } else {
987                let mut window = vec![0u8; row_bytes * to_usize(valid_height)?];
988                self.read_window_into(level, band, x0, y0, valid_width, valid_height, &mut window)?;
989                for row in 0..to_usize(valid_height)? {
990                    let src = row * row_bytes;
991                    let dst = row * dst_stride;
992                    data[dst..dst + row_bytes].copy_from_slice(&window[src..src + row_bytes]);
993                }
994            }
995        }
996
997        RasterBuffer::new(data, block_width, rows, data_type, self.nodata)
998    }
999
1000    /// Returns the raster metadata
1001    #[must_use]
1002    pub fn metadata(&self) -> RasterMetadata {
1003        let info = self.cog_reader.primary_info();
1004
1005        // Generate WKT from GeoKeys
1006        let crs_wkt = parse_geokeys_to_wkt(self.cog_reader.geo_keys());
1007
1008        // Parse color interpretation from photometric
1009        let color_interpretation =
1010            parse_photometric_interpretation(info.photometric, info.samples_per_pixel);
1011
1012        RasterMetadata {
1013            width: info.width,
1014            height: info.height,
1015            band_count: u32::from(info.samples_per_pixel),
1016            data_type: info.data_type().unwrap_or(RasterDataType::UInt8),
1017            geo_transform: self.geo_transform,
1018            crs_wkt,
1019            nodata: self.nodata,
1020            color_interpretation,
1021            layout: oxigeo_core::types::PixelLayout::Tiled {
1022                tile_width: info.tile_width.unwrap_or(256),
1023                tile_height: info.tile_height.unwrap_or(256),
1024            },
1025            driver_metadata: Vec::new(),
1026            statistics: None,
1027        }
1028    }
1029
1030    /// Creates a new reader (alias for `open`)
1031    ///
1032    /// # Errors
1033    /// Returns an error if the file cannot be opened or parsed
1034    pub fn new(source: S) -> Result<Self> {
1035        Self::open(source)
1036    }
1037}
1038
1039/// Checks if data looks like a TIFF file
1040#[must_use]
1041pub fn is_tiff(data: &[u8]) -> bool {
1042    if data.len() < 4 {
1043        return false;
1044    }
1045
1046    // Check for TIFF magic
1047    (data[0] == 0x49 && data[1] == 0x49 && data[2] == 0x2A && data[3] == 0x00)  // Little-endian classic
1048        || (data[0] == 0x4D && data[1] == 0x4D && data[2] == 0x00 && data[3] == 0x2A) // Big-endian classic
1049        || (data[0] == 0x49 && data[1] == 0x49 && data[2] == 0x2B && data[3] == 0x00) // Little-endian BigTIFF
1050        || (data[0] == 0x4D && data[1] == 0x4D && data[2] == 0x00 && data[3] == 0x2B) // Big-endian BigTIFF
1051}
1052
1053/// Checks if a TIFF appears to be a COG
1054pub fn is_cog<S: DataSource>(source: &S) -> Result<bool> {
1055    let tiff = TiffFile::parse(source)?;
1056    let validation = cog::validate_cog(&tiff, source);
1057    Ok(validation.is_valid)
1058}
1059
1060#[cfg(test)]
1061mod tests {
1062    use super::*;
1063    use crate::geokeys::GeoKeyEntry;
1064
1065    #[test]
1066    fn test_is_tiff() {
1067        // Classic TIFF, little-endian
1068        assert!(is_tiff(&[0x49, 0x49, 0x2A, 0x00, 0x08, 0x00, 0x00, 0x00]));
1069
1070        // Classic TIFF, big-endian
1071        assert!(is_tiff(&[0x4D, 0x4D, 0x00, 0x2A, 0x00, 0x00, 0x00, 0x08]));
1072
1073        // BigTIFF, little-endian
1074        assert!(is_tiff(&[0x49, 0x49, 0x2B, 0x00, 0x08, 0x00, 0x00, 0x00]));
1075
1076        // Not TIFF
1077        assert!(!is_tiff(&[0x89, 0x50, 0x4E, 0x47])); // PNG
1078        assert!(!is_tiff(&[0xFF, 0xD8, 0xFF])); // JPEG
1079        assert!(!is_tiff(&[]));
1080    }
1081
1082    /// The host's byte order, as the normalisation rule sees it.
1083    const HOST: ByteOrderType = if cfg!(target_endian = "big") {
1084        ByteOrderType::BigEndian
1085    } else {
1086        ByteOrderType::LittleEndian
1087    };
1088
1089    /// The byte order that is *not* the host's.
1090    const FOREIGN: ByteOrderType = if cfg!(target_endian = "big") {
1091        ByteOrderType::LittleEndian
1092    } else {
1093        ByteOrderType::BigEndian
1094    };
1095
1096    #[test]
1097    fn native_swap_is_skipped_when_the_file_matches_the_host() {
1098        // The common case, and the whole of the zero-cost claim: nothing to do.
1099        for width in [0usize, 1, 2, 3, 4, 6, 8, 16] {
1100            assert!(
1101                !decoded_needs_native_swap(HOST, width, Compression::None),
1102                "width {width} must not be swapped for a host-order file"
1103            );
1104        }
1105    }
1106
1107    #[test]
1108    fn native_swap_covers_exactly_the_two_four_and_eight_byte_widths() {
1109        for width in [2usize, 4, 8] {
1110            assert!(
1111                decoded_needs_native_swap(FOREIGN, width, Compression::None),
1112                "width {width} of a foreign-order file must be swapped"
1113            );
1114        }
1115        // 0 = sub-byte BitsPerSample (bilevel/4-bit), 1 = byte samples, and 3/6
1116        // stand in for exotic widths such as a 24-bit BitsPerSample: none has a
1117        // swap to perform or a defined order to swap to.
1118        for width in [0usize, 1, 3, 5, 6, 7, 9, 12] {
1119            assert!(
1120                !decoded_needs_native_swap(FOREIGN, width, Compression::None),
1121                "width {width} must be passed through untouched"
1122            );
1123        }
1124    }
1125
1126    #[test]
1127    fn native_swap_never_touches_lerc_blocks() {
1128        // This crate's LERC decoder emits native-order samples already
1129        // (`lerc_codec::serialize_native`), so a swap would introduce the
1130        // corruption it exists to remove.
1131        for width in [2usize, 4, 8] {
1132            assert!(!decoded_needs_native_swap(
1133                FOREIGN,
1134                width,
1135                Compression::Lerc
1136            ));
1137            assert!(!decoded_needs_native_swap(HOST, width, Compression::Lerc));
1138        }
1139    }
1140
1141    #[test]
1142    fn native_swap_reverses_whole_samples_and_leaves_a_partial_tail_alone() {
1143        let mut two = [1u8, 2, 3, 4, 9];
1144        swap_sample_bytes::<2>(&mut two);
1145        assert_eq!(two, [2, 1, 4, 3, 9], "trailing odd byte must be untouched");
1146
1147        let mut four = [1u8, 2, 3, 4, 5, 6, 7, 8, 0xaa, 0xbb];
1148        swap_sample_bytes::<4>(&mut four);
1149        assert_eq!(four, [4, 3, 2, 1, 8, 7, 6, 5, 0xaa, 0xbb]);
1150
1151        let mut eight = [1u8, 2, 3, 4, 5, 6, 7, 8];
1152        swap_sample_bytes::<8>(&mut eight);
1153        assert_eq!(eight, [8, 7, 6, 5, 4, 3, 2, 1]);
1154
1155        // Swapping twice is the identity, which is what makes a double swap so
1156        // hard to notice — and why the driver must do it in exactly one place.
1157        let original = [0x12u8, 0x34, 0x56, 0x78];
1158        let mut round_trip = original;
1159        swap_sample_bytes::<4>(&mut round_trip);
1160        swap_sample_bytes::<4>(&mut round_trip);
1161        assert_eq!(round_trip, original);
1162    }
1163
1164    #[test]
1165    fn normalize_samples_to_native_is_a_no_op_for_a_host_order_file() {
1166        let original: Vec<u8> = (0..32).collect();
1167        let mut data = original.clone();
1168        normalize_samples_to_native(&mut data, 4, HOST, Compression::None);
1169        assert_eq!(data, original);
1170
1171        // ... and does reverse each sample for a foreign-order one.
1172        normalize_samples_to_native(&mut data, 4, FOREIGN, Compression::None);
1173        assert_eq!(&data[..4], &[3, 2, 1, 0]);
1174    }
1175
1176    #[test]
1177    fn checked_band_bytes_accepts_reasonable_dimensions() {
1178        // 4096 x 4096 x 2 bytes x 3 samples = 100 MiB — well within the cap.
1179        let n = checked_band_bytes(4096, 4096, 2, 3);
1180        assert!(matches!(n, Ok(v) if v == 4096 * 4096 * 2 * 3));
1181        // A zero-area band is valid (empty buffer).
1182        assert!(matches!(checked_band_bytes(0, 0, 4, 1), Ok(0)));
1183    }
1184
1185    #[test]
1186    fn checked_band_bytes_rejects_oversized_dimensions() {
1187        // 65535 x 65535 x 8 bytes x 4 samples ~= 137 GB — far past the cap.
1188        let err = checked_band_bytes(65535, 65535, 8, 4);
1189        assert!(matches!(
1190            err,
1191            Err(OxiGeoError::Format(FormatError::InvalidHeader { .. }))
1192        ));
1193    }
1194
1195    #[test]
1196    fn checked_band_bytes_rejects_multiplication_overflow() {
1197        // Dimensions chosen so the product wraps `usize`; must be rejected, not
1198        // silently truncated to a small (then out-of-bounds) allocation.
1199        let err = checked_band_bytes(usize::MAX, 2, 1, 1);
1200        assert!(matches!(
1201            err,
1202            Err(OxiGeoError::Format(FormatError::InvalidHeader { .. }))
1203        ));
1204    }
1205
1206    #[test]
1207    fn test_parse_geokeys_to_wkt_none() {
1208        // Test with None input
1209        let wkt = parse_geokeys_to_wkt(None);
1210        assert!(wkt.is_none());
1211    }
1212
1213    #[test]
1214    fn test_parse_geokeys_to_wkt_epsg_4326() {
1215        // Create a mock GeoKeyDirectory with EPSG:4326
1216        let geo_dir = GeoKeyDirectory {
1217            version: 1,
1218            key_revision_major: 1,
1219            key_revision_minor: 0,
1220            entries: vec![GeoKeyEntry {
1221                key_id: GeoKey::GeographicType as u16,
1222                tiff_tag_location: 0,
1223                count: 1,
1224                value_offset: 4326,
1225            }],
1226            double_params: Vec::new(),
1227            ascii_params: String::new(),
1228        };
1229
1230        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1231        assert!(wkt.is_some());
1232        let wkt_str = wkt.unwrap_or_default();
1233        assert!(wkt_str.contains("WGS 84"));
1234        assert!(wkt_str.contains("EPSG"));
1235        assert!(wkt_str.contains("4326"));
1236    }
1237
1238    #[test]
1239    fn test_parse_geokeys_to_wkt_epsg_3857() {
1240        // Create a mock GeoKeyDirectory with EPSG:3857 (Web Mercator)
1241        let geo_dir = GeoKeyDirectory {
1242            version: 1,
1243            key_revision_major: 1,
1244            key_revision_minor: 0,
1245            entries: vec![GeoKeyEntry {
1246                key_id: GeoKey::ProjectedCsType as u16,
1247                tiff_tag_location: 0,
1248                count: 1,
1249                value_offset: 3857,
1250            }],
1251            double_params: Vec::new(),
1252            ascii_params: String::new(),
1253        };
1254
1255        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1256        assert!(wkt.is_some());
1257        let wkt_str = wkt.unwrap_or_default();
1258        assert!(wkt_str.contains("Pseudo-Mercator"));
1259        assert!(wkt_str.contains("3857"));
1260    }
1261
1262    #[test]
1263    fn test_parse_geokeys_to_wkt_utm_north() {
1264        // Create a mock GeoKeyDirectory with EPSG:32632 (UTM Zone 32N)
1265        let geo_dir = GeoKeyDirectory {
1266            version: 1,
1267            key_revision_major: 1,
1268            key_revision_minor: 0,
1269            entries: vec![GeoKeyEntry {
1270                key_id: GeoKey::ProjectedCsType as u16,
1271                tiff_tag_location: 0,
1272                count: 1,
1273                value_offset: 32632,
1274            }],
1275            double_params: Vec::new(),
1276            ascii_params: String::new(),
1277        };
1278
1279        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1280        assert!(wkt.is_some());
1281        let wkt_str = wkt.unwrap_or_default();
1282        assert!(wkt_str.contains("UTM zone 32N"));
1283        assert!(wkt_str.contains("32632"));
1284        assert!(wkt_str.contains("central_meridian"));
1285    }
1286
1287    #[test]
1288    fn test_parse_geokeys_to_wkt_utm_south() {
1289        // Create a mock GeoKeyDirectory with EPSG:32732 (UTM Zone 32S)
1290        let geo_dir = GeoKeyDirectory {
1291            version: 1,
1292            key_revision_major: 1,
1293            key_revision_minor: 0,
1294            entries: vec![GeoKeyEntry {
1295                key_id: GeoKey::ProjectedCsType as u16,
1296                tiff_tag_location: 0,
1297                count: 1,
1298                value_offset: 32732,
1299            }],
1300            double_params: Vec::new(),
1301            ascii_params: String::new(),
1302        };
1303
1304        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1305        assert!(wkt.is_some());
1306        let wkt_str = wkt.unwrap_or_default();
1307        assert!(wkt_str.contains("UTM zone 32S"));
1308        assert!(wkt_str.contains("32732"));
1309        assert!(wkt_str.contains("false_northing"));
1310    }
1311
1312    #[test]
1313    fn test_parse_geokeys_to_wkt_nad83() {
1314        // Create a mock GeoKeyDirectory with EPSG:4269 (NAD83)
1315        let geo_dir = GeoKeyDirectory {
1316            version: 1,
1317            key_revision_major: 1,
1318            key_revision_minor: 0,
1319            entries: vec![GeoKeyEntry {
1320                key_id: GeoKey::GeographicType as u16,
1321                tiff_tag_location: 0,
1322                count: 1,
1323                value_offset: 4269,
1324            }],
1325            double_params: Vec::new(),
1326            ascii_params: String::new(),
1327        };
1328
1329        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1330        assert!(wkt.is_some());
1331        let wkt_str = wkt.unwrap_or_default();
1332        assert!(wkt_str.contains("NAD83"));
1333        assert!(wkt_str.contains("4269"));
1334    }
1335
1336    #[test]
1337    fn test_parse_geokeys_to_wkt_unknown_epsg() {
1338        // Create a mock GeoKeyDirectory with an unknown EPSG code
1339        let geo_dir = GeoKeyDirectory {
1340            version: 1,
1341            key_revision_major: 1,
1342            key_revision_minor: 0,
1343            entries: vec![GeoKeyEntry {
1344                key_id: GeoKey::ProjectedCsType as u16,
1345                tiff_tag_location: 0,
1346                count: 1,
1347                value_offset: 9999,
1348            }],
1349            double_params: Vec::new(),
1350            ascii_params: String::new(),
1351        };
1352
1353        let wkt = parse_geokeys_to_wkt(Some(&geo_dir));
1354        assert!(wkt.is_some());
1355        assert_eq!(wkt.unwrap_or_default(), "EPSG:9999");
1356    }
1357
1358    #[test]
1359    fn test_parse_photometric_gray_single() {
1360        let interp = parse_photometric_interpretation(PhotometricInterpretation::BlackIsZero, 1);
1361        assert_eq!(interp.len(), 1);
1362        assert_eq!(interp[0], ColorInterpretation::Gray);
1363    }
1364
1365    #[test]
1366    fn test_parse_photometric_gray_with_alpha() {
1367        let interp = parse_photometric_interpretation(PhotometricInterpretation::WhiteIsZero, 2);
1368        assert_eq!(interp.len(), 2);
1369        assert_eq!(interp[0], ColorInterpretation::Gray);
1370        assert_eq!(interp[1], ColorInterpretation::Alpha);
1371    }
1372
1373    #[test]
1374    fn test_parse_photometric_rgb() {
1375        let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 3);
1376        assert_eq!(interp.len(), 3);
1377        assert_eq!(interp[0], ColorInterpretation::Red);
1378        assert_eq!(interp[1], ColorInterpretation::Green);
1379        assert_eq!(interp[2], ColorInterpretation::Blue);
1380    }
1381
1382    #[test]
1383    fn test_parse_photometric_rgba() {
1384        let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 4);
1385        assert_eq!(interp.len(), 4);
1386        assert_eq!(interp[0], ColorInterpretation::Red);
1387        assert_eq!(interp[1], ColorInterpretation::Green);
1388        assert_eq!(interp[2], ColorInterpretation::Blue);
1389        assert_eq!(interp[3], ColorInterpretation::Alpha);
1390    }
1391
1392    #[test]
1393    fn test_parse_photometric_palette() {
1394        let interp = parse_photometric_interpretation(PhotometricInterpretation::Palette, 1);
1395        assert_eq!(interp.len(), 1);
1396        assert_eq!(interp[0], ColorInterpretation::PaletteIndex);
1397    }
1398
1399    #[test]
1400    fn test_parse_photometric_cmyk() {
1401        let interp = parse_photometric_interpretation(PhotometricInterpretation::Cmyk, 4);
1402        assert_eq!(interp.len(), 4);
1403        assert_eq!(interp[0], ColorInterpretation::Cyan);
1404        assert_eq!(interp[1], ColorInterpretation::Magenta);
1405        assert_eq!(interp[2], ColorInterpretation::Yellow);
1406        assert_eq!(interp[3], ColorInterpretation::Black);
1407    }
1408
1409    #[test]
1410    fn test_parse_photometric_ycbcr() {
1411        let interp = parse_photometric_interpretation(PhotometricInterpretation::YCbCr, 3);
1412        assert_eq!(interp.len(), 3);
1413        assert_eq!(interp[0], ColorInterpretation::YCbCrY);
1414        assert_eq!(interp[1], ColorInterpretation::YCbCrCb);
1415        assert_eq!(interp[2], ColorInterpretation::YCbCrCr);
1416    }
1417
1418    #[test]
1419    fn test_parse_photometric_ycbcr_with_alpha() {
1420        let interp = parse_photometric_interpretation(PhotometricInterpretation::YCbCr, 4);
1421        assert_eq!(interp.len(), 4);
1422        assert_eq!(interp[0], ColorInterpretation::YCbCrY);
1423        assert_eq!(interp[1], ColorInterpretation::YCbCrCb);
1424        assert_eq!(interp[2], ColorInterpretation::YCbCrCr);
1425        assert_eq!(interp[3], ColorInterpretation::Alpha);
1426    }
1427
1428    #[test]
1429    fn test_parse_photometric_rgb_extra_bands() {
1430        let interp = parse_photometric_interpretation(PhotometricInterpretation::Rgb, 6);
1431        assert_eq!(interp.len(), 6);
1432        assert_eq!(interp[0], ColorInterpretation::Red);
1433        assert_eq!(interp[1], ColorInterpretation::Green);
1434        assert_eq!(interp[2], ColorInterpretation::Blue);
1435        assert_eq!(interp[3], ColorInterpretation::Alpha);
1436        assert_eq!(interp[4], ColorInterpretation::Undefined);
1437        assert_eq!(interp[5], ColorInterpretation::Undefined);
1438    }
1439
1440    #[test]
1441    fn test_parse_photometric_undefined() {
1442        // Test with an uncommon photometric interpretation
1443        let interp =
1444            parse_photometric_interpretation(PhotometricInterpretation::TransparencyMask, 2);
1445        assert_eq!(interp.len(), 2);
1446        assert_eq!(interp[0], ColorInterpretation::Undefined);
1447        assert_eq!(interp[1], ColorInterpretation::Undefined);
1448    }
1449}