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
use crate::enums::{ByteOrder, OutputDimension};
use crate::error::{Error, GResult};
use geos_sys::*;
use libc::{c_char, c_void, strlen};
use std::convert::TryFrom;
use std::ffi::CStr;
use std::ops::Deref;
use std::slice;
use std::sync::Mutex;

macro_rules! set_callbacks {
    ($c_func:ident, $kind:ident, $callback_name:ident, $last:ident) => {
        fn $kind<'a>(ptr: GEOSContextHandle_t, nf: *mut InnerContext<'a>) {
            unsafe extern "C" fn message_handler_func<'a>(
                message: *const c_char,
                data: *mut c_void,
            ) {
                let inner_context: &InnerContext<'a> = &*(data as *mut _);

                if let Ok(callback) = inner_context.$callback_name.lock() {
                    let bytes = slice::from_raw_parts(message as *const u8, strlen(message));
                    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());
                    }
                }
            }

            unsafe {
                $c_func(ptr, Some(message_handler_func), nf as *mut _);
            }
        }
    };
}

set_callbacks!(
    GEOSContext_setNoticeMessageHandler_r,
    set_notif,
    notif_callback,
    last_notification
);
set_callbacks!(
    GEOSContext_setErrorMessageHandler_r,
    set_error,
    error_callback,
    last_error
);

pub(crate) struct PtrWrap<T>(pub T);

impl<T> Deref for PtrWrap<T> {
    type Target = T;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

unsafe impl<T> Send for PtrWrap<T> {}
unsafe impl<T> Sync for PtrWrap<T> {}

pub(crate) struct InnerContext<'a> {
    last_notification: Mutex<Option<String>>,
    last_error: Mutex<Option<String>>,
    notif_callback: Mutex<Box<dyn Fn(&str) + Send + Sync + 'a>>,
    error_callback: Mutex<Box<dyn Fn(&str) + Send + Sync + 'a>>,
}

pub struct ContextHandle<'a> {
    ptr: PtrWrap<GEOSContextHandle_t>,
    pub(crate) inner: PtrWrap<*mut InnerContext<'a>>,
}

impl<'a> ContextHandle<'a> {
    /// Creates a new `ContextHandle`.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::ContextHandle;
    ///
    /// let context_handle = ContextHandle::init().expect("invalid init");
    /// ```
    pub fn init() -> GResult<Self> {
        Self::init_e(None)
    }

    pub(crate) fn init_e(caller: Option<&str>) -> GResult<Self> {
        let ptr = unsafe { GEOS_init_r() };
        if ptr.is_null() {
            return if let Some(ref caller) = caller {
                Err(Error::GenericError(format!(
                    "GEOS_init_r failed from \"{}\"",
                    caller
                )))
            } else {
                Err(Error::GenericError("GEOS_init_r failed".to_owned()))
            };
        }
        let last_notification = Mutex::new(None);
        let last_error = Mutex::new(None);

        let notif_callback: Mutex<Box<dyn Fn(&str) + Send + Sync + 'a>> =
            Mutex::new(Box::new(|_| {}));
        let error_callback: Mutex<Box<dyn Fn(&str) + Send + Sync + 'a>> =
            Mutex::new(Box::new(|_| {}));

        let inner = Box::into_raw(Box::new(InnerContext {
            last_notification,
            last_error,
            notif_callback,
            error_callback,
        }));

        set_notif(ptr, inner);
        set_error(ptr, inner);

        Ok(ContextHandle {
            ptr: PtrWrap(ptr),
            inner: PtrWrap(inner),
        })
    }

    pub(crate) fn as_raw(&self) -> GEOSContextHandle_t {
        *self.ptr
    }

