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
use crate::context_handle::PtrWrap;
use crate::enums::CapStyle;
use crate::{
    AsRaw, AsRawMut, ContextHandle, ContextHandling, ContextInteractions, Error, GResult, JoinStyle,
};

use geos_sys::*;
use std::sync::Arc;

/// Contains the parameters which describe how a [Geometry](crate::Geometry) buffer should be constructed using [buffer_with_params](crate::Geom::buffer_with_params)
pub struct BufferParams<'a> {
    ptr: PtrWrap<*mut GEOSBufferParams>,
    context: Arc<ContextHandle<'a>>,
}

/// Build options for a [`BufferParams`] object
#[derive(Default)]
pub struct BufferParamsBuilder {
    end_cap_style: Option<CapStyle>,
    join_style: Option<JoinStyle>,
    mitre_limit: Option<f64>,
    quadrant_segments: Option<i32>,
    single_sided: Option<bool>,
}

impl<'a> BufferParams<'a> {
    pub fn new() -> GResult<BufferParams<'a>> {
        match ContextHandle::init_e(Some("BufferParams::new")) {
            Ok(context) => unsafe {
                let ptr = GEOSBufferParams_create_r(context.as_raw());
                Ok(BufferParams {
                    ptr: PtrWrap(ptr),
                    context: Arc::new(context),
                })
            },
            Err(e) => Err(e),
        }
    }

    pub fn builder() -> BufferParamsBuilder {
        BufferParamsBuilder::default()
    }

    /// Specifies the end cap style of the generated buffer.
    pub fn set_end_cap_style(&mut self, style: CapStyle) -> GResult<()> {
        unsafe {
            let ret = GEOSBufferParams_setEndCapStyle_r(
                self.get_raw_context(),
                self.as_raw_mut_override(),
                style.into(),
            );
            if ret == 0 {
                Err(Error::GeosError("GEOSBufferParams_setEndCapStyle_r".into()))
            } else {
                Ok(())
            }
        }
    }

    /// Sets the join style for outside (reflex) corners between line segments.
    pub fn set_join_style(&mut self, style: JoinStyle) -> GResult<()> {
        unsafe {
            let ret = GEOSBufferParams_setJoinStyle_r(
                self.get_raw_context(),
                self.as_raw_mut_override(),
                style.into(),
            );
            if ret == 0 {
                Err(Error::GeosError("GEOSBufferParams_setJoinStyle_r".into()))
            } else {
                Ok(())
            }
        }
    }

    /// Sets the limit on the mitre ratio used for very sharp corners.
    ///
    /// The mitre ratio is the ratio of the distance from the corner
    /// to the end of the mitred offset corner.
    /// When two line segments meet at a sharp angle,
    /// a miter join will extend far beyond the original geometry.
    /// (and in the extreme case will be infinitely far.)
    /// To prevent unreasonable geometry, the mitre limit
    /// allows controlling the maximum length of the join corner.
    /// Corners with a ratio which exceed the limit will be beveled.
    pub fn set_mitre_limit(&mut self, limit: f64) -> GResult<()> {
        unsafe {
            let ret = GEOSBufferParams_setMitreLimit_r(
                self.get_raw_context(),
                self.as_raw_mut_override(),
                limit,
            );
            if ret == 0 {
                Err(Error::GeosError("GEOSBufferParams_setMitreLimit_r".into()))
            } else {
                Ok(())
            }
        }
    }

    /// Sets the number of line segments used to approximate
    /// an angle fillet.
    ///
    /// - If `quadsegs` >= 1, joins are round, and `quadsegs` indicates the number of
    ///   segments to use to approximate a quarter-circle.
    /// - If `quadsegs` = 0, joins are bevelled (flat)
    /// - If `quadSegs` < 0, joins are mitred, and the value of qs
    ///   indicates the mitre ration limit as `mitreLimit = |quadsegs|`
    ///
    /// For round joins, `quadsegs` determines the maximum
    /// error in the approximation to the true buffer curve.
    ///
    /// The default value of 8 gives less than 2% max error in the
    /// buffer distance.
    ///
    /// For a max error of < 1%, use QS = 12.
    /// For a max error of < 0.1%, use QS = 18.
    /// The error is always less than the buffer distance
    /// (in other words, the computed buffer curve is always inside
    ///  the true curve).
    pub fn set_quadrant_segments(&mut self, quadsegs: i32) -> GResult<()> {
        unsafe {
            let ret = GEOSBufferParams_setQuadrantSegments_r(
                self.get_raw_context(),
                self.as_raw_mut_override(),
                quadsegs as _,
            );
            if ret == 0 {
                Err(Error::GeosError(
                    "GEOSBufferParams_setQuadrantSegments_r".into(),
                ))
            } else {
                Ok(())
            }
        }
    }

    /// Sets whether the computed buffer should be single-sided.
    ///
    /// A single-sided buffer is constructed on only one side of each input line.
    ///
    /// The side used is determined by the sign of the buffer distance:
    /// - a positive distance indicates the left-hand side
    /// - a negative distance indicates the right-hand side
    ///
    /// The single-sided buffer of point geometries is the same as the regular buffer.
    ///
    /// The End Cap Style for single-sided buffers is always ignored, and forced to the
    /// equivalent of [`CapStyle::Flat`].
    pub fn set_single_sided(&mut self, is_single_sided: bool) -> GResult<()> {
        unsafe {
            let single_sided = if is_single_sided { 1 } else { 0 };
            let ret = GEOSBufferParams_setSingleSided_r(
                self.get_raw_context(),
                self.as_raw_mut_override(),
                single_sided,
            );
            if ret == 0 {
                Err(Error::GeosError("GEOSBufferParams_setSingleSided_r".into()))
            } else {
                Ok(())
            }
        }
    }
}

