oxigeo-node 0.2.1

Node.js bindings for OxiGeo - Pure Rust geospatial data abstraction library
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
//! Raster I/O bindings for Node.js
//!
//! This module provides comprehensive raster dataset operations including
//! reading, writing, metadata management, and band operations.

use napi::bindgen_prelude::*;
use napi_derive::napi;
use oxigeo_core::buffer::RasterBuffer;
use oxigeo_core::io::FileDataSource;
use oxigeo_core::types::{
    ColorInterpretation, GeoTransform, NoDataValue, PixelLayout, RasterDataType, RasterMetadata,
};
use oxigeo_geotiff::tiff::Predictor;
use oxigeo_geotiff::writer::{GeoTiffWriterOptions, OverviewResampling, WriterConfig};
use oxigeo_geotiff::{Compression, PhotometricInterpretation};
use std::path::Path;

use crate::buffer::BufferWrapper;
use crate::error::{NodeError, ToNapiResult};

/// Raster dataset for reading and writing geospatial raster data
#[napi]
pub struct Dataset {
    metadata: RasterMetadata,
    bands: Vec<RasterBuffer>,
    file_path: Option<String>,
}

#[napi]
impl Dataset {
    /// Opens a raster dataset from a file
    #[napi(factory)]
    pub fn open(path: String) -> Result<Self> {
        // Determine format from file extension
        let path_obj = Path::new(&path);
        let ext = path_obj
            .extension()
            .and_then(|e| e.to_str())
            .ok_or_else(|| NodeError {
                code: "INVALID_FILE".to_string(),
                message: "File has no extension".to_string(),
            })?;

        match ext.to_lowercase().as_str() {
            "tif" | "tiff" => {
                // Open GeoTIFF using FileDataSource
                let data_source = FileDataSource::open(&path).to_napi()?;
                let reader = oxigeo_geotiff::GeoTiffReader::open(data_source).to_napi()?;
                let metadata = reader.metadata().clone();
                let band_count = metadata.band_count as usize;

                // The underlying reader returns the whole image in its on-disk
                // (band-interleaved-by-pixel / chunky) layout regardless of the
                // band index, so read it once and deinterleave into per-band
                // buffers here. This is the inverse of `interleave_bands` used
                // on save, and is what makes multi-band GeoTIFFs round-trip.
                let interleaved = reader.read_band(0, 0).to_napi()?;
                let bands = Self::deinterleave_bands(
                    &interleaved,
                    metadata.width,
                    metadata.height,
                    band_count,
                    metadata.data_type,
                    metadata.nodata,
                )?;

                Ok(Self {
                    metadata,
                    bands,
                    file_path: Some(path),
                })
            }
            "json" | "geojson" => Err(NodeError {
                code: "INVALID_FORMAT".to_string(),
                message: "GeoJSON is a vector format, use vector API".to_string(),
            }
            .into()),
            _ => Err(NodeError {
                code: "UNSUPPORTED_FORMAT".to_string(),
                message: format!("Unsupported file format: .{}", ext),
            }
            .into()),
        }
    }

    /// Creates a new raster dataset in memory
    #[napi(factory)]
    pub fn create(width: u32, height: u32, band_count: u32, data_type: String) -> Result<Self> {
        let dtype = parse_data_type(&data_type)?;

        let metadata = RasterMetadata {
            width: width as u64,
            height: height as u64,
            band_count,
            data_type: dtype,
            geo_transform: None,
            crs_wkt: None,
            nodata: NoDataValue::None,
            color_interpretation: vec![ColorInterpretation::Undefined; band_count as usize],
            layout: PixelLayout::BandSequential,
            driver_metadata: Vec::new(),
            statistics: None,
        };

        let mut bands = Vec::with_capacity(band_count as usize);
        for _ in 0..band_count {
            bands.push(RasterBuffer::zeros(width as u64, height as u64, dtype));
        }

        Ok(Self {
            metadata,
            bands,
            file_path: None,
        })
    }

