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
use crate::enums::{ByteOrder, CoordDimensions};
use crate::error::{Error, GResult};
use crate::functions::errcheck;
use geos_sys::*;
use libc::{c_char, c_void, strlen};
use std::convert::TryFrom;
use std::ffi::CStr;
use std::ptr::NonNull;
use std::slice;
use std::sync::Mutex;
thread_local!(
static CONTEXT: ContextHandle = ContextHandle::init().unwrap();
);
/// Provides thread-local geos context to the function `f`.
///
/// It is an efficient and thread-safe way of providing geos context to be used in reentrant c api.
///
/// # Example
///
/// ```ignore
/// with_context(|ctx| unsafe {
/// let ptr = GEOSGeom_createEmptyPolygon_r(ctx.as_raw());
/// GEOSGeom_destroy_r(ctx.as_raw, ptr);
/// })
/// ```
pub fn with_context<R>(f: impl FnOnce(&ContextHandle) -> R) -> R {
CONTEXT.with(f)
}
pub type HandlerCallback = Box<dyn Fn(&str) + Send + Sync>;
unsafe extern "C" fn message_handler(message: *const c_char, data: *mut c_void) {
let inner_context: &InnerContext = &*(data.cast());
if let Ok(callback) = inner_context.callback.lock() {
let bytes = slice::from_raw_parts(message.cast::<u8>(), strlen(message) + 1);
let s = CStr::from_bytes_with_nul_unchecked(bytes);
let notif = s.to_str().expect("invalid CStr -> &str conversion");
callback(notif);
if let Ok(mut last) = inner_context.last.lock() {
*last = Some(notif.to_owned());
}
}
}
pub struct InnerContext {
last: Mutex<Option<String>>,
callback: Mutex<HandlerCallback>,
}
impl InnerContext {
fn take(&self) -> Option<String> {
self.last.lock().map(|mut last| last.take()).unwrap_or(None)
}
}
pub struct ContextHandle {
ptr: NonNull<GEOSContextHandle_HS>,
pub(crate) notice_ctx: NonNull<InnerContext>,
pub(crate) error_ctx: NonNull<InnerContext>,
}
impl ContextHandle {
/// Creates a new `ContextHandle`.
///
/// # Example
///
/// ```
/// use geos::ContextHandle;
///
/// let context_handle = ContextHandle::init()?;
/// # Ok::<(), geos::Error>(())
/// ```
pub fn init() -> GResult<Self> {
let ptr = unsafe { GEOS_init_r() };
let ptr = NonNull::new(ptr).ok_or(Error::GeosError(("GEOS_init_r", None)))?;
let error_ctx = unsafe {
NonNull::new_unchecked(Box::into_raw(Box::new(InnerContext {
last: Mutex::new(None),
callback: Mutex::new(Box::new(|_| {})),
})))
};
let notice_ctx = unsafe {
NonNull::new_unchecked(Box::into_raw(Box::new(InnerContext {
last: Mutex::new(None),
callback: Mutex::new(Box::new(|_| {})),
})))
};
unsafe {
GEOSContext_setNoticeMessageHandler_r(
ptr.as_ptr(),
Some(message_handler),
notice_ctx.as_ptr().cast(),
);
GEOSContext_setErrorMessageHandler_r(
ptr.as_ptr(),
Some(message_handler),
error_ctx.as_ptr().cast(),
);
}
Ok(Self {
ptr,
notice_ctx,
error_ctx,
})
}
pub(crate) const fn as_raw(&self) -> GEOSContextHandle_t {
self.ptr.as_ptr()
}
pub(crate) fn get_notice_context(&self) -> &InnerContext {
unsafe { self.notice_ctx.as_ref() }
}
pub(crate) fn get_error_context(&self) -> &InnerContext {
unsafe { self.error_ctx.as_ref() }
}
/// Allows to set a notice message handler.
///
/// Passing [`None`] as parameter will unset this callback.
///
/// # Example
///
/// ```
/// use geos::ContextHandle;
///
/// let context_handle = ContextHandle::init()?;
///
/// context_handle.set_notice_message_handler(Some(Box::new(|s| println!("new message: {}", s))));
/// # Ok::<(), geos::Error>(())
/// ```
pub fn set_notice_message_handler(&self, nf: Option<HandlerCallback>) {
if let Ok(mut callback) = self.get_notice_context().callback.lock() {
*callback = nf.unwrap_or_else(|| Box::new(|_| {}));
}
}
/// Allows to set an error message handler.
///
/// Passing [`None`] as parameter will unset this callback.
///
/// # Example
///
/// ```
/// use geos::ContextHandle;
///
/// let context_handle = ContextHandle::init()?;
///
/// context_handle.set_error_message_handler(Some(Box::new(|s| println!("new message: {}", s))));
/// # Ok::<(), geos::Error>(())
/// ```
pub fn set_error_message_handler(&self, ef: Option<HandlerCallback>) {
if let Ok(mut callback) = self.get_error_context().callback.lock() {
*callback = ef.unwrap_or_else(|| Box::new(|_| {}));
}
}
/// Returns the last error encountered.
///
/// Please note that calling this function will remove the current last error!
///
/// ```
/// use geos::ContextHandle;
///
/// let context_handle = ContextHandle::init()?;
/// // make some functions calls...
/// if let Some(last_error) = context_handle.get_last_error() {
/// println!("We have an error: {}", last_error);
/// } else {
/// println!("No error occurred!");
/// }
/// # Ok::<(), geos::Error>(())
/// ```
pub fn get_last_error(&self) -> Option<String> {
self.get_error_context().take()
}
/// Returns the last notification encountered.
///
/// Please note that calling this function will remove the current last notification!
///
/// ```
/// use geos::ContextHandle;
///
/// let context_handle = ContextHandle::init()?;
/// // make some functions calls...
/// if let Some(last_notif) = context_handle.get_last_notification() {
/// println!("We have a notification: {}", last_notif);
/// } else {
/// println!("No notifications!");
/// }
/// # Ok::<(), geos::Error>(())
/// ```
pub fn get_last_notification(&self) -> Option<String> {
self.get_notice_context().take()
}
/// Gets WKB output dimensions.
///
/// # Example
///
/// ```
/// use geos::{ContextHandle, CoordDimensions};
///
/// let mut context_handle = ContextHandle::init()?;
///
/// context_handle.set_wkb_output_dimensions(CoordDimensions::TwoD);
/// assert_eq!(
/// context_handle.get_wkb_output_dimensions()?,
/// CoordDimensions::TwoD
/// );
/// # Ok::<(), geos::Error>(())
/// ```
pub fn get_wkb_output_dimensions(&self) -> GResult<CoordDimensions> {
unsafe {
let out = errcheck!(-1, GEOS_getWKBOutputDims_r(self.as_raw()))?;
CoordDimensions::try_from(out)
}
}
/// Sets WKB output dimensions.
///
/// # Example
///
/// ```
/// use geos::{ContextHandle, CoordDimensions};
///
/// let mut context_handle = ContextHandle::init()?;
///
/// context_handle.set_wkb_output_dimensions(CoordDimensions::TwoD)?;
/// assert_eq!(
/// context_handle.get_wkb_output_dimensions()?,
/// CoordDimensions::TwoD
/// );
/// # Ok::<(), geos::Error>(())
/// ```
pub fn set_wkb_output_dimensions(
&mut self,
dimensions: CoordDimensions,
) -> GResult<CoordDimensions> {
unsafe {
let out = errcheck!(
-1,
GEOS_setWKBOutputDims_r(self.as_raw(), dimensions.into())
)?;
CoordDimensions::try_from(out)
}
}
/// Gets WKB byte order.
///
/// # Example
///
/// ```
/// use geos::{ByteOrder, ContextHandle};
///
/// let mut context_handle = ContextHandle::init()?;
///
/// context_handle.set_wkb_byte_order(ByteOrder::LittleEndian)?;
/// assert_eq!(
/// context_handle.get_wkb_byte_order()?,
/// ByteOrder::LittleEndian
/// );
/// # Ok::<(), geos::Error>(())
/// ```
pub fn get_wkb_byte_order(&self) -> GResult<ByteOrder> {
let out = unsafe { errcheck!(-1, GEOS_getWKBByteOrder_r(self.as_raw()))? };
ByteOrder::try_from(out)
}
/// Sets WKB byte order.
///
/// # Example
///
/// ```
/// use geos::{ByteOrder, ContextHandle};
///
/// let mut context_handle = ContextHandle::init()?;
///
/// context_handle.set_wkb_byte_order(ByteOrder::LittleEndian)?;
/// assert_eq!(
/// context_handle.get_wkb_byte_order()?,
/// ByteOrder::LittleEndian
/// );
/// # Ok::<(), geos::Error>(())
/// ```
pub fn set_wkb_byte_order(&mut self, byte_order: ByteOrder) -> GResult<ByteOrder> {
let out =
unsafe { errcheck!(-1, GEOS_setWKBByteOrder_r(self.as_raw(), byte_order.into()))? };
ByteOrder::try_from(out)
}
}
impl Drop for ContextHandle {
fn drop(&mut self) {
unsafe {
GEOS_finish_r(self.as_raw());
// Now we just have to clear stuff!
let _ = Box::from_raw(self.error_ctx.as_ptr());
let _ = Box::from_raw(self.notice_ctx.as_ptr());
}
}
}