unsafe impl<'a> Send for BufferParams<'a> {}
unsafe impl<'a> Sync for BufferParams<'a> {}

impl<'a> Drop for BufferParams<'a> {
    fn drop(&mut self) {
        if !self.ptr.is_null() {
            unsafe { GEOSBufferParams_destroy_r(self.get_raw_context(), self.as_raw_mut()) };
        }
    }
}

impl<'a> AsRaw for BufferParams<'a> {
    type RawType = GEOSBufferParams;

    fn as_raw(&self) -> *const Self::RawType {
        *self.ptr
    }
}

impl<'a> AsRawMut for BufferParams<'a> {
    type RawType = GEOSBufferParams;

    unsafe fn as_raw_mut_override(&self) -> *mut Self::RawType {
        *self.ptr
    }
}

impl<'a> ContextInteractions<'a> for BufferParams<'a> {
    fn set_context_handle(&mut self, context: ContextHandle<'a>) {
        self.context = Arc::new(context);
    }

    fn get_context_handle(&self) -> &ContextHandle<'a> {
        &self.context
    }
}

impl<'a> ContextHandling for BufferParams<'a> {
    type Context = Arc<ContextHandle<'a>>;

    fn get_raw_context(&self) -> GEOSContextHandle_t {
        self.context.as_raw()
    }

    fn clone_context(&self) -> Arc<ContextHandle<'a>> {
        Arc::clone(&self.context)
    }
}

impl BufferParamsBuilder {
    pub fn end_cap_style(mut self, style: CapStyle) -> BufferParamsBuilder {
        self.end_cap_style = Some(style);
        self
    }
    pub fn join_style(mut self, style: JoinStyle) -> BufferParamsBuilder {
        self.join_style = Some(style);
        self
    }
    pub fn mitre_limit(mut self, limit: f64) -> BufferParamsBuilder {
        self.mitre_limit = Some(limit);
        self
    }
    pub fn quadrant_segments(mut self, quadsegs: i32) -> BufferParamsBuilder {
        self.quadrant_segments = Some(quadsegs);
        self
    }
    pub fn single_sided(mut self, is_single_sided: bool) -> BufferParamsBuilder {
        self.single_sided = Some(is_single_sided);
        self
    }
    pub fn build(self) -> GResult<BufferParams<'static>> {
        let mut params = BufferParams::new()?;
        if let Some(style) = self.end_cap_style {
            params.set_end_cap_style(style)?;
        }
        if let Some(style) = self.join_style {
            params.set_join_style(style)?;
        }
        if let Some(limit) = self.mitre_limit {
            params.set_mitre_limit(limit)?;
        }
        if let Some(quad_segs) = self.quadrant_segments {
            params.set_quadrant_segments(quad_segs)?;
        }
        if let Some(is_single_sided) = self.single_sided {
            params.set_single_sided(is_single_sided)?;
        }
        Ok(params)
    }
}