    /// Gets the width of the dataset
    #[napi(getter)]
    pub fn width(&self) -> u32 {
        self.metadata.width as u32
    }

    /// Gets the height of the dataset
    #[napi(getter)]
    pub fn height(&self) -> u32 {
        self.metadata.height as u32
    }

    /// Gets the number of bands
    #[napi(getter)]
    pub fn band_count(&self) -> u32 {
        self.metadata.band_count
    }

    /// Gets the data type as a string
    #[napi(getter)]
    pub fn data_type(&self) -> String {
        format_data_type(self.metadata.data_type)
    }

    /// Gets the file path if opened from file
    #[napi(getter)]
    pub fn file_path(&self) -> Option<String> {
        self.file_path.clone()
    }

    /// Gets the CRS as WKT string
    #[napi(getter)]
    pub fn crs(&self) -> Option<String> {
        self.metadata.crs_wkt.clone()
    }

    /// Sets the CRS
    #[napi(setter)]
    pub fn set_crs(&mut self, crs: Option<String>) {
        self.metadata.crs_wkt = crs;
    }

    /// Gets the NoData value
    #[napi(getter)]
    pub fn nodata(&self) -> Option<f64> {
        self.metadata.nodata.as_f64()
    }

    /// Sets the NoData value
    #[napi(setter)]
    pub fn set_nodata(&mut self, value: Option<f64>) {
        self.metadata.nodata = match value {
            Some(v) => NoDataValue::Float(v),
            None => NoDataValue::None,
        };
    }

    /// Gets the geo transform as an array of 6 values
    #[napi]
    pub fn get_geo_transform(&self) -> Option<Vec<f64>> {
        self.metadata.geo_transform.as_ref().map(|gt| {
            vec![
                gt.origin_x,
                gt.pixel_width,
                gt.row_rotation,
                gt.origin_y,
                gt.col_rotation,
                gt.pixel_height,
            ]
        })
    }

    /// Sets the geo transform from an array of 6 values
    #[napi]
    pub fn set_geo_transform(&mut self, values: Vec<f64>) -> Result<()> {
        if values.len() != 6 {
            return Err(NodeError {
                code: "INVALID_PARAMETER".to_string(),
                message: "Geo transform must have exactly 6 values".to_string(),
            }
            .into());
        }

        self.metadata.geo_transform = Some(GeoTransform {
            origin_x: values[0],
            pixel_width: values[1],
            row_rotation: values[2],
            origin_y: values[3],
            col_rotation: values[4],
            pixel_height: values[5],
        });

        Ok(())
    }

    /// Gets the bounding box in geographic coordinates
    #[napi]
    pub fn get_bounds(&self) -> Option<Bounds> {
        self.metadata.geo_transform.as_ref().map(|gt| {
            let min_x = gt.origin_x;
            let max_y = gt.origin_y;
            let max_x = min_x + gt.pixel_width * self.metadata.width as f64;
            let min_y = max_y + gt.pixel_height * self.metadata.height as f64;

            Bounds {
                min_x,
                min_y,
                max_x,
                max_y,
            }
        })
    }

    /// Reads a band as a BufferWrapper
    #[napi]
    pub fn read_band(&self, band_index: u32) -> Result<BufferWrapper> {
        if band_index >= self.metadata.band_count {
            return Err(NodeError {
                code: "OUT_OF_BOUNDS".to_string(),
                message: format!(
                    "Band index {} out of range (0-{})",
                    band_index,
                    self.metadata.band_count - 1
                ),
            }
            .into());
        }

        let buffer = self.bands[band_index as usize].clone();
        Ok(BufferWrapper::from_raster_buffer(buffer))
    }

