gdal 0.19.0

GDAL bindings for Rust
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
use std::{
    ffi::{CStr, CString, NulError},
    path::Path,
    ptr,
};

use gdal_sys::{CPLErr, GDALDatasetH, GDALMajorObjectH};

use crate::cpl::CslStringList;
use crate::errors::{GdalError, Result};
use crate::options::DatasetOptions;
use crate::raster::RasterCreationOptions;
use crate::utils::{_last_cpl_err, _last_null_pointer_err, _path_to_c_string, _string};
use crate::{
    gdal_major_object::MajorObject, spatial_ref::SpatialRef, Driver, GeoTransform, Metadata,
};

pub struct DatasetCapability(&'static CStr);

/// Dataset capabilities
impl DatasetCapability {
    /// Dataset can create new layers.
    pub const CREATE_LAYER: DatasetCapability = DatasetCapability(c"CreateLayer");
    /// Dataset can delete existing layers.
    pub const DELETE_LAYER: DatasetCapability = DatasetCapability(c"DeleteLayer");
    /// Layers of this datasource support CreateGeomField() just after layer creation.
    pub const CREATE_GEOM_FIELD_AFTER_CREATE_LAYER: DatasetCapability =
        DatasetCapability(c"CreateGeomFieldAfterCreateLayer");
    /// Dataset supports curve geometries.
    pub const CURVE_GEOMETRIES: DatasetCapability = DatasetCapability(c"CurveGeometries");
    /// Dataset supports (efficient) transactions.
    pub const TRANSACTIONS: DatasetCapability = DatasetCapability(c"Transactions");
    /// Dataset supports transactions through emulation.
    pub const EMULATED_TRANSACTIONS: DatasetCapability = DatasetCapability(c"EmulatedTransactions");
    /// Dataset has a dedicated GetNextFeature() implementation, potentially returning features from layers in a non sequential way.
    pub const RANDOM_LAYER_READ: DatasetCapability = DatasetCapability(c"RandomLayerRead");
    /// Dataset supports calling CreateFeature() on layers in a non sequential way.
    pub const RANDOM_LAYER_WRITE: DatasetCapability = DatasetCapability(c"RandomLayerWrite");
}

/// Wrapper around a [`GDALDataset`][GDALDataset] object.
///
/// Represents both a [vector dataset][vector-data-model]
/// containing a collection of layers; and a
/// [raster dataset][raster-data-model] containing a collection of raster-bands.
///
/// [vector-data-model]: https://gdal.org/user/vector_data_model.html
/// [raster-data-model]: https://gdal.org/user/raster_data_model.html
/// [GDALDataset]: https://gdal.org/api/gdaldataset_cpp.html#_CPPv411GDALDataset
#[derive(Debug)]
pub struct Dataset {
    c_dataset: GDALDatasetH,
    closed: bool,
}

// GDAL Docs state: The returned dataset should only be accessed by one thread at a time.
// See: https://gdal.org/api/raster_c_api.html#_CPPv48GDALOpenPKc10GDALAccess
unsafe impl Send for Dataset {}

/// Core dataset methods
impl Dataset {
    /// Returns the wrapped C pointer
    ///
    /// # Safety
    /// This method returns a raw C pointer
    pub fn c_dataset(&self) -> GDALDatasetH {
        self.c_dataset
    }

    /// Creates a new Dataset by wrapping a C pointer
    ///
    /// # Safety
    /// This method operates on a raw C pointer
    /// The dataset must not have been closed (using [`gdal_sys::GDALClose`]) before.
    pub unsafe fn from_c_dataset(c_dataset: GDALDatasetH) -> Dataset {
        Dataset {
            c_dataset,
            closed: false,
        }
    }

    /// Open a dataset at the given `path` with default
    /// options.
    pub fn open<P: AsRef<Path>>(path: P) -> Result<Dataset> {
        Self::_open_ex(path.as_ref(), DatasetOptions::default())
    }

    /// Open a dataset with extended options. See
    /// [`GDALOpenEx`].
    ///
    /// [`GDALOpenEx`]: https://gdal.org/doxygen/gdal_8h.html#a9cb8585d0b3c16726b08e25bcc94274a
    pub fn open_ex<P: AsRef<Path>>(path: P, options: DatasetOptions) -> Result<Dataset> {
        Self::_open_ex(path.as_ref(), options)
    }

    fn _open_ex(path: &Path, options: DatasetOptions) -> Result<Dataset> {
        crate::driver::_register_drivers();

        let c_filename = _path_to_c_string(path)?;
        let c_open_flags = options.open_flags.bits();

        // handle driver params:
        // we need to keep the CStrings and the pointers around
        let c_allowed_drivers = options.allowed_drivers.map(|d| {
            d.iter()
                .map(|&s| CString::new(s))
                .collect::<std::result::Result<Vec<CString>, NulError>>()
        });
        let c_drivers_vec = match c_allowed_drivers {
            Some(Err(e)) => return Err(e.into()),
            Some(Ok(c_drivers_vec)) => c_drivers_vec,
            None => Vec::from([]),
        };
        let mut c_drivers_ptrs = c_drivers_vec.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
        c_drivers_ptrs.push(ptr::null());

        let c_drivers_ptr = if options.allowed_drivers.is_some() {
            c_drivers_ptrs.as_ptr()
        } else {
            ptr::null()
        };

        // handle open options params:
        // we need to keep the CStrings and the pointers around
        let c_open_options = options.open_options.map(|d| {
            d.iter()
                .map(|&s| CString::new(s))
                .collect::<std::result::Result<Vec<CString>, NulError>>()
        });
        let c_open_options_vec = match c_open_options {
            Some(Err(e)) => return Err(e.into()),
            Some(Ok(c_open_options_vec)) => c_open_options_vec,
            None => Vec::from([]),
        };
        let mut c_open_options_ptrs = c_open_options_vec
            .iter()
            .map(|s| s.as_ptr())
            .collect::<Vec<_>>();
        c_open_options_ptrs.push(ptr::null());

        let c_open_options_ptr = if options.open_options.is_some() {
            c_open_options_ptrs.as_ptr()
        } else {
            ptr::null()
        };

        // handle sibling files params:
        // we need to keep the CStrings and the pointers around
        let c_sibling_files = options.sibling_files.map(|d| {
            d.iter()
                .map(|&s| CString::new(s))
                .collect::<std::result::Result<Vec<CString>, NulError>>()
        });
        let c_sibling_files_vec = match c_sibling_files {
            Some(Err(e)) => return Err(e.into()),
            Some(Ok(c_sibling_files_vec)) => c_sibling_files_vec,
            None => Vec::from([]),
        };
        let mut c_sibling_files_ptrs = c_sibling_files_vec
            .iter()
            .map(|s| s.as_ptr())
            .collect::<Vec<_>>();
        c_sibling_files_ptrs.push(ptr::null());

        let c_sibling_files_ptr = if options.sibling_files.is_some() {
            c_sibling_files_ptrs.as_ptr()
        } else {
            ptr::null()
        };

        let c_dataset = unsafe {
            gdal_sys::GDALOpenEx(
                c_filename.as_ptr(),
                c_open_flags,
                c_drivers_ptr,
                c_open_options_ptr,
                c_sibling_files_ptr,
            )
        };
        if c_dataset.is_null() {
            return Err(_last_null_pointer_err("GDALOpenEx"));
        }
        Ok(Dataset {
            c_dataset,
            closed: false,
        })
    }

    /// Flush all write cached data to disk.
    ///
    /// See [`gdal_sys::GDALFlushCache`].
    ///
    /// Note: on GDAL versions older than 3.7, this function always succeeds.
    pub fn flush_cache(&mut self) -> Result<()> {
        #[cfg(any(all(major_ge_3, minor_ge_7), major_ge_4))]
        {
            let rv = unsafe { gdal_sys::GDALFlushCache(self.c_dataset) };
            if rv != CPLErr::CE_None {
                return Err(_last_cpl_err(rv));
            }
        }
        #[cfg(not(any(all(major_is_3, minor_ge_7), major_ge_4)))]
        {
            unsafe {
                gdal_sys::GDALFlushCache(self.c_dataset);
            }
        }
        Ok(())
    }

    /// Close the dataset.
    ///
    /// See [`gdal_sys::GDALClose`].
    ///
    /// Note: on GDAL versions older than 3.7.0, this function always succeeds.
    pub fn close(mut self) -> Result<()> {
        self.closed = true;

        #[cfg(any(all(major_ge_3, minor_ge_7), major_ge_4))]
        {
            let rv = unsafe { gdal_sys::GDALClose(self.c_dataset) };
            if rv != CPLErr::CE_None {
                return Err(_last_cpl_err(rv));
            }
        }
        #[cfg(not(any(all(major_is_3, minor_ge_7), major_ge_4)))]
        {
            unsafe {
                gdal_sys::GDALClose(self.c_dataset);
            }
        }
        Ok(())
    }

    /// Fetch the projection definition string for this dataset.
    pub fn projection(&self) -> String {
        let rv = unsafe { gdal_sys::GDALGetProjectionRef(self.c_dataset) };
        _string(rv).unwrap_or_default()
    }

    /// Set the projection reference string for this dataset.
    pub fn set_projection(&mut self, projection: &str) -> Result<()> {
        let c_projection = CString::new(projection)?;
        unsafe { gdal_sys::GDALSetProjection(self.c_dataset, c_projection.as_ptr()) };
        Ok(())
    }

    /// Get the spatial reference system for this dataset.
    pub fn spatial_ref(&self) -> Result<SpatialRef> {
        unsafe {
            let spatial_ref = gdal_sys::GDALGetSpatialRef(self.c_dataset);
            if spatial_ref.is_null() {
                Err(GdalError::NullPointer {
                    method_name: "GDALGetSpatialRef",
                    msg: "Unable to get a spatial reference".to_string(),
                })
            } else {
                SpatialRef::from_c_obj(spatial_ref)
            }
        }
    }

    /// Set the spatial reference system for this dataset.
    pub fn set_spatial_ref(&mut self, spatial_ref: &SpatialRef) -> Result<()> {
        let rv = unsafe { gdal_sys::GDALSetSpatialRef(self.c_dataset, spatial_ref.to_c_hsrs()) };
        if rv != CPLErr::CE_None {
            return Err(_last_cpl_err(rv));
        }
        Ok(())
    }

    pub fn create_copy<P: AsRef<Path>>(
        &self,
        driver: &Driver,
        filename: P,
        options: &RasterCreationOptions,
    ) -> Result<Dataset> {
        fn _create_copy(
            ds: &Dataset,
            driver: &Driver,
            filename: &Path,
            options: &CslStringList,
        ) -> Result<Dataset> {
            let c_filename = _path_to_c_string(filename)?;

            let c_dataset = unsafe {
                gdal_sys::GDALCreateCopy(
                    driver.c_driver(),
                    c_filename.as_ptr(),
                    ds.c_dataset,
                    0,
                    options.as_ptr(),
                    None,
                    ptr::null_mut(),
                )
            };
            if c_dataset.is_null() {
                return Err(_last_null_pointer_err("GDALCreateCopy"));
            }
            Ok(unsafe { Dataset::from_c_dataset(c_dataset) })
        }
        _create_copy(self, driver, filename.as_ref(), options)
    }

    /// Fetch the driver to which this dataset relates.
    pub fn driver(&self) -> Driver {
        unsafe {
            let c_driver = gdal_sys::GDALGetDatasetDriver(self.c_dataset);
            Driver::from_c_driver(c_driver)
        }
    }

    /// Set the [`Dataset`]'s affine transformation; also called a _geo-transformation_.
    ///
    /// This is like a linear transformation preserves points, straight lines and planes.
    /// Also, sets of parallel lines remain parallel after an affine transformation.
    ///
    /// # Arguments
    /// * `transformation` - coefficients of the transformation, which are:
    ///    - x-coordinate of the top-left corner pixel (x-offset)
    ///    - width of a pixel (x-resolution)
    ///    - row rotation (typically zero)
    ///    - y-coordinate of the top-left corner pixel
    ///    - column rotation (typically zero)
    ///    - height of a pixel (y-resolution, typically negative)
    pub fn set_geo_transform(&mut self, transformation: &GeoTransform) -> Result<()> {
        assert_eq!(transformation.len(), 6);
        let rv = unsafe {
            gdal_sys::GDALSetGeoTransform(self.c_dataset, transformation.as_ptr() as *mut f64)
        };
        if rv != CPLErr::CE_None {
            return Err(_last_cpl_err(rv));
        }
        Ok(())
    }

    /// Get the coefficients of the [`crate::Dataset`]'s affine transformation.
    ///
    /// # Returns
    /// - x-coordinate of the top-left corner pixel (x-offset)
    /// - width of a pixel (x-resolution)
    /// - row rotation (typically zero)
    /// - y-coordinate of the top-left corner pixel
    /// - column rotation (typically zero)
    /// - height of a pixel (y-resolution, typically negative)
    pub fn geo_transform(&self) -> Result<GeoTransform> {
        let mut transformation = GeoTransform::default();
        let rv =
            unsafe { gdal_sys::GDALGetGeoTransform(self.c_dataset, transformation.as_mut_ptr()) };

        // check if the dataset has a GeoTransform
        if rv != CPLErr::CE_None {
            return Err(_last_cpl_err(rv));
        }
        Ok(transformation)
    }

    pub fn has_capability(&self, capability: DatasetCapability) -> bool {
        unsafe { gdal_sys::GDALDatasetTestCapability(self.c_dataset(), capability.0.as_ptr()) == 1 }
    }
}

impl MajorObject for Dataset {
    fn gdal_object_ptr(&self) -> GDALMajorObjectH {
        self.c_dataset
    }
}

impl Metadata for Dataset {}

impl Drop for Dataset {
    fn drop(&mut self) {
        if !self.closed {
            unsafe {
                gdal_sys::GDALClose(self.c_dataset);
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use gdal_sys::GDALAccess;

    use crate::dataset::DatasetCapability;
    use crate::test_utils::{fixture, open_gpkg_for_update};
    use crate::GdalOpenFlags;

    use super::*;

    #[test]
    fn test_open_vector() {
        let dataset = Dataset::open(fixture("roads.geojson")).unwrap();
        dataset.close().unwrap();
    }

    #[test]
    fn test_open_ex_ro_vector() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                open_flags: GDALAccess::GA_ReadOnly.into(),
                ..DatasetOptions::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn test_open_ex_update_vector() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                open_flags: GDALAccess::GA_Update.into(),
                ..DatasetOptions::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn test_open_ex_allowed_driver_vector() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                allowed_drivers: Some(&["GeoJSON"]),
                ..DatasetOptions::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn test_open_ex_allowed_driver_vector_fail() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                allowed_drivers: Some(&["TIFF"]),
                ..DatasetOptions::default()
            },
        )
        .unwrap_err();
    }

    #[test]
    fn test_open_ex_open_option() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                open_options: Some(&["FLATTEN_NESTED_ATTRIBUTES=YES"]),
                ..DatasetOptions::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn test_open_ex_extended_flags_vector() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                open_flags: GdalOpenFlags::GDAL_OF_UPDATE | GdalOpenFlags::GDAL_OF_VECTOR,
                ..DatasetOptions::default()
            },
        )
        .unwrap();
    }

    #[test]
    fn test_open_ex_extended_flags_vector_fail() {
        Dataset::open_ex(
            fixture("roads.geojson"),
            DatasetOptions {
                open_flags: GdalOpenFlags::GDAL_OF_UPDATE | GdalOpenFlags::GDAL_OF_RASTER,
                ..DatasetOptions::default()
            },
        )
        .unwrap_err();
    }

    #[test]
    fn test_dataset_capabilities() {
        let ds = Dataset::open(fixture("poly.gpkg")).unwrap();
        assert!(!ds.has_capability(DatasetCapability::CREATE_LAYER));
        assert!(!ds.has_capability(DatasetCapability::DELETE_LAYER));
        assert!(ds.has_capability(DatasetCapability::TRANSACTIONS));

        let (_tmp_path, ds) = open_gpkg_for_update(&fixture("poly.gpkg"));
        assert!(ds.has_capability(DatasetCapability::CREATE_LAYER));
        assert!(ds.has_capability(DatasetCapability::DELETE_LAYER));
        assert!(ds.has_capability(DatasetCapability::TRANSACTIONS));
    }

    #[test]
    fn test_raster_count_on_vector() {
        let ds = Dataset::open(fixture("roads.geojson")).unwrap();
        assert_eq!(ds.raster_count(), 0);
    }
}