    pub(crate) fn get_inner(&self) -> &InnerContext<'a> {
        unsafe { &*self.inner.0 }
    }

    /// Allows to set a notice message handler.
    ///
    /// Passing [`None`] as parameter will unset this callback.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::ContextHandle;
    ///
    /// let context_handle = ContextHandle::init().expect("invalid init");
    ///
    /// context_handle.set_notice_message_handler(Some(Box::new(|s| println!("new message: {}", s))));
    /// ```
    pub fn set_notice_message_handler(&self, nf: Option<Box<dyn Fn(&str) + Send + Sync + 'a>>) {
        let inner_context = self.get_inner();
        if let Ok(mut callback) = inner_context.notif_callback.lock() {
            if let Some(nf) = nf {
                *callback = nf;
            } else {
                *callback = 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().expect("invalid init");
    ///
    /// context_handle.set_error_message_handler(Some(Box::new(|s| println!("new message: {}", s))));
    /// ```
    pub fn set_error_message_handler(&self, ef: Option<Box<dyn Fn(&str) + Send + Sync + 'a>>) {
        let inner_context = self.get_inner();
        if let Ok(mut callback) = inner_context.error_callback.lock() {
            if let Some(ef) = ef {
                *callback = ef;
            } else {
                *callback = 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().expect("invalid 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!");
    /// }
    /// ```
    pub fn get_last_error(&self) -> Option<String> {
        let inner_context = self.get_inner();
        if let Ok(mut last) = inner_context.last_error.lock() {
            last.take()
        } else {
            None
        }
    }

    /// 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().expect("invalid 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!");
    /// }
    /// ```
    pub fn get_last_notification(&self) -> Option<String> {
        let inner_context = self.get_inner();
        if let Ok(mut last) = inner_context.last_notification.lock() {
            last.take()
        } else {
            None
        }
    }

    /// Gets WKB output dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::{ContextHandle, OutputDimension};
    ///
    /// let mut context_handle = ContextHandle::init().expect("invalid init");
    ///
    /// context_handle.set_wkb_output_dimensions(OutputDimension::TwoD);
    /// assert_eq!(context_handle.get_wkb_output_dimensions(), Ok(OutputDimension::TwoD));
    /// ```
    pub fn get_wkb_output_dimensions(&self) -> GResult<OutputDimension> {
        unsafe {
            let out = GEOS_getWKBOutputDims_r(self.as_raw());
            OutputDimension::try_from(out).map_err(|e| Error::GenericError(e.to_owned()))
        }
    }

    /// Sets WKB output dimensions.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::{ContextHandle, OutputDimension};
    ///
    /// let mut context_handle = ContextHandle::init().expect("invalid init");
    ///
    /// context_handle.set_wkb_output_dimensions(OutputDimension::TwoD);
    /// assert_eq!(context_handle.get_wkb_output_dimensions(), Ok(OutputDimension::TwoD));
    /// ```
    pub fn set_wkb_output_dimensions(
        &mut self,
        dimensions: OutputDimension,
    ) -> GResult<OutputDimension> {
        unsafe {
            let out = GEOS_setWKBOutputDims_r(self.as_raw(), dimensions.into());
            OutputDimension::try_from(out).map_err(|e| Error::GenericError(e.to_owned()))
        }
    }

    /// Gets WKB byte order.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::{ContextHandle, ByteOrder};
    ///
    /// let mut context_handle = ContextHandle::init().expect("invalid init");
    ///
    /// context_handle.set_wkb_byte_order(ByteOrder::LittleEndian);
    /// assert!(context_handle.get_wkb_byte_order() == ByteOrder::LittleEndian);
    /// ```
    pub fn get_wkb_byte_order(&self) -> ByteOrder {
        ByteOrder::try_from(unsafe { GEOS_getWKBByteOrder_r(self.as_raw()) })
            .expect("failed to convert to ByteOrder")
    }

    /// Sets WKB byte order.
    ///
    /// # Example
    ///
    /// ```
    /// use geos::{ContextHandle, ByteOrder};
    ///
    /// let mut context_handle = ContextHandle::init().expect("invalid init");
    ///
    /// context_handle.set_wkb_byte_order(ByteOrder::LittleEndian);
    /// assert!(context_handle.get_wkb_byte_order() == ByteOrder::LittleEndian);
    /// ```
    pub fn set_wkb_byte_order(&mut self, byte_order: ByteOrder) -> ByteOrder {
        ByteOrder::try_from(unsafe { GEOS_setWKBByteOrder_r(self.as_raw(), byte_order.into()) })
            .expect("failed to convert to ByteOrder")
    }
}

impl<'a> Drop for ContextHandle<'a> {
    fn drop(&mut self) {
        unsafe {
            if !self.ptr.is_null() {
                GEOS_finish_r(self.as_raw());
            }
            // Now we just have to clear stuff!
            let _inner: Box<InnerContext<'a>> = Box::from_raw(self.inner.0);
        }
    }
}