    /// Reads a band into a provided Node.js Buffer
    #[napi]
    pub fn read_band_into(&self, band_index: u32, mut buffer: Buffer) -> Result<()> {
        if band_index >= self.metadata.band_count {
            return Err(NodeError {
                code: "OUT_OF_BOUNDS".to_string(),
                message: format!(
                    "Band index {} out of range (0-{})",
                    band_index,
                    self.metadata.band_count - 1
                ),
            }
            .into());
        }

        let band = &self.bands[band_index as usize];
        let data = band.as_bytes();

        if buffer.len() != data.len() {
            return Err(NodeError {
                code: "BUFFER_SIZE_MISMATCH".to_string(),
                message: format!(
                    "Buffer size mismatch: expected {} bytes, got {}",
                    data.len(),
                    buffer.len()
                ),
            }
            .into());
        }

        // SAFETY: We've checked the buffer size matches
        buffer.copy_from_slice(data);

        Ok(())
    }

    /// Writes a band from a BufferWrapper
    #[napi]
    pub fn write_band(&mut self, band_index: u32, buffer: &BufferWrapper) -> Result<()> {
        if band_index >= self.metadata.band_count {
            return Err(NodeError {
                code: "OUT_OF_BOUNDS".to_string(),
                message: format!(
                    "Band index {} out of range (0-{})",
                    band_index,
                    self.metadata.band_count - 1
                ),
            }
            .into());
        }

        if buffer.width() != self.width() || buffer.height() != self.height() {
            return Err(NodeError {
                code: "DIMENSION_MISMATCH".to_string(),
                message: format!(
                    "Buffer dimensions ({}x{}) don't match dataset ({}x{})",
                    buffer.width(),
                    buffer.height(),
                    self.width(),
                    self.height()
                ),
            }
            .into());
        }

        self.bands[band_index as usize] = buffer.inner().clone();
        Ok(())
    }

    /// Reads a window (subset) of a band
    #[napi]
    pub fn read_window(
        &self,
        band_index: u32,
        x_off: u32,
        y_off: u32,
        width: u32,
        height: u32,
    ) -> Result<BufferWrapper> {
        if band_index >= self.metadata.band_count {
            return Err(NodeError {
                code: "OUT_OF_BOUNDS".to_string(),
                message: format!(
                    "Band index {} out of range (0-{})",
                    band_index,
                    self.metadata.band_count - 1
                ),
            }
            .into());
        }

        if x_off + width > self.width() || y_off + height > self.height() {
            return Err(NodeError {
                code: "OUT_OF_BOUNDS".to_string(),
                message: format!(
                    "Window ({}+{}, {}+{}) exceeds dataset bounds ({}x{})",
                    x_off,
                    width,
                    y_off,
                    height,
                    self.width(),
                    self.height()
                ),
            }
            .into());
        }

        let band = &self.bands[band_index as usize];
        let dtype = band.data_type();
        let mut window_buffer = RasterBuffer::zeros(width as u64, height as u64, dtype);

        // Copy window data
        for y in 0..height {
            for x in 0..width {
                let src_x = (x_off + x) as u64;
                let src_y = (y_off + y) as u64;
                let dst_x = x as u64;
                let dst_y = y as u64;

                // Copy pixel using get_pixel/set_pixel
                let value = band.get_pixel(src_x, src_y).to_napi()?;
                window_buffer.set_pixel(dst_x, dst_y, value).to_napi()?;
            }
        }

        Ok(BufferWrapper::from_raster_buffer(window_buffer))
    }

