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
//! # Address
//!
//! This modules contains structures to do with addresses, positions and
//! suchlike.
#[cfg(feature = "read_write")]
use crate::read_write::component::Component;
#[cfg(feature = "read_write")]
use crate::read_write::error::FromComponentError;
#[cfg(feature = "read_write")]
use regex::Regex;
#[cfg(feature = "read_write")]
use std::mem;
#[cfg(feature = "sql")]
use crate::SqlConversionError;
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[non_exhaustive]
/// A simple structure to hold address information
pub struct Address {
/// This is the street where the address points to.
pub street: Option<String>,
/// This is the locality/city where the address points to.
pub locality: Option<String>,
/// This is the region/county where the address points to.
pub region: Option<String>,
/// This is the code where the address is. This may be a zip/postal code.
pub code: Option<String>,
/// This is the country where ths address points to.
pub country: Option<String>,
/// This is the longitude and latitude of the address.
pub geo: Option<Geo>,
}
#[derive(Debug, Clone, PartialEq, PartialOrd)]
#[non_exhaustive]
/// A simple structure to hold Geo location.
pub struct Geo {
/// This is the longitude for the geo-location.
pub longitude: f64,
/// This is the latitude for the geo-location.
pub latitude: f64,
}
impl Address {
/// Creates a new address
#[must_use]
pub const fn new(
street: Option<String>,
locality: Option<String>,
region: Option<String>,
code: Option<String>,
country: Option<String>,
) -> Self {
Self {
street,
locality,
region,
code,
country,
geo: None,
}
}
}
impl Geo {
/// Creates a `Geo` from longitue and latitude.
///
/// Both are floats and are given in the order `lontigude`
/// and `latitude`.
///
/// # Examples
///
/// Create a new `Geo` at null island.
///
/// ```rust
/// use contack::Geo;
/// let geo = Geo::new(0.0, 0.0);
/// ```
///
#[must_use]
pub const fn new(longitude: f64, latitude: f64) -> Self {
Self {
longitude,
latitude,
}
}
}
#[cfg(feature = "sql")]
#[derive(Debug, Clone, Default)]
pub(crate) struct AddressRaw {
pub street: Option<String>,
pub locality: Option<String>,
pub region: Option<String>,
pub code: Option<String>,
pub country: Option<String>,
pub geo_long: Option<f64>,
pub geo_lat: Option<f64>,
}
#[cfg(feature = "sql")]
pub(crate) type AddressRawTuple = (
Option<String>,
Option<String>,
Option<String>,
Option<String>,
Option<String>,
(Option<f64>, Option<f64>),
);
#[cfg(feature = "sql")]
impl AddressRaw {
/// Creates a new `AddressRaw`
pub(crate) const fn new(
street: Option<String>,
locality: Option<String>,
region: Option<String>,
code: Option<String>,
country: Option<String>,
geo_long: Option<f64>,
geo_lat: Option<f64>,
) -> Self {
Self {
street,
locality,
region,
code,
country,
geo_long,
geo_lat,
}
}
}
#[cfg(feature = "sql")]
impl Address {
/// Converts an address to something that can be used by a `SqlContact`.
pub(crate) fn to_sql_raw(address: Option<Self>) -> AddressRawTuple {
match address {
None => (None, None, None, None, None, (None, None)),
Some(adr) => (
adr.street,
adr.locality,
adr.region,
adr.code,
adr.country,
match adr.geo {
None => (None, None),
Some(geo) => (Some(geo.longitude), Some(geo.latitude)),
},
),
}
}
}
#[cfg(feature = "sql")]
impl AddressRaw {
/// This should only be used internally.
///
/// # Errors
///
/// Fails if given an imcomplete geo, requires both
/// `longitude` and `latitude`.
pub(crate) fn try_from_sql_raw(
self,
) -> Result<Option<Address>, SqlConversionError> {
let address = Address {
// Set up the basic fields
street: self.street,
locality: self.locality,
region: self.region,
code: self.code,
country: self.country,
// Set up the Geo
geo: {
match (self.geo_long, self.geo_lat) {
(Some(longitude), Some(latitude)) => Some(Geo {
longitude,
latitude,
}),
(None, None) => None,
_ => return Err(SqlConversionError::IncompleteGeo),
}
},
};
// Check if the address has all fields.
if address.street.is_none()
&& address.locality.is_none()
&& address.region.is_none()
&& address.code.is_none()
&& address.country.is_none()
&& address.geo.is_none()
{
Ok(None)
} else {
Ok(Some(address))
}
}
}
#[cfg(feature = "read_write")]
impl From<Address> for Component {
fn from(adr: Address) -> Self {
Self {
// No Group
group: None,
// The parameters will probably be appeneded to later, to add
// a type=(work|home), if done through Contact
parameters: match adr.geo {
Some(org) => {
let mut hashmap = std::collections::HashMap::new();
hashmap.insert(
"geo".to_string(),
format!("{},{}", org.longitude, org.latitude),
);
hashmap
}
None => std::collections::HashMap::default(),
},
name: "ADR".to_string(),
values: vec![
vec![],
vec![],
adr.street.map(|x| vec![x]).unwrap_or_default(),
adr.locality.map(|x| vec![x]).unwrap_or_default(),
adr.region.map(|x| vec![x]).unwrap_or_default(),
adr.code.map(|x| vec![x]).unwrap_or_default(),
adr.country.map(|x| vec![x]).unwrap_or_default(),
],
}
}
}
#[cfg(feature = "read_write")]
impl TryFrom<Component> for Address {
type Error = FromComponentError;
fn try_from(mut comp: Component) -> Result<Self, Self::Error> {
lazy_static! {
static ref RE_ORG: Regex =
Regex::new(r#"\d+(\.\d+)?,\d+(\.\d+)?"#).unwrap();
}
// Get rid of extended address and postbox, because, supposedly
// they are not longer supported because they are inconsistent.
Ok(Self {
street: mem::take(&mut comp.values.get_mut(2)).and_then(Vec::pop),
locality: mem::take(&mut comp.values.get_mut(3)).and_then(Vec::pop),
region: mem::take(&mut comp.values.get_mut(4)).and_then(Vec::pop),
code: mem::take(&mut comp.values.get_mut(5)).and_then(Vec::pop),
country: mem::take(&mut comp.values.get_mut(6)).and_then(Vec::pop),
geo: match comp.parameters.get("GEO") {
Some(geo) => {
// Find the GEO part, removing the URI part
let geo = RE_ORG
.find(geo)
.ok_or(FromComponentError::InvalidRegex)?
.as_str();
// Split it by the comma, this should give us the
// long and lat.
let split: Vec<String> =
geo.split(',').map(|x| x.trim().to_owned()).collect();
// Checks that it gives two values
if split.len() != 2 {
return Err(FromComponentError::NotEnoughValues);
}
// Build the Geo
Some(Geo {
longitude: split[0]
.parse()
.map_err(FromComponentError::ParseFloatError)?,
latitude: split[1]
.parse()
.map_err(FromComponentError::ParseFloatError)?,
})
}
None => None,
},
})
}
}