-
Notifications
You must be signed in to change notification settings - Fork 92
/
layer.rs
1516 lines (1356 loc) · 50.4 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
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
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
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::{Envelope, Feature, FieldValue, Geometry, LayerOptions};
use crate::{dataset::Dataset, gdal_major_object::MajorObject};
use gdal_sys::{self, GDALMajorObjectH, OGRErr, OGRFieldDefnH, OGRFieldType, OGRLayerH};
use libc::c_int;
use std::ffi::NulError;
use std::mem::MaybeUninit;
use std::ptr::null_mut;
use std::{ffi::CString, marker::PhantomData};
use crate::errors::*;
use crate::vector::feature::{FeatureIterator, OwnedFeatureIterator};
/// 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,
/// Layer capability for a specialized implementation to ArrowArrayStream
OLCFastGetArrowStream,
}
// 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",
Self::OLCFastGetArrowStream => "FastGetArrowStream",
})
.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> {
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 {
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 feature on this layer layer.
///
/// See: [SetFeature](https://gdal.org/doxygen/classOGRLayer.html#a681139bfd585b74d7218e51a32144283)
fn set_feature(&self, feature: Feature) -> Result<()> {
unsafe { gdal_sys::OGR_L_SetFeature(self.c_layer(), feature.c_feature()) };
Ok(())
}
/// Set a spatial filter on this layer.
///
/// See: [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<Envelope> {
let mut envelope = MaybeUninit::uninit();
let force = 1;
let rv = unsafe { gdal_sys::OGR_L_GetExtent(self.c_layer(), envelope.as_mut_ptr(), force) };
if rv != OGRErr::OGRERR_NONE {
return Err(GdalError::OgrError {
err: rv,
method_name: "OGR_L_GetExtent",
});
}
Ok(unsafe { envelope.assume_init() })
}
/// 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<Envelope>> {
let mut envelope = MaybeUninit::uninit();
let force = 0;
let rv = unsafe { gdal_sys::OGR_L_GetExtent(self.c_layer(), envelope.as_mut_ptr(), 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(unsafe { envelope.assume_init() }))
}
}
/// Get the spatial reference system for this layer.
///
/// Returns `Some(SpatialRef)`, or `None` if one isn't defined.
///
/// See: [OGR_L_GetSpatialRef](https://gdal.org/doxygen/classOGRLayer.html#a75c06b4993f8eb76b569f37365cd19ab)
fn spatial_ref(&self) -> Option<SpatialRef> {
let c_obj = unsafe { gdal_sys::OGR_L_GetSpatialRef(self.c_layer()) };
if c_obj.is_null() {
None
} else {
unsafe { SpatialRef::from_c_obj(c_obj) }.ok()
}
}
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());
}
}
/// Read batches of columnar [Arrow](https://arrow.apache.org/) data from OGR.
///
/// Extended options are available via [`crate::cpl::CslStringList`].
/// As defined in the OGR documentation for [`GetArrowStream`](https://gdal.org/api/ogrlayer_cpp.html#_CPPv4N8OGRLayer14GetArrowStreamEP16ArrowArrayStream12CSLConstList),
/// the current options are:
///
/// * `INCLUDE_FID=YES/NO`. Whether to include the FID column. Defaults to YES.
/// * `MAX_FEATURES_IN_BATCH=integer`. Maximum number of features to retrieve in a ArrowArray batch. Defaults to 65 536.
///
/// Additional driver-specific options may exist.
///
/// This API is new as of GDAL 3.6.
///
/// # Example
///
/// Refer to the example provided in `read_ogr_arrow.rs`.
///
/// # Safety
/// This uses the Arrow C Data Interface to operate on raw pointers provisioned from Rust.
/// These pointers must be valid and provisioned according to the ArrowArrayStream spec.
#[cfg(any(major_ge_4, all(major_is_3, minor_ge_6)))]
unsafe fn read_arrow_stream(
&mut self,
out_stream: *mut gdal_sys::ArrowArrayStream,
options: &crate::cpl::CslStringList,
) -> Result<()> {
self.reset_feature_reading();
unsafe {
let success =
gdal_sys::OGR_L_GetArrowStream(self.c_layer(), out_stream, options.as_ptr());
if !success {
return Err(GdalError::OgrError {
err: 1,
method_name: "OGR_L_GetArrowStream",
});
}
}
Ok(())
}
}
pub struct LayerIterator<'a> {
dataset: &'a Dataset,
idx: usize,
count: usize,
}
impl<'a> Iterator for LayerIterator<'a> {
type Item = Layer<'a>;
#[inline]
fn next(&mut self) -> Option<Layer<'a>> {
let idx = self.idx;
if idx < self.count {
self.idx += 1;
let c_layer =
unsafe { gdal_sys::OGR_DS_GetLayer(self.dataset.c_dataset(), idx as c_int) };
if !c_layer.is_null() {
let layer = unsafe { Layer::from_c_layer(self.dataset, c_layer) };
return Some(layer);
}
}
None
}
fn size_hint(&self) -> (usize, Option<usize>) {
let size = self.count;
(size, Some(size))
}
}
impl<'a> LayerIterator<'a> {
pub fn with_dataset(dataset: &'a Dataset) -> LayerIterator<'a> {
LayerIterator {
dataset,
idx: 0,
count: dataset.layer_count(),
}
}
}
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 {
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(())
}
}
/// [Layer] related methods for [Dataset].
impl Dataset {
fn child_layer(&self, c_layer: OGRLayerH) -> Layer {
unsafe { Layer::from_c_layer(self, c_layer) }
}
fn into_child_layer(self, c_layer: OGRLayerH) -> OwnedLayer {
unsafe { OwnedLayer::from_c_layer(self, c_layer) }
}
/// Get the number of layers in this dataset.
pub fn layer_count(&self) -> usize {
(unsafe { gdal_sys::OGR_DS_GetLayerCount(self.c_dataset()) }) as usize
}
/// Fetch a layer by index.
///
/// Applies to vector datasets, and fetches by the given
/// _0-based_ index.
pub fn layer(&self, idx: usize) -> Result<Layer> {
let idx = libc::c_int::try_from(idx)?;
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayer(self.c_dataset(), idx) };
if c_layer.is_null() {
return Err(_last_null_pointer_err("OGR_DS_GetLayer"));
}
Ok(self.child_layer(c_layer))
}
/// Fetch a layer by index.
///
/// Applies to vector datasets, and fetches by the given
/// _0-based_ index.
pub fn into_layer(self, idx: usize) -> Result<OwnedLayer> {
let idx = libc::c_int::try_from(idx)?;
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayer(self.c_dataset(), idx) };
if c_layer.is_null() {
return Err(_last_null_pointer_err("OGR_DS_GetLayer"));
}
Ok(self.into_child_layer(c_layer))
}
/// Fetch a layer by name.
pub fn layer_by_name(&self, name: &str) -> Result<Layer> {
let c_name = CString::new(name)?;
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayerByName(self.c_dataset(), c_name.as_ptr()) };
if c_layer.is_null() {
return Err(_last_null_pointer_err("OGR_DS_GetLayerByName"));
}
Ok(self.child_layer(c_layer))
}
/// Fetch a layer by name.
pub fn into_layer_by_name(self, name: &str) -> Result<OwnedLayer> {
let c_name = CString::new(name)?;
let c_layer = unsafe { gdal_sys::OGR_DS_GetLayerByName(self.c_dataset(), c_name.as_ptr()) };
if c_layer.is_null() {
return Err(_last_null_pointer_err("OGR_DS_GetLayerByName"));
}
Ok(self.into_child_layer(c_layer))
}
/// Returns an iterator over the layers of the dataset.
pub fn layers(&self) -> LayerIterator {
LayerIterator::with_dataset(self)
}
/// Creates a new layer. The [`LayerOptions`] struct implements `Default`, so you only need to
/// specify those options that deviate from the default.
///
/// # Examples
///
/// Create a new layer with an empty name, no spatial reference, and unknown geometry type:
///
/// ```
/// # use gdal::DriverManager;
/// # let driver = DriverManager::get_driver_by_name("GPKG").unwrap();
/// # let mut dataset = driver.create_vector_only("/vsimem/example.gpkg").unwrap();
/// let blank_layer = dataset.create_layer(Default::default()).unwrap();
/// ```
///
/// Create a new named line string layer using WGS84:
///
/// ```
/// # use gdal::{DriverManager };
/// # use gdal::spatial_ref::SpatialRef;
/// # use gdal::vector::LayerOptions;
/// # let driver = DriverManager::get_driver_by_name("GPKG").unwrap();
/// # let mut dataset = driver.create_vector_only("/vsimem/example.gpkg").unwrap();
/// let roads = dataset.create_layer(LayerOptions {
/// name: "roads",
/// srs: Some(&SpatialRef::from_epsg(4326).unwrap()),
/// ty: gdal_sys::OGRwkbGeometryType::wkbLineString,
/// ..Default::default()
/// }).unwrap();
/// ```
pub fn create_layer(&mut self, options: LayerOptions<'_>) -> Result<Layer> {
let c_name = CString::new(options.name)?;
let c_srs = match options.srs {
Some(srs) => srs.to_c_hsrs(),
None => null_mut(),
};
// Handle string options: we need to keep the CStrings and the pointers around.
let c_options = options.options.map(|d| {
d.iter()
.map(|&s| CString::new(s))
.collect::<std::result::Result<Vec<CString>, NulError>>()
});
let c_options_vec = match c_options {
Some(Err(e)) => return Err(e.into()),
Some(Ok(c_options_vec)) => c_options_vec,
None => Vec::from([]),
};
let mut c_options_ptrs = c_options_vec.iter().map(|s| s.as_ptr()).collect::<Vec<_>>();
c_options_ptrs.push(std::ptr::null());
let c_options_ptr = if options.options.is_some() {
c_options_ptrs.as_ptr()
} else {
std::ptr::null()
};
let c_layer = unsafe {
// The C function takes `char **papszOptions` without mention of `const`, and this is
// propagated to the gdal_sys wrapper. The lack of `const` seems like a mistake in the
// GDAL API, so we just do a cast here.
gdal_sys::OGR_DS_CreateLayer(
self.c_dataset(),
c_name.as_ptr(),
c_srs,
options.ty,
c_options_ptr as *mut *mut libc::c_char,
)
};
if c_layer.is_null() {
return Err(_last_null_pointer_err("OGR_DS_CreateLayer"));
};
Ok(self.child_layer(c_layer))
}
}
#[cfg(test)]
mod tests {
use super::{LayerCaps::*, *};
use crate::options::DatasetOptions;
use crate::spatial_ref::AxisMappingStrategy;
use crate::test_utils::{fixture, open_gpkg_for_update, SuppressGDALErrorLog, TempFixture};
use crate::vector::feature::FeatureIterator;
use crate::{assert_almost_eq, Dataset, DriverManager, GdalOpenFlags};
use gdal_sys::OGRwkbGeometryType;
fn ds_with_layer<F>(ds_name: &str, layer_name: &str, f: F)
where
F: Fn(Layer),
{
let ds = Dataset::open(fixture(ds_name)).unwrap();
let layer = ds.layer_by_name(layer_name).unwrap();
f(layer);
}
fn with_layer<F>(name: &str, f: F)
where
F: Fn(Layer),
{
let ds = Dataset::open(fixture(name)).unwrap();
let layer = ds.layer(0).unwrap();
f(layer);
}
fn with_owned_layer<F>(name: &str, f: F)
where
F: Fn(OwnedLayer),
{
let ds = Dataset::open(fixture(name)).unwrap();
let layer = ds.into_layer(0).unwrap();
f(layer);
}
fn with_features<F>(name: &str, f: F)
where
F: Fn(FeatureIterator),
{
with_layer(name, |mut layer| f(layer.features()));
}
fn with_feature<F>(name: &str, fid: u64, f: F)
where
F: Fn(Feature),
{
with_layer(name, |layer| f(layer.feature(fid).unwrap()));
}
#[test]
fn test_create_layer_options() {
use gdal_sys::OGRwkbGeometryType::wkbPoint;
let (_temp_path, mut ds) = open_gpkg_for_update(&fixture("poly.gpkg"));
let mut options = LayerOptions {
name: "new",
ty: wkbPoint,
..Default::default()
};
ds.create_layer(options.clone()).unwrap();
assert!(ds.create_layer(options.clone()).is_err());
options.options = Some(&["OVERWRITE=YES"]);
assert!(ds.create_layer(options).is_ok());
}
#[test]
fn test_layer_count() {
let ds = Dataset::open(fixture("roads.geojson")).unwrap();
assert_eq!(ds.layer_count(), 1);
}
#[test]
fn test_many_layer_count() {
let ds = Dataset::open(fixture("three_layer_ds.s3db")).unwrap();
assert_eq!(ds.layer_count(), 3);
}
#[test]
fn test_layer_get_extent() {
let ds = Dataset::open(fixture("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
let extent = layer.get_extent().unwrap();
assert_almost_eq(extent.MinX, 26.100768);
assert_almost_eq(extent.MaxX, 26.103515);
assert_almost_eq(extent.MinY, 44.429858);
assert_almost_eq(extent.MaxY, 44.431818);
}
#[test]
fn test_layer_try_get_extent() {
let ds = Dataset::open(fixture("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
if cfg!(any(major_ge_4, all(major_is_3, minor_ge_9))) {
assert!(layer.try_get_extent().unwrap().is_some());
} else {
assert!(layer.try_get_extent().unwrap().is_none());
}
}
#[test]
fn test_layer_spatial_ref() {
let ds = Dataset::open(fixture("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
let srs = layer.spatial_ref().unwrap();
assert_eq!(srs.auth_code().unwrap(), 4326);
}
#[test]
fn test_layer_capabilities() {
let ds = Dataset::open(fixture("roads.geojson")).unwrap();
let layer = ds.layer(0).unwrap();
assert!(!layer.has_capability(OLCFastSpatialFilter));
assert!(layer.has_capability(OLCFastFeatureCount));
if cfg!(any(major_ge_4, all(major_is_3, minor_ge_9))) {
assert!(layer.has_capability(OLCFastGetExtent));
} else {
assert!(!layer.has_capability(OLCFastGetExtent));
}
assert!(layer.has_capability(OLCRandomRead));
assert!(layer.has_capability(OLCStringsAsUTF8));
}
#[test]
fn test_feature_count() {
with_layer("roads.geojson", |layer| {
assert_eq!(layer.feature_count(), 21);
});
}
#[test]
fn test_many_feature_count() {
ds_with_layer("three_layer_ds.s3db", "layer_0", |layer| {
assert_eq!(layer.feature_count(), 3);
});
}
#[test]
fn test_try_feature_count() {
with_layer("roads.geojson", |layer| {
assert_eq!(layer.try_feature_count(), Some(21));
});
}
#[test]
fn test_feature() {
with_layer("roads.geojson", |layer| {
assert!(layer.feature(236194095).is_some());
assert!(layer.feature(23489660).is_some());
assert!(layer.feature(0).is_none());
assert!(layer.feature(404).is_none());
});
}
#[test]
fn test_iterate_features() {
with_features("roads.geojson", |features| {
assert_eq!(features.size_hint(), (21, Some(21)));
assert_eq!(features.count(), 21);
});
}
#[test]
fn test_iterate_layers() {
let ds = Dataset::open(fixture("three_layer_ds.s3db")).unwrap();
let layers = ds.layers();
assert_eq!(layers.size_hint(), (3, Some(3)));
assert_eq!(layers.count(), 3);
}
#[test]
fn test_owned_layers() {
let ds = Dataset::open(fixture("three_layer_ds.s3db")).unwrap();
assert_eq!(ds.layer_count(), 3);
let mut layer = ds.into_layer(0).unwrap();
{
let feature = layer.features().next().unwrap();
assert_eq!(feature.field("id").unwrap(), None);
}
// convert back to dataset
let ds = layer.into_dataset();
assert_eq!(ds.layer_count(), 3);
}
#[test]
fn test_iterate_owned_features() {
with_owned_layer("roads.geojson", |layer| {
let mut features = layer.owned_features();
assert_eq!(features.as_mut().size_hint(), (21, Some(21)));
assert_eq!(features.count(), 21);
// get back layer
let layer = features.into_layer();
assert_eq!(layer.name(), "roads");
});
}
#[test]
fn test_fid() {
with_feature("roads.geojson", 236194095, |feature| {
assert_eq!(feature.fid(), Some(236194095));
});
}
#[test]
fn test_string_field() {
with_feature("roads.geojson", 236194095, |feature| {
assert_eq!(
feature.field("highway").unwrap().unwrap().into_string(),
Some("footway".to_string())
);
});
with_features("roads.geojson", |features| {
assert_eq!(
features
.filter(|field| {
let highway = field.field("highway").unwrap().unwrap().into_string();
highway == Some("residential".to_string())
})
.count(),
2
);
});
}
#[test]
fn test_null_field() {
with_features("null_feature_fields.geojson", |mut features| {
let feature = features.next().unwrap();
assert_eq!(
feature.field("some_int").unwrap(),
Some(FieldValue::IntegerValue(0))
);
assert_eq!(feature.field("some_string").unwrap(), None);
});
}
#[test]
fn test_string_list_field() {
with_features("soundg.json", |mut features| {
let feature = features.next().unwrap();
assert_eq!(
feature.field("a_string_list").unwrap().unwrap(),
FieldValue::StringListValue(vec![
String::from("a"),
String::from("list"),
String::from("of"),
String::from("strings")
])
);
});
}
#[test]
fn test_set_string_list_field() {
with_features("soundg.json", |mut features| {
let mut feature = features.next().unwrap();
let value = FieldValue::StringListValue(vec![
String::from("the"),
String::from("new"),
String::from("strings"),
]);