    /// Saves the dataset to a file
    #[napi]
    pub fn save(&self, path: String) -> Result<()> {
        let path_obj = Path::new(&path);
        let ext = path_obj
            .extension()
            .and_then(|e| e.to_str())
            .ok_or_else(|| NodeError {
                code: "INVALID_FILE".to_string(),
                message: "File has no extension".to_string(),
            })?;

        match ext.to_lowercase().as_str() {
            "tif" | "tiff" => {
                // Create WriterConfig from metadata
                let config = WriterConfig {
                    width: self.metadata.width,
                    height: self.metadata.height,
                    band_count: self.metadata.band_count as u16,
                    data_type: self.metadata.data_type,
                    compression: Compression::Lzw,
                    predictor: Predictor::HorizontalDifferencing,
                    tile_width: Some(256),
                    tile_height: Some(256),
                    photometric: PhotometricInterpretation::BlackIsZero,
                    geo_transform: self.metadata.geo_transform,
                    epsg_code: None,
                    nodata: self.metadata.nodata,
                    use_bigtiff: false,
                    generate_overviews: false,
                    overview_resampling: OverviewResampling::Average,
                    overview_levels: Vec::new(),
                };

                let options = GeoTiffWriterOptions::default();
                let mut writer =
                    oxigeo_geotiff::writer::GeoTiffWriter::create(&path, config, options)
                        .to_napi()?;

                // The GeoTIFF writer expects a single, fully band-interleaved
                // (BIP: band-interleaved-by-pixel) buffer covering every band,
                // and validates the total length against
                // width * height * bytes_per_sample * band_count. Calling
                // `write` once per band (with only a single band's bytes) fails
                // that check for multi-band rasters and rewrites the TIFF header
                // on every call. Instead, interleave all bands up front and
                // write exactly once.
                let interleaved = self.interleave_bands()?;
                writer.write(&interleaved).to_napi()?;

                Ok(())
            }
            _ => Err(NodeError {
                code: "UNSUPPORTED_FORMAT".to_string(),
                message: format!("Unsupported output format: .{}", ext),
            }
            .into()),
        }
    }

    /// Builds a single band-interleaved-by-pixel (BIP) byte buffer spanning
    /// every band, in the layout the GeoTIFF writer expects.
    ///
    /// For each pixel (in row-major order) the `bytes_per_sample` bytes of
    /// every band are emitted consecutively, i.e. `[b0_p0, b1_p0, ..., b0_p1,
    /// b1_p1, ...]`. This mirrors the interleaving logic used by the Python
    /// bindings and is required for `band_count > 1`; for a single band it is a
    /// straight copy of that band's bytes.
    fn interleave_bands(&self) -> Result<Vec<u8>> {
        let bytes_per_sample = self.metadata.data_type.size_bytes();
        let pixel_count = (self.metadata.width as usize) * (self.metadata.height as usize);
        let expected_band_len = pixel_count * bytes_per_sample;

        // Every band buffer must match the dataset dimensions/type exactly, or
        // the interleaved slicing below would read past the end of a band.
        for (index, band) in self.bands.iter().enumerate() {
            let band_len = band.as_bytes().len();
            if band_len != expected_band_len {
                return Err(NodeError {
                    code: "BAND_SIZE_MISMATCH".to_string(),
                    message: format!(
                        "Band {} has {} bytes, expected {} ({}x{} x {} bytes/sample)",
                        index,
                        band_len,
                        expected_band_len,
                        self.metadata.width,
                        self.metadata.height,
                        bytes_per_sample
                    ),
                }
                .into());
            }
        }

        // Fast path: a single band is already in the required layout.
        if self.bands.len() == 1 {
            return Ok(self.bands[0].as_bytes().to_vec());
        }

        let band_count = self.bands.len();
        let mut interleaved = vec![0u8; pixel_count * band_count * bytes_per_sample];
        for (band_index, band) in self.bands.iter().enumerate() {
            let band_bytes = band.as_bytes();
            for pixel in 0..pixel_count {
                let src = pixel * bytes_per_sample;
                let dst = (pixel * band_count + band_index) * bytes_per_sample;
                interleaved[dst..dst + bytes_per_sample]
                    .copy_from_slice(&band_bytes[src..src + bytes_per_sample]);
            }
        }

        Ok(interleaved)
    }

