-
Notifications
You must be signed in to change notification settings - Fork 91
/
layer.rs
599 lines (538 loc) · 18.8 KB
/
layer.rs
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
use crate::metadata::Metadata;
use crate::spatial_ref::SpatialRef;
use crate::utils::{_last_null_pointer_err, _string};
use crate::vector::defn::Defn;
use crate::vector::{Feature, FieldValue, Geometry};
use crate::{dataset::Dataset, gdal_major_object::MajorObject};
use gdal_sys::{
self, GDALMajorObjectH, OGREnvelope, OGRErr, OGRFieldDefnH, OGRFieldType, OGRLayerH,
};
use libc::c_int;
use std::ptr::null_mut;
use std::{convert::TryInto, ffi::CString, marker::PhantomData};
use crate::errors::*;
/// Layer capabilities
#[allow(clippy::upper_case_acronyms)]
pub enum LayerCaps {
/// Layer capability for random read
OLCRandomRead,
/// Layer capability for sequential write
OLCSequentialWrite,
/// Layer capability for random write
OLCRandomWrite,
/// Layer capability for fast spatial filter
OLCFastSpatialFilter,
/// Layer capability for fast feature count retrieval
OLCFastFeatureCount,
/// Layer capability for fast extent retrieval
OLCFastGetExtent,
/// Layer capability for field creation
OLCCreateField,
/// Layer capability for field deletion
OLCDeleteField,
/// Layer capability for field reordering
OLCReorderFields,
/// Layer capability for field alteration
OLCAlterFieldDefn,
/// Layer capability for transactions
OLCTransactions,
/// Layer capability for feature deletiond
OLCDeleteFeature,
/// Layer capability for setting next feature index
OLCFastSetNextByIndex,
/// Layer capability for strings returned with UTF-8 encoding
OLCStringsAsUTF8,
/// Layer capability for field ignoring
OLCIgnoreFields,
/// Layer capability for geometry field creation
OLCCreateGeomField,
/// Layer capability for curve geometries support
OLCCurveGeometries,
/// Layer capability for measured geometries support
OLCMeasuredGeometries,
}
// Manage conversion to Gdal values
impl LayerCaps {
fn into_cstring(self) -> CString {
CString::new(match self {
Self::OLCRandomRead => "RandomRead",
Self::OLCSequentialWrite => "SequentialWrite",
Self::OLCRandomWrite => "RandomWrite",
Self::OLCFastSpatialFilter => "FastSpatialFilter",
Self::OLCFastFeatureCount => "FastFeatureCount",
Self::OLCFastGetExtent => "FastGetExtent",
Self::OLCCreateField => "CreateField",
Self::OLCDeleteField => "DeleteField",
Self::OLCReorderFields => "ReorderFields",
Self::OLCAlterFieldDefn => "AlterFieldDefn",
Self::OLCTransactions => "Transactions",
Self::OLCDeleteFeature => "DeleteFeature",
Self::OLCFastSetNextByIndex => "FastSetNextByIndex",
Self::OLCStringsAsUTF8 => "StringsAsUTF8",
Self::OLCIgnoreFields => "IgnoreFields",
Self::OLCCreateGeomField => "CreateGeomField",
Self::OLCCurveGeometries => "CurveGeometries",
Self::OLCMeasuredGeometries => "MeasuredGeometries",
})
.unwrap()
}
}
/// Layer in a vector dataset
///
/// ```
/// use std::path::Path;
/// use gdal::Dataset;
/// use gdal::vector::LayerAccess;
///
/// let dataset = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap();
/// let mut layer = dataset.layer(0).unwrap();
/// for feature in layer.features() {
/// // do something with each feature
/// }
/// ```
#[derive(Debug)]
pub struct Layer<'a> {
c_layer: OGRLayerH,
defn: Defn,
phantom: PhantomData<&'a Dataset>,
}
impl<'a> MajorObject for Layer<'a> {
unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
self.c_layer
}
}
impl<'a> Metadata for Layer<'a> {}
impl<'a> LayerAccess for Layer<'a> {
unsafe fn c_layer(&self) -> OGRLayerH {
self.c_layer
}
fn defn(&self) -> &Defn {
&self.defn
}
}
impl<'a> Layer<'a> {
/// Creates a new Layer from a GDAL layer pointer
///
/// # Safety
/// This method operates on a raw C pointer
pub(crate) unsafe fn from_c_layer(_: &'a Dataset, c_layer: OGRLayerH) -> Self {
let c_defn = gdal_sys::OGR_L_GetLayerDefn(c_layer);
let defn = Defn::from_c_defn(c_defn);
Self {
c_layer,
defn,
phantom: PhantomData,
}
}
}
/// Layer in a vector dataset
///
/// ```
/// use std::path::Path;
/// use gdal::Dataset;
/// use gdal::vector::LayerAccess;
///
/// let dataset = Dataset::open(Path::new("fixtures/roads.geojson")).unwrap();
/// let mut layer = dataset.into_layer(0).unwrap();
/// for feature in layer.features() {
/// // do something with each feature
/// }
/// ```
#[derive(Debug)]
pub struct OwnedLayer {
c_layer: OGRLayerH,
defn: Defn,
// we store the dataset to prevent dropping (i.e. closing) it
_dataset: Dataset,
}
impl MajorObject for OwnedLayer {
unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
self.c_layer
}
}
impl Metadata for OwnedLayer {}
impl LayerAccess for OwnedLayer {
unsafe fn c_layer(&self) -> OGRLayerH {
self.c_layer
}
fn defn(&self) -> &Defn {
&self.defn
}
}
impl OwnedLayer {
/// Creates a new Layer from a GDAL layer pointer
///
/// # Safety
/// This method operates on a raw C pointer
pub(crate) unsafe fn from_c_layer(dataset: Dataset, c_layer: OGRLayerH) -> Self {
let c_defn = gdal_sys::OGR_L_GetLayerDefn(c_layer);
let defn = Defn::from_c_defn(c_defn);
Self {
c_layer,
defn,
_dataset: dataset,
}
}
/// Returns iterator over the features in this layer.
///
/// **Note.** This method resets the current index to
/// the beginning before iteration. It also borrows the
/// layer mutably, preventing any overlapping borrows.
pub fn owned_features(mut self) -> OwnedFeatureIterator {
self.reset_feature_reading();
OwnedFeatureIterator::_with_layer(self)
}
/// Returns the `Dataset` this layer belongs to and consumes this layer.
pub fn into_dataset(self) -> Dataset {
self._dataset
}
}
/// As long we have a 1:1 mapping between a dataset and a layer, it is `Send`.
/// We cannot allow a layer to be send, when two or more access (and modify) the same `Dataset`.
unsafe impl Send for OwnedLayer {}
impl From<OwnedLayer> for Dataset {
fn from(owned_layer: OwnedLayer) -> Self {
owned_layer.into_dataset()
}
}
pub trait LayerAccess: Sized {
/// Returns the C wrapped pointer
///
/// # Safety
/// This method returns a raw C pointer
unsafe fn c_layer(&self) -> OGRLayerH;
fn defn(&self) -> &Defn;
/// Returns the feature with the given feature id `fid`, or `None` if not found.
///
/// This function is unaffected by the spatial or attribute filters.
///
/// Not all drivers support this efficiently; however, the call should always work if the
/// feature exists, as a fallback implementation just scans all the features in the layer
/// looking for the desired feature.
fn feature(&self, fid: u64) -> Option<Feature> {
let c_feature = unsafe { gdal_sys::OGR_L_GetFeature(self.c_layer(), fid as i64) };
if c_feature.is_null() {
None
} else {
Some(unsafe { Feature::from_c_feature(self.defn(), c_feature) })
}
}
/// Returns iterator over the features in this layer.
///
/// **Note.** This method resets the current index to
/// the beginning before iteration. It also borrows the
/// layer mutably, preventing any overlapping borrows.
fn features(&mut self) -> FeatureIterator {
self.reset_feature_reading();
FeatureIterator::_with_layer(self)
}
/// Set a spatial filter on this layer.
///
/// Refer [OGR_L_SetSpatialFilter](https://gdal.org/doxygen/classOGRLayer.html#a75c06b4993f8eb76b569f37365cd19ab)
fn set_spatial_filter(&mut self, geometry: &Geometry) {
unsafe { gdal_sys::OGR_L_SetSpatialFilter(self.c_layer(), geometry.c_geometry()) };
}
/// Set a spatial rectangle filter on this layer by specifying the bounds of a rectangle.
fn set_spatial_filter_rect(&mut self, min_x: f64, min_y: f64, max_x: f64, max_y: f64) {
unsafe { gdal_sys::OGR_L_SetSpatialFilterRect(self.c_layer(), min_x, min_y, max_x, max_y) };
}
/// Clear spatial filters set on this layer.
fn clear_spatial_filter(&mut self) {
unsafe { gdal_sys::OGR_L_SetSpatialFilter(self.c_layer(), null_mut()) };
}
/// Get the name of this layer.
fn name(&self) -> String {
let rv = unsafe { gdal_sys::OGR_L_GetName(self.c_layer()) };
_string(rv)
}
fn has_capability(&self, capability: LayerCaps) -> bool {
unsafe {
gdal_sys::OGR_L_TestCapability(self.c_layer(), capability.into_cstring().as_ptr()) == 1
}
}
fn create_defn_fields(&self, fields_def: &[(&str, OGRFieldType::Type)]) -> Result<()> {
for fd in fields_def {
let fdefn = FieldDefn::new(fd.0, fd.1)?;
fdefn.add_to_layer(self)?;
}
Ok(())
}
fn create_feature(&mut self, geometry: Geometry) -> Result<()> {
let feature = Feature::new(self.defn())?;
let c_geometry = unsafe { geometry.into_c_geometry() };
let rv = unsafe { gdal_sys::OGR_F_SetGeometryDirectly(feature.c_feature(), c_geometry) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_F_SetGeometryDirectly",
});
}
let rv = unsafe { gdal_sys::OGR_L_CreateFeature(self.c_layer(), feature.c_feature()) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_CreateFeature",
});
}
Ok(())
}
fn create_feature_fields(
&mut self,
geometry: Geometry,
field_names: &[&str],
values: &[FieldValue],
) -> Result<()> {
let mut ft = Feature::new(self.defn())?;
ft.set_geometry(geometry)?;
for (fd, val) in field_names.iter().zip(values.iter()) {
ft.set_field(fd, val)?;
}
ft.create(self)?;
Ok(())
}
/// Returns the number of features in this layer, even if it requires expensive calculation.
///
/// Some drivers will actually scan the entire layer once to count objects.
///
/// The returned count takes the [spatial filter](`Layer::set_spatial_filter`) into account.
/// For dynamic databases the count may not be exact.
fn feature_count(&self) -> u64 {
(unsafe { gdal_sys::OGR_L_GetFeatureCount(self.c_layer(), 1) }) as u64
}
/// Returns the number of features in this layer, if it is possible to compute this
/// efficiently.
///
/// For some drivers, it would be expensive to establish the feature count, in which case
/// [`None`] will be returned.
///
/// The returned count takes the [spatial filter](`Layer::set_spatial_filter`) into account.
/// For dynamic databases the count may not be exact.
fn try_feature_count(&self) -> Option<u64> {
let rv = unsafe { gdal_sys::OGR_L_GetFeatureCount(self.c_layer(), 0) };
if rv < 0 {
None
} else {
Some(rv as u64)
}
}
/// Returns the extent of this layer as an axis-aligned bounding box, even if it requires
/// expensive calculation.
///
/// Some drivers will actually scan the entire layer once to count objects.
///
/// Depending on the driver, the returned extent may or may not take the [spatial
/// filter](`Layer::set_spatial_filter`) into account. So it is safer to call `get_extent`
/// without setting a spatial filter.
///
/// Layers without any geometry may return [`OGRErr::OGRERR_FAILURE`] to indicate that no
/// meaningful extents could be collected.
fn get_extent(&self) -> Result<gdal_sys::OGREnvelope> {
let mut envelope = OGREnvelope {
MinX: 0.0,
MaxX: 0.0,
MinY: 0.0,
MaxY: 0.0,
};
let force = 1;
let rv = unsafe { gdal_sys::OGR_L_GetExtent(self.c_layer(), &mut envelope, force) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_GetExtent",
});
}
Ok(envelope)
}
/// Returns the extent of this layer as an axis-aligned bounding box, if it is possible to
/// compute this efficiently.
///
/// For some drivers, it would be expensive to calculate the extent, in which case [`None`]
/// will be returned.
///
/// Depending on the driver, the returned extent may or may not take the [spatial
/// filter](`Layer::set_spatial_filter`) into account. So it is safer to call `try_get_extent`
/// without setting a spatial filter.
fn try_get_extent(&self) -> Result<Option<gdal_sys::OGREnvelope>> {
let mut envelope = OGREnvelope {
MinX: 0.0,
MaxX: 0.0,
MinY: 0.0,
MaxY: 0.0,
};
let force = 0;
let rv = unsafe { gdal_sys::OGR_L_GetExtent(self.c_layer(), &mut envelope, force) };
if rv == OGRErr::OGRERR_FAILURE {
Ok(None)
} else {
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_GetExtent",
});
}
Ok(Some(envelope))
}
}
/// Fetch the spatial reference system for this layer.
///
/// Refer [OGR_L_GetSpatialRef](https://gdal.org/doxygen/classOGRLayer.html#a75c06b4993f8eb76b569f37365cd19ab)
fn spatial_ref(&self) -> Result<SpatialRef> {
let c_obj = unsafe { gdal_sys::OGR_L_GetSpatialRef(self.c_layer()) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OGR_L_GetSpatialRef"));
}
unsafe { SpatialRef::from_c_obj(c_obj) }
}
fn reset_feature_reading(&mut self) {
unsafe {
gdal_sys::OGR_L_ResetReading(self.c_layer());
}
}
/// Set a new attribute query that restricts features when using the feature iterator.
///
/// From the GDAL docs: Note that installing a query string will generally result in resetting the current reading position
///
/// Parameters:
/// - `query` in restricted SQL WHERE format
///
fn set_attribute_filter(&mut self, query: &str) -> Result<()> {
let c_str = CString::new(query)?;
let rv = unsafe { gdal_sys::OGR_L_SetAttributeFilter(self.c_layer(), c_str.as_ptr()) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_SetAttributeFilter",
});
}
Ok(())
}
/// Clear the attribute filter set on this layer
///
/// From the GDAL docs: Note that installing a query string will generally result in resetting the current reading position
///
fn clear_attribute_filter(&mut self) {
unsafe {
gdal_sys::OGR_L_SetAttributeFilter(self.c_layer(), null_mut());
}
}
}
pub struct FeatureIterator<'a> {
defn: &'a Defn,
c_layer: OGRLayerH,
size_hint: Option<usize>,
}
impl<'a> Iterator for FeatureIterator<'a> {
type Item = Feature<'a>;
#[inline]
fn next(&mut self) -> Option<Feature<'a>> {
let c_feature = unsafe { gdal_sys::OGR_L_GetNextFeature(self.c_layer) };
if c_feature.is_null() {
None
} else {
Some(unsafe { Feature::from_c_feature(self.defn, c_feature) })
}
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.size_hint {
Some(size) => (size, Some(size)),
None => (0, None),
}
}
}
impl<'a> FeatureIterator<'a> {
pub(crate) fn _with_layer<L: LayerAccess>(layer: &'a L) -> Self {
let defn = layer.defn();
let size_hint = layer.try_feature_count().and_then(|s| s.try_into().ok());
Self {
c_layer: unsafe { layer.c_layer() },
size_hint,
defn,
}
}
}
pub struct OwnedFeatureIterator {
pub(crate) layer: OwnedLayer,
size_hint: Option<usize>,
}
impl<'a> Iterator for &'a mut OwnedFeatureIterator
where
Self: 'a,
{
type Item = Feature<'a>;
#[inline]
fn next(&mut self) -> Option<Feature<'a>> {
let c_feature = unsafe { gdal_sys::OGR_L_GetNextFeature(self.layer.c_layer()) };
if c_feature.is_null() {
return None;
}
Some(unsafe {
// We have to convince the compiler that our `Defn` adheres to our iterator lifetime `<'a>`
let defn: &'a Defn = std::mem::transmute::<&'_ _, &'a _>(self.layer.defn());
Feature::from_c_feature(defn, c_feature)
})
}
fn size_hint(&self) -> (usize, Option<usize>) {
match self.size_hint {
Some(size) => (size, Some(size)),
None => (0, None),
}
}
}
impl OwnedFeatureIterator {
pub(crate) fn _with_layer(layer: OwnedLayer) -> Self {
let size_hint = layer.try_feature_count().and_then(|s| s.try_into().ok());
Self { layer, size_hint }
}
pub fn into_layer(self) -> OwnedLayer {
self.layer
}
}
impl AsMut<OwnedFeatureIterator> for OwnedFeatureIterator {
fn as_mut(&mut self) -> &mut Self {
self
}
}
impl From<OwnedFeatureIterator> for OwnedLayer {
fn from(feature_iterator: OwnedFeatureIterator) -> Self {
feature_iterator.into_layer()
}
}
pub struct FieldDefn {
c_obj: OGRFieldDefnH,
}
impl Drop for FieldDefn {
fn drop(&mut self) {
unsafe { gdal_sys::OGR_Fld_Destroy(self.c_obj) };
}
}
impl MajorObject for FieldDefn {
unsafe fn gdal_object_ptr(&self) -> GDALMajorObjectH {
self.c_obj
}
}
impl FieldDefn {
pub fn new(name: &str, field_type: OGRFieldType::Type) -> Result<FieldDefn> {
let c_str = CString::new(name)?;
let c_obj = unsafe { gdal_sys::OGR_Fld_Create(c_str.as_ptr(), field_type) };
if c_obj.is_null() {
return Err(_last_null_pointer_err("OGR_Fld_Create"));
};
Ok(FieldDefn { c_obj })
}
pub fn set_width(&self, width: i32) {
unsafe { gdal_sys::OGR_Fld_SetWidth(self.c_obj, width as c_int) };
}
pub fn set_precision(&self, precision: i32) {
unsafe { gdal_sys::OGR_Fld_SetPrecision(self.c_obj, precision as c_int) };
}
pub fn add_to_layer<L: LayerAccess>(&self, layer: &L) -> Result<()> {
let rv = unsafe { gdal_sys::OGR_L_CreateField(layer.c_layer(), self.c_obj, 1) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_CreateFeature",
});
}
Ok(())
}
}