-
Notifications
You must be signed in to change notification settings - Fork 25
/
Copy pathlib.rs
960 lines (898 loc) · 31.2 KB
/
lib.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
#![doc(html_logo_url = "https://raw.githubusercontent.com/georust/meta/master/logo/logo.png")]
// Copyright 2014-2015 The GeoRust Developers
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// The unstable `doc_auto_cfg` feature annotates documentation with any required cfg/features
// needed for optional items. We set the `docsrs` config when building for docs.rs. To use it
// in a local docs build, run: `cargo +nightly rustdoc --all-features -- --cfg docsrs`
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
//! The `wkt` crate provides conversions to and from the [WKT (Well Known Text)](https://en.wikipedia.org/wiki/Well-known_text_representation_of_geometry)
//! geometry format.
//!
//! Conversions are available via the [`TryFromWkt`] and [`ToWkt`] traits, with implementations for
//! [`geo_types`] and [`geo_traits`] primitives enabled by default.
//!
//! For advanced usage, see the [`types`](crate::types) module for a list of internally used types.
//!
//! This crate has optional `serde` integration for deserializing fields containing WKT. See
//! [`deserialize`] for an example.
//!
//! # Examples
//!
//! ## Read `geo_types` from a WKT string
#![cfg_attr(feature = "geo-types", doc = "```")]
#![cfg_attr(not(feature = "geo-types"), doc = "```ignore")]
//! // This example requires the geo-types feature (on by default).
//! use wkt::TryFromWkt;
//! use geo_types::Point;
//!
//! let point: Point<f64> = Point::try_from_wkt_str("POINT(10 20)").unwrap();
//! assert_eq!(point.y(), 20.0);
//! ```
//!
//! ## Write `geo_types` to a WKT string
#![cfg_attr(feature = "geo-types", doc = "```")]
#![cfg_attr(not(feature = "geo-types"), doc = "```ignore")]
//! // This example requires the geo-types feature (on by default).
//! use wkt::ToWkt;
//! use geo_types::Point;
//!
//! let point: Point<f64> = Point::new(1.0, 2.0);
//! assert_eq!(point.wkt_string(), "POINT(1 2)");
//! ```
//!
//! ## Read or write your own geometry types
//!
//! Not using `geo-types` for your geometries? No problem!
//!
//! As of `wkt` version 0.12, this crate provides read and write integration with [`geo_traits`],
//! a collection of geometry access traits, to provide zero-copy integration with geometry
//! representations other than `geo-types`.
//!
//! This integration allows you to transparently read data from this crate's intermediate geometry
//! structure, and it allows you to write WKT strings directly from your geometry without any
//! intermediate representation.
//!
//! ### Reading
//!
//! You can use [`Wkt::from_str`] to parse a WKT string into this crate's intermediate geometry
//! structure. `Wkt` (and all structs defined in [types]) implement traits from [geo_traits]. You
//! can write functions in terms of those traits and you'll be able to work with the parsed WKT
//! without any further overhead.
//!
//! ```
//! use std::str::FromStr;
//! use wkt::Wkt;
//! use geo_traits::{GeometryTrait, GeometryType};
//!
//! fn is_line_string(geom: &impl GeometryTrait<T = f64>) {
//! assert!(matches!(geom.as_type(), GeometryType::LineString(_)))
//! }
//!
//! let wktls: Wkt<f64> = Wkt::from_str("LINESTRING(10 20, 20 30)").unwrap();
//! is_line_string(&wktls);
//! ```
//!
//! Working with the trait definition is preferable to working with `wkt::Wkt` directly, as the
//! geometry trait will work with many different geometry representations; not just the one from
//! this crate.
//!
//! ### Writing
//!
//! Consult the functions provided in [`to_wkt`]. Those functions will write any `geo_traits` object to WKT without any intermediate overhead.
//!
//! Implement [`geo_traits`] on your own geometry representation and those functions will work out
//! of the box on your data.
use std::default::Default;
use std::fmt;
use std::str::FromStr;
use geo_traits::{
GeometryCollectionTrait, GeometryTrait, LineStringTrait, MultiLineStringTrait, MultiPointTrait,
MultiPolygonTrait, PointTrait, PolygonTrait,
};
use num_traits::{Float, Num, NumCast};
use crate::to_wkt::write_geometry;
use crate::tokenizer::{PeekableTokens, Token, Tokens};
use crate::types::{
Dimension, GeometryCollection, LineString, MultiLineString, MultiPoint, MultiPolygon, Point,
Polygon,
};
pub mod to_wkt;
mod tokenizer;
/// Error variant for this crate
pub mod error;
/// `WKT` primitive types and collections
pub mod types;
mod infer_type;
pub use infer_type::infer_type;
#[cfg(feature = "geo-types")]
extern crate geo_types;
pub use crate::to_wkt::ToWkt;
#[cfg(feature = "geo-types")]
#[deprecated(note = "renamed module to `wkt::geo_types_from_wkt`")]
pub mod conversion;
#[cfg(feature = "geo-types")]
pub mod geo_types_from_wkt;
#[cfg(feature = "geo-types")]
mod geo_types_to_wkt;
#[cfg(feature = "serde")]
extern crate serde;
#[cfg(feature = "serde")]
pub mod deserialize;
#[cfg(feature = "serde")]
pub use deserialize::deserialize_wkt;
mod from_wkt;
pub use from_wkt::TryFromWkt;
#[cfg(all(feature = "serde", feature = "geo-types"))]
#[allow(deprecated)]
pub use deserialize::geo_types::deserialize_geometry;
#[cfg(all(feature = "serde", feature = "geo-types"))]
#[deprecated(
since = "0.10.2",
note = "instead: use wkt::deserialize::geo_types::deserialize_point"
)]
pub use deserialize::geo_types::deserialize_point;
pub trait WktNum: Num + NumCast + PartialOrd + PartialEq + Copy + fmt::Debug {}
impl<T> WktNum for T where T: Num + NumCast + PartialOrd + PartialEq + Copy + fmt::Debug {}
pub trait WktFloat: WktNum + Float {}
impl<T> WktFloat for T where T: WktNum + Float {}
#[derive(Clone, Debug, PartialEq)]
/// All supported WKT geometry [`types`]
pub enum Wkt<T>
where
T: WktNum,
{
Point(Point<T>),
LineString(LineString<T>),
Polygon(Polygon<T>),
MultiPoint(MultiPoint<T>),
MultiLineString(MultiLineString<T>),
MultiPolygon(MultiPolygon<T>),
GeometryCollection(GeometryCollection<T>),
}
impl<T> Wkt<T>
where
T: WktNum + FromStr + Default,
{
fn from_word_and_tokens(
word: &str,
tokens: &mut PeekableTokens<T>,
) -> Result<Self, &'static str> {
// Normally Z/M/ZM is separated by a space from the primary WKT word. E.g. `POINT Z`
// instead of `POINTZ`. However we wish to support both types (in reading). When written
// without a space, `POINTZ` is considered a single word, which means we need to include
// matches here.
match word {
w if w.eq_ignore_ascii_case("POINT") => {
let x = <Point<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POINTZ") => {
let x = <Point<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POINTM") => {
let x = <Point<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POINTZM") => {
let x = <Point<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("LINESTRING") || w.eq_ignore_ascii_case("LINEARRING") => {
let x = <LineString<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("LINESTRINGZ") => {
let x = <LineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("LINESTRINGM") => {
let x = <LineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("LINESTRINGZM") => {
let x = <LineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POLYGON") => {
let x = <Polygon<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POLYGONZ") => {
let x = <Polygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POLYGONM") => {
let x = <Polygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("POLYGONZM") => {
let x = <Polygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOINT") => {
let x = <MultiPoint<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOINTZ") => {
let x = <MultiPoint<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOINTM") => {
let x = <MultiPoint<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOINTZM") => {
let x = <MultiPoint<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTILINESTRING") => {
let x =
<MultiLineString<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTILINESTRINGZ") => {
let x = <MultiLineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTILINESTRINGM") => {
let x = <MultiLineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTILINESTRINGZM") => {
let x = <MultiLineString<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOLYGON") => {
let x = <MultiPolygon<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOLYGONZ") => {
let x = <MultiPolygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOLYGONM") => {
let x = <MultiPolygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("MULTIPOLYGONZM") => {
let x = <MultiPolygon<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("GEOMETRYCOLLECTION") => {
let x =
<GeometryCollection<T> as FromTokens<T>>::from_tokens_with_header(tokens, None);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("GEOMETRYCOLLECTIONZ") => {
let x = <GeometryCollection<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZ),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("GEOMETRYCOLLECTIONM") => {
let x = <GeometryCollection<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYM),
);
x.map(|y| y.into())
}
w if w.eq_ignore_ascii_case("GEOMETRYCOLLECTIONZM") => {
let x = <GeometryCollection<T> as FromTokens<T>>::from_tokens_with_header(
tokens,
Some(Dimension::XYZM),
);
x.map(|y| y.into())
}
_ => Err("Invalid type encountered"),
}
}
}
impl<T> fmt::Display for Wkt<T>
where
T: WktNum + fmt::Display,
{
fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
Ok(write_geometry(f, self)?)
}
}
impl<T> Wkt<T>
where
T: WktNum + FromStr + Default,
{
fn from_tokens(tokens: Tokens<T>) -> Result<Self, &'static str> {
let mut tokens = tokens.peekable();
let word = match tokens.next().transpose()? {
Some(Token::Word(word)) => {
if !word.is_ascii() {
return Err("Encountered non-ascii word");
}
word
}
_ => return Err("Invalid WKT format"),
};
Wkt::from_word_and_tokens(&word, &mut tokens)
}
}
impl<T> FromStr for Wkt<T>
where
T: WktNum + FromStr + Default,
{
type Err = &'static str;
fn from_str(wkt_str: &str) -> Result<Self, Self::Err> {
Wkt::from_tokens(Tokens::from_str(wkt_str))
}
}
impl<T: WktNum> GeometryTrait for Wkt<T> {
type T = T;
type PointType<'b>
= Point<T>
where
Self: 'b;
type LineStringType<'b>
= LineString<T>
where
Self: 'b;
type PolygonType<'b>
= Polygon<T>
where
Self: 'b;
type MultiPointType<'b>
= MultiPoint<T>
where
Self: 'b;
type MultiLineStringType<'b>
= MultiLineString<T>
where
Self: 'b;
type MultiPolygonType<'b>
= MultiPolygon<T>
where
Self: 'b;
type GeometryCollectionType<'b>
= GeometryCollection<T>
where
Self: 'b;
type RectType<'b>
= geo_traits::UnimplementedRect<T>
where
Self: 'b;
type LineType<'b>
= geo_traits::UnimplementedLine<T>
where
Self: 'b;
type TriangleType<'b>
= geo_traits::UnimplementedTriangle<T>
where
Self: 'b;
fn dim(&self) -> geo_traits::Dimensions {
match self {
Wkt::Point(geom) => PointTrait::dim(geom),
Wkt::LineString(geom) => LineStringTrait::dim(geom),
Wkt::Polygon(geom) => PolygonTrait::dim(geom),
Wkt::MultiPoint(geom) => MultiPointTrait::dim(geom),
Wkt::MultiLineString(geom) => MultiLineStringTrait::dim(geom),
Wkt::MultiPolygon(geom) => MultiPolygonTrait::dim(geom),
Wkt::GeometryCollection(geom) => GeometryCollectionTrait::dim(geom),
}
}
fn as_type(
&self,
) -> geo_traits::GeometryType<
'_,
Point<T>,
LineString<T>,
Polygon<T>,
MultiPoint<T>,
MultiLineString<T>,
MultiPolygon<T>,
GeometryCollection<T>,
Self::RectType<'_>,
Self::TriangleType<'_>,
Self::LineType<'_>,
> {
match self {
Wkt::Point(geom) => geo_traits::GeometryType::Point(geom),
Wkt::LineString(geom) => geo_traits::GeometryType::LineString(geom),
Wkt::Polygon(geom) => geo_traits::GeometryType::Polygon(geom),
Wkt::MultiPoint(geom) => geo_traits::GeometryType::MultiPoint(geom),
Wkt::MultiLineString(geom) => geo_traits::GeometryType::MultiLineString(geom),
Wkt::MultiPolygon(geom) => geo_traits::GeometryType::MultiPolygon(geom),
Wkt::GeometryCollection(geom) => geo_traits::GeometryType::GeometryCollection(geom),
}
}
}
impl<T: WktNum> GeometryTrait for &Wkt<T> {
type T = T;
type PointType<'b>
= Point<T>
where
Self: 'b;
type LineStringType<'b>
= LineString<T>
where
Self: 'b;
type PolygonType<'b>
= Polygon<T>
where
Self: 'b;
type MultiPointType<'b>
= MultiPoint<T>
where
Self: 'b;
type MultiLineStringType<'b>
= MultiLineString<T>
where
Self: 'b;
type MultiPolygonType<'b>
= MultiPolygon<T>
where
Self: 'b;
type GeometryCollectionType<'b>
= GeometryCollection<T>
where
Self: 'b;
type RectType<'b>
= geo_traits::UnimplementedRect<T>
where
Self: 'b;
type LineType<'b>
= geo_traits::UnimplementedLine<T>
where
Self: 'b;
type TriangleType<'b>
= geo_traits::UnimplementedTriangle<T>
where
Self: 'b;
fn dim(&self) -> geo_traits::Dimensions {
match self {
Wkt::Point(geom) => PointTrait::dim(geom),
Wkt::LineString(geom) => LineStringTrait::dim(geom),
Wkt::Polygon(geom) => PolygonTrait::dim(geom),
Wkt::MultiPoint(geom) => MultiPointTrait::dim(geom),
Wkt::MultiLineString(geom) => MultiLineStringTrait::dim(geom),
Wkt::MultiPolygon(geom) => MultiPolygonTrait::dim(geom),
Wkt::GeometryCollection(geom) => GeometryCollectionTrait::dim(geom),
}
}
fn as_type(
&self,
) -> geo_traits::GeometryType<
'_,
Point<T>,
LineString<T>,
Polygon<T>,
MultiPoint<T>,
MultiLineString<T>,
MultiPolygon<T>,
GeometryCollection<T>,
Self::RectType<'_>,
Self::TriangleType<'_>,
Self::LineType<'_>,
> {
match self {
Wkt::Point(geom) => geo_traits::GeometryType::Point(geom),
Wkt::LineString(geom) => geo_traits::GeometryType::LineString(geom),
Wkt::Polygon(geom) => geo_traits::GeometryType::Polygon(geom),
Wkt::MultiPoint(geom) => geo_traits::GeometryType::MultiPoint(geom),
Wkt::MultiLineString(geom) => geo_traits::GeometryType::MultiLineString(geom),
Wkt::MultiPolygon(geom) => geo_traits::GeometryType::MultiPolygon(geom),
Wkt::GeometryCollection(geom) => geo_traits::GeometryType::GeometryCollection(geom),
}
}
}
// Specialized implementations on each WKT concrete type.
macro_rules! impl_specialization {
($geometry_type:ident) => {
impl<T: WktNum> GeometryTrait for $geometry_type<T> {
type T = T;
type PointType<'b>
= Point<Self::T>
where
Self: 'b;
type LineStringType<'b>
= LineString<Self::T>
where
Self: 'b;
type PolygonType<'b>
= Polygon<Self::T>
where
Self: 'b;
type MultiPointType<'b>
= MultiPoint<Self::T>
where
Self: 'b;
type MultiLineStringType<'b>
= MultiLineString<Self::T>
where
Self: 'b;
type MultiPolygonType<'b>
= MultiPolygon<Self::T>
where
Self: 'b;
type GeometryCollectionType<'b>
= GeometryCollection<Self::T>
where
Self: 'b;
type RectType<'b>
= geo_traits::UnimplementedRect<T>
where
Self: 'b;
type LineType<'b>
= geo_traits::UnimplementedLine<T>
where
Self: 'b;
type TriangleType<'b>
= geo_traits::UnimplementedTriangle<T>
where
Self: 'b;
fn dim(&self) -> geo_traits::Dimensions {
geo_traits::Dimensions::Xy
}
fn as_type(
&self,
) -> geo_traits::GeometryType<
'_,
Point<T>,
LineString<T>,
Polygon<T>,
MultiPoint<T>,
MultiLineString<T>,
MultiPolygon<T>,
GeometryCollection<T>,
Self::RectType<'_>,
Self::TriangleType<'_>,
Self::LineType<'_>,
> {
geo_traits::GeometryType::$geometry_type(self)
}
}
impl<'a, T: WktNum + 'a> GeometryTrait for &'a $geometry_type<T> {
type T = T;
type PointType<'b>
= Point<Self::T>
where
Self: 'b;
type LineStringType<'b>
= LineString<Self::T>
where
Self: 'b;
type PolygonType<'b>
= Polygon<Self::T>
where
Self: 'b;
type MultiPointType<'b>
= MultiPoint<Self::T>
where
Self: 'b;
type MultiLineStringType<'b>
= MultiLineString<Self::T>
where
Self: 'b;
type MultiPolygonType<'b>
= MultiPolygon<Self::T>
where
Self: 'b;
type GeometryCollectionType<'b>
= GeometryCollection<Self::T>
where
Self: 'b;
type RectType<'b>
= geo_traits::UnimplementedRect<T>
where
Self: 'b;
type LineType<'b>
= geo_traits::UnimplementedLine<T>
where
Self: 'b;
type TriangleType<'b>
= geo_traits::UnimplementedTriangle<T>
where
Self: 'b;
fn dim(&self) -> geo_traits::Dimensions {
geo_traits::Dimensions::Xy
}
fn as_type(
&self,
) -> geo_traits::GeometryType<
'_,
Point<T>,
LineString<T>,
Polygon<T>,
MultiPoint<T>,
MultiLineString<T>,
MultiPolygon<T>,
GeometryCollection<T>,
Self::RectType<'_>,
Self::TriangleType<'_>,
Self::LineType<'_>,
> {
geo_traits::GeometryType::$geometry_type(self)
}
}
};
}
impl_specialization!(Point);
impl_specialization!(LineString);
impl_specialization!(Polygon);
impl_specialization!(MultiPoint);
impl_specialization!(MultiLineString);
impl_specialization!(MultiPolygon);
impl_specialization!(GeometryCollection);
fn infer_geom_dimension<T: WktNum + FromStr + Default>(
tokens: &mut PeekableTokens<T>,
) -> Result<Dimension, &'static str> {
if let Some(Ok(c)) = tokens.peek() {
match c {
// If we match a word check if it's Z/M/ZM and consume the token from the stream
Token::Word(w) => match w.as_str() {
w if w.eq_ignore_ascii_case("Z") => {
tokens.next().unwrap().unwrap();
Ok(Dimension::XYZ)
}
w if w.eq_ignore_ascii_case("M") => {
tokens.next().unwrap().unwrap();
Ok(Dimension::XYM)
}
w if w.eq_ignore_ascii_case("ZM") => {
tokens.next().unwrap().unwrap();
Ok(Dimension::XYZM)
}
w if w.eq_ignore_ascii_case("EMPTY") => Ok(Dimension::XY),
_ => Err("Unexpected word before open paren"),
},
// Not a word, e.g. an open paren
_ => Ok(Dimension::XY),
}
} else {
Err("End of stream")
}
}
trait FromTokens<T>: Sized + Default
where
T: WktNum + FromStr + Default,
{
fn from_tokens(tokens: &mut PeekableTokens<T>, dim: Dimension) -> Result<Self, &'static str>;
/// The preferred top-level FromTokens API, which additionally checks for the presence of Z, M,
/// and ZM in the token stream.
fn from_tokens_with_header(
tokens: &mut PeekableTokens<T>,
dim: Option<Dimension>,
) -> Result<Self, &'static str> {
let dim = if let Some(dim) = dim {
dim
} else {
infer_geom_dimension(tokens)?
};
FromTokens::from_tokens_with_parens(tokens, dim)
}
fn from_tokens_with_parens(
tokens: &mut PeekableTokens<T>,
dim: Dimension,
) -> Result<Self, &'static str> {
match tokens.next().transpose()? {
Some(Token::ParenOpen) => (),
Some(Token::Word(ref s)) if s.eq_ignore_ascii_case("EMPTY") => {
// TODO: expand this to support Z EMPTY
// Maybe create a DefaultXY, DefaultXYZ trait etc for each geometry type, and then
// here match on the dim to decide which default trait to use.
return Ok(Default::default());
}
_ => return Err("Missing open parenthesis for type"),
};
let result = FromTokens::from_tokens(tokens, dim);
match tokens.next().transpose()? {
Some(Token::ParenClose) => (),
_ => return Err("Missing closing parenthesis for type"),
};
result
}
fn from_tokens_with_optional_parens(
tokens: &mut PeekableTokens<T>,
dim: Dimension,
) -> Result<Self, &'static str> {
match tokens.peek() {
Some(Ok(Token::ParenOpen)) => Self::from_tokens_with_parens(tokens, dim),
_ => Self::from_tokens(tokens, dim),
}
}
fn comma_many<F>(
f: F,
tokens: &mut PeekableTokens<T>,
dim: Dimension,
) -> Result<Vec<Self>, &'static str>
where
F: Fn(&mut PeekableTokens<T>, Dimension) -> Result<Self, &'static str>,
{
let mut items = Vec::new();
let item = f(tokens, dim)?;
items.push(item);
while let Some(&Ok(Token::Comma)) = tokens.peek() {
tokens.next(); // throw away comma
let item = f(tokens, dim)?;
items.push(item);
}
Ok(items)
}
}
#[cfg(test)]
mod tests {
use crate::types::{Coord, MultiPolygon, Point};
use crate::Wkt;
use std::str::FromStr;
#[test]
fn empty_string() {
let res: Result<Wkt<f64>, _> = Wkt::from_str("");
assert!(res.is_err());
}
#[test]
fn empty_items() {
let wkt: Wkt<f64> = Wkt::from_str("POINT EMPTY").ok().unwrap();
match wkt {
Wkt::Point(Point(None)) => (),
_ => unreachable!(),
};
let wkt: Wkt<f64> = Wkt::from_str("MULTIPOLYGON EMPTY").ok().unwrap();
match wkt {
Wkt::MultiPolygon(MultiPolygon(polygons)) => assert_eq!(polygons.len(), 0),
_ => unreachable!(),
};
}
#[test]
fn lowercase_point() {
let wkt: Wkt<f64> = Wkt::from_str("point EMPTY").ok().unwrap();
match wkt {
Wkt::Point(Point(None)) => (),
_ => unreachable!(),
};
}
#[test]
fn invalid_number() {
let msg = <Wkt<f64>>::from_str("POINT (10 20.1A)").unwrap_err();
assert_eq!(
"Unable to parse input number as the desired output type",
msg
);
}
#[test]
fn test_points() {
// point(x, y)
let wkt = <Wkt<f64>>::from_str("POINT (10 20.1)").ok().unwrap();
match wkt {
Wkt::Point(Point(Some(coord))) => {
assert_eq!(coord.x, 10.0);
assert_eq!(coord.y, 20.1);
assert_eq!(coord.z, None);
assert_eq!(coord.m, None);
}
_ => panic!("excepted to be parsed as a POINT"),
}
// point(x, y, z)
let wkt = <Wkt<f64>>::from_str("POINT Z (10 20.1 5)").ok().unwrap();
match wkt {
Wkt::Point(Point(Some(coord))) => {
assert_eq!(coord.x, 10.0);
assert_eq!(coord.y, 20.1);
assert_eq!(coord.z, Some(5.0));
assert_eq!(coord.m, None);
}
_ => panic!("excepted to be parsed as a POINT"),
}
// point(x, y, m)
let wkt = <Wkt<f64>>::from_str("POINT M (10 20.1 80)").ok().unwrap();
match wkt {
Wkt::Point(Point(Some(coord))) => {
assert_eq!(coord.x, 10.0);
assert_eq!(coord.y, 20.1);
assert_eq!(coord.z, None);
assert_eq!(coord.m, Some(80.0));
}
_ => panic!("excepted to be parsed as a POINT"),
}
// point(x, y, z, m)
let wkt = <Wkt<f64>>::from_str("POINT ZM (10 20.1 5 80)")
.ok()
.unwrap();
match wkt {
Wkt::Point(Point(Some(coord))) => {
assert_eq!(coord.x, 10.0);
assert_eq!(coord.y, 20.1);
assert_eq!(coord.z, Some(5.0));
assert_eq!(coord.m, Some(80.0));
}
_ => panic!("excepted to be parsed as a POINT"),
}
}
#[test]
fn support_jts_linearring() {
let wkt: Wkt<f64> = Wkt::from_str("linearring (10 20, 30 40)").ok().unwrap();
match wkt {
Wkt::LineString(_ls) => (),
_ => panic!("expected to be parsed as a LINESTRING"),
};
}
#[test]
fn test_debug() {
let g = Wkt::Point(Point(Some(Coord {
x: 1.0,
y: 2.0,
m: None,
z: None,
})));
assert_eq!(
format!("{:?}", g),
"Point(Point(Some(Coord { x: 1.0, y: 2.0, z: None, m: None })))"
);
}
#[test]
fn test_display_on_wkt() {
let wktls: Wkt<f64> = Wkt::from_str("LINESTRING(10 20, 20 30)").unwrap();
assert_eq!(wktls.to_string(), "LINESTRING(10 20,20 30)");
}
}