    /// Splits a single band-interleaved-by-pixel (BIP) byte buffer into one
    /// contiguous (band-sequential) buffer per band.
    ///
    /// This is the inverse of [`Self::interleave_bands`]. The input is expected
    /// to contain `width * height * bytes_per_sample * band_count` bytes with
    /// each pixel's samples stored consecutively; band `b` is gathered by taking
    /// the `b`-th sample of every pixel.
    fn deinterleave_bands(
        interleaved: &[u8],
        width: u64,
        height: u64,
        band_count: usize,
        data_type: RasterDataType,
        nodata: NoDataValue,
    ) -> Result<Vec<RasterBuffer>> {
        let bytes_per_sample = data_type.size_bytes();
        let pixel_count = (width as usize) * (height as usize);
        let expected = pixel_count * bytes_per_sample * band_count;

        if interleaved.len() != expected {
            return Err(NodeError {
                code: "FORMAT_ERROR".to_string(),
                message: format!(
                    "Interleaved raster has {} bytes, expected {} ({}x{} x {} bands x {} bytes/sample)",
                    interleaved.len(),
                    expected,
                    width,
                    height,
                    band_count,
                    bytes_per_sample
                ),
            }
            .into());
        }

        let mut bands = Vec::with_capacity(band_count);
        for band_index in 0..band_count {
            // Fast path: a single band is already band-sequential.
            let band_bytes = if band_count == 1 {
                interleaved.to_vec()
            } else {
                let mut buf = vec![0u8; pixel_count * bytes_per_sample];
                for pixel in 0..pixel_count {
                    let src = (pixel * band_count + band_index) * bytes_per_sample;
                    let dst = pixel * bytes_per_sample;
                    buf[dst..dst + bytes_per_sample]
                        .copy_from_slice(&interleaved[src..src + bytes_per_sample]);
                }
                buf
            };

            let buffer =
                RasterBuffer::new(band_bytes, width, height, data_type, nodata).to_napi()?;
            bands.push(buffer);
        }

        Ok(bands)
    }

    /// Gets metadata as a JavaScript object
    #[napi]
    pub fn get_metadata(&self) -> Metadata {
        Metadata {
            width: self.width(),
            height: self.height(),
            band_count: self.band_count(),
            data_type: self.data_type(),
            crs: self.crs(),
            nodata: self.nodata(),
            geo_transform: self.get_geo_transform(),
            bounds: self.get_bounds(),
        }
    }

    /// Creates a copy of the dataset
    #[napi]
    pub fn clone(&self) -> Self {
        Self {
            metadata: self.metadata.clone(),
            bands: self.bands.clone(),
            file_path: self.file_path.clone(),
        }
    }

    /// Borrows the underlying per-band pixel buffers (crate-internal).
    ///
    /// Used by the parallel-processing helpers in `async_ops` which need direct
    /// read access to each band's pixels.
    pub(crate) fn bands(&self) -> &[RasterBuffer] {
        &self.bands
    }

    /// Builds a new dataset that shares this dataset's metadata/geo-referencing
    /// but carries a freshly computed set of band buffers (crate-internal).
    ///
    /// The number of supplied bands must match the existing band count so that
    /// the metadata stays consistent with the pixel data.
    pub(crate) fn with_bands(&self, bands: Vec<RasterBuffer>) -> Self {
        let mut metadata = self.metadata.clone();
        metadata.band_count = bands.len() as u32;
        Self {
            metadata,
            bands,
            file_path: self.file_path.clone(),
        }
    }

    /// Converts pixel coordinates to geographic coordinates
    #[napi]
    pub fn pixel_to_geo(&self, x: f64, y: f64) -> Result<Coordinate> {
        let gt = self
            .metadata
            .geo_transform
            .as_ref()
            .ok_or_else(|| NodeError {
                code: "NO_GEO_TRANSFORM".to_string(),
                message: "Dataset has no geo transform".to_string(),
            })?;

        let geo_x = gt.origin_x + x * gt.pixel_width + y * gt.row_rotation;
        let geo_y = gt.origin_y + x * gt.col_rotation + y * gt.pixel_height;

        Ok(Coordinate { x: geo_x, y: geo_y })
    }

    /// Converts geographic coordinates to pixel coordinates
    #[napi]
    pub fn geo_to_pixel(&self, x: f64, y: f64) -> Result<Coordinate> {
        let gt = self
            .metadata
            .geo_transform
            .as_ref()
            .ok_or_else(|| NodeError {
                code: "NO_GEO_TRANSFORM".to_string(),
                message: "Dataset has no geo transform".to_string(),
            })?;

        // Inverse transform
        let det = gt.pixel_width * gt.pixel_height - gt.row_rotation * gt.col_rotation;
        if det.abs() < 1e-10 {
            return Err(NodeError {
                code: "INVALID_TRANSFORM".to_string(),
                message: "Geo transform is not invertible".to_string(),
            }
            .into());
        }

        let dx = x - gt.origin_x;
        let dy = y - gt.origin_y;

        let pixel_x = (gt.pixel_height * dx - gt.row_rotation * dy) / det;
        let pixel_y = (-gt.col_rotation * dx + gt.pixel_width * dy) / det;

        Ok(Coordinate {
            x: pixel_x,
            y: pixel_y,
        })
    }
}

/// Metadata object for JavaScript
#[napi(object)]
pub struct Metadata {
    pub width: u32,
    pub height: u32,
    pub band_count: u32,
    pub data_type: String,
    pub crs: Option<String>,
    pub nodata: Option<f64>,
    pub geo_transform: Option<Vec<f64>>,
    pub bounds: Option<Bounds>,
}

/// Bounding box
#[napi(object)]
#[derive(Clone)]
pub struct Bounds {
    pub min_x: f64,
    pub min_y: f64,
    pub max_x: f64,
    pub max_y: f64,
}

/// Coordinate pair
#[napi(object)]
pub struct Coordinate {
    pub x: f64,
    pub y: f64,
}

/// Parse data type string to RasterDataType
fn parse_data_type(dtype: &str) -> Result<RasterDataType> {
    match dtype.to_lowercase().as_str() {
        "uint8" | "u8" => Ok(RasterDataType::UInt8),
        "int16" | "i16" => Ok(RasterDataType::Int16),
        "uint16" | "u16" => Ok(RasterDataType::UInt16),
        "int32" | "i32" => Ok(RasterDataType::Int32),
        "uint32" | "u32" => Ok(RasterDataType::UInt32),
        "float32" | "f32" => Ok(RasterDataType::Float32),
        "float64" | "f64" => Ok(RasterDataType::Float64),
        _ => Err(NodeError {
            code: "INVALID_DATA_TYPE".to_string(),
            message: format!("Unknown data type: {}", dtype),
        }
        .into()),
    }
}

/// Format RasterDataType to string
fn format_data_type(dtype: RasterDataType) -> String {
    match dtype {
        RasterDataType::UInt8 => "uint8".to_string(),
        RasterDataType::Int16 => "int16".to_string(),
        RasterDataType::UInt16 => "uint16".to_string(),
        RasterDataType::Int32 => "int32".to_string(),
        RasterDataType::UInt32 => "uint32".to_string(),
        RasterDataType::Float32 => "float32".to_string(),
        RasterDataType::Float64 => "float64".to_string(),
        _ => "unknown".to_string(),
    }
}

/// Opens a raster dataset (convenience function)
#[allow(dead_code)]
#[napi]
pub fn open_raster(path: String) -> Result<Dataset> {
    Dataset::open(path)
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::expect_used, clippy::panic)]
mod tests {
    use super::*;

    /// Builds a unique temp path for a test artifact, scoped to the OS temp dir
    /// so nothing is hard-coded and parallel test runs don't collide.
    fn temp_tif(tag: &str) -> String {
        let mut path = std::env::temp_dir();
        let nanos = std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .map(|d| d.as_nanos())
            .unwrap_or(0);
        path.push(format!("oxigeo_node_{tag}_{nanos}.tif"));
        path.to_string_lossy().into_owned()
    }

    #[test]
    fn interleave_single_band_is_a_straight_copy() {
        let mut ds = Dataset::create(3, 2, 1, "uint8".to_string()).expect("create");
        let mut buf = BufferWrapper::new(3, 2, "uint8".to_string()).expect("buffer");
        for y in 0..2 {
            for x in 0..3 {
                buf.set_pixel(x, y, (x + y * 3) as f64).expect("set");
            }
        }
        ds.write_band(0, &buf).expect("write_band");
        let interleaved = ds.interleave_bands().expect("interleave");
        assert_eq!(interleaved, ds.bands[0].as_bytes());
    }

    #[test]
    fn interleave_two_bands_is_band_interleaved_by_pixel() {
        let mut ds = Dataset::create(2, 1, 2, "uint8".to_string()).expect("create");
        let mut b0 = BufferWrapper::new(2, 1, "uint8".to_string()).expect("b0");
        let mut b1 = BufferWrapper::new(2, 1, "uint8".to_string()).expect("b1");
        b0.set_pixel(0, 0, 10.0).expect("set");
        b0.set_pixel(1, 0, 11.0).expect("set");
        b1.set_pixel(0, 0, 20.0).expect("set");
        b1.set_pixel(1, 0, 21.0).expect("set");
        ds.write_band(0, &b0).expect("write b0");
        ds.write_band(1, &b1).expect("write b1");

        let interleaved = ds.interleave_bands().expect("interleave");
        // BIP layout for 2 pixels x 2 bands (uint8): b0p0, b1p0, b0p1, b1p1.
        assert_eq!(interleaved, vec![10u8, 20u8, 11u8, 21u8]);
    }

    #[test]
    fn save_and_reopen_multiband_geotiff_roundtrips() {
        let width = 8u32;
        let height = 6u32;
        let mut ds = Dataset::create(width, height, 3, "uint8".to_string()).expect("create");

        // Distinct, per-band gradients so a band/offset mixup would be caught.
        for band in 0..3u32 {
            let mut buf = BufferWrapper::new(width, height, "uint8".to_string()).expect("buffer");
            for y in 0..height {
                for x in 0..width {
                    let value = (band * 40 + x + y) % 256;
                    buf.set_pixel(x, y, value as f64).expect("set");
                }
            }
            ds.write_band(band, &buf).expect("write_band");
        }

        let path = temp_tif("multiband");
        ds.save(path.clone()).expect("save multi-band geotiff");

        let reopened = Dataset::open(path.clone()).expect("reopen");
        assert_eq!(reopened.band_count(), 3);
        assert_eq!(reopened.width(), width);
        assert_eq!(reopened.height(), height);

        for band in 0..3u32 {
            let read = reopened.read_band(band).expect("read_band");
            for y in 0..height {
                for x in 0..width {
                    let expected = ((band * 40 + x + y) % 256) as f64;
                    let actual = read.get_pixel(x, y).expect("get_pixel");
                    assert!(
                        (actual - expected).abs() < f64::EPSILON,
                        "band {band} pixel ({x},{y}): expected {expected}, got {actual}"
                    );
                }
            }
        }

        let _ = std::fs::remove_file(&path);
    }

    #[test]
    fn interleave_rejects_wrong_size_band() {
        // Manufacture an inconsistent dataset: metadata says 2x2 but a band is
        // the wrong length. `with_bands` keeps metadata, so build via fields.
        let mut ds = Dataset::create(2, 2, 1, "uint8".to_string()).expect("create");
        ds.bands[0] = RasterBuffer::zeros(3, 3, RasterDataType::UInt8);
        let err = ds.interleave_bands();
        assert!(err.is_err(), "mismatched band length must be rejected");
    }
}

/// Creates a new raster dataset (convenience function)
#[allow(dead_code)]
#[napi]
pub fn create_raster(
    width: u32,
    height: u32,
    band_count: u32,
    data_type: String,
) -> Result<Dataset> {
    Dataset::create(width, height, band_count, data_type)
}