geoarrow_array/array/
wkt.rs

1use std::str::FromStr;
2use std::sync::Arc;
3
4use arrow_array::builder::GenericStringBuilder;
5use arrow_array::cast::AsArray;
6use arrow_array::{
7    Array, ArrayRef, GenericStringArray, LargeStringArray, OffsetSizeTrait, StringArray,
8};
9use arrow_buffer::NullBuffer;
10use arrow_schema::{DataType, Field};
11use geoarrow_schema::error::{GeoArrowError, GeoArrowResult};
12use geoarrow_schema::{GeoArrowType, Metadata, WktType};
13use wkt::Wkt;
14
15use crate::GeoArrowArrayAccessor;
16use crate::array::WktViewArray;
17use crate::trait_::{GeoArrowArray, IntoArrow};
18use crate::util::{offsets_buffer_i32_to_i64, offsets_buffer_i64_to_i32};
19
20/// An immutable array of WKT geometries using GeoArrow's in-memory representation.
21///
22/// This is a wrapper around an Arrow [GenericStringArray] and is semantically equivalent to
23/// `Vec<Option<WKT>>` due to the internal validity bitmap.
24///
25/// Refer to [`crate::cast`] for converting this array to other GeoArrow array types.
26#[derive(Debug, Clone, PartialEq)]
27pub struct GenericWktArray<O: OffsetSizeTrait> {
28    pub(crate) data_type: WktType,
29    pub(crate) array: GenericStringArray<O>,
30}
31
32// Implement geometry accessors
33impl<O: OffsetSizeTrait> GenericWktArray<O> {
34    /// Create a new GenericWktArray from a StringArray
35    pub fn new(array: GenericStringArray<O>, metadata: Arc<Metadata>) -> Self {
36        Self {
37            data_type: WktType::new(metadata),
38            array,
39        }
40    }
41
42    /// Returns true if the array is empty
43    pub fn is_empty(&self) -> bool {
44        self.len() == 0
45    }
46
47    /// Access the underlying string array.
48    pub fn inner(&self) -> &GenericStringArray<O> {
49        &self.array
50    }
51
52    /// Slice this [`GenericWktArray`].
53    ///
54    /// # Panic
55    /// This function panics iff `offset + length > self.len()`.
56    #[inline]
57    pub fn slice(&self, offset: usize, length: usize) -> Self {
58        assert!(
59            offset + length <= self.len(),
60            "offset + length may not exceed length of array"
61        );
62        Self {
63            array: self.array.slice(offset, length),
64            data_type: self.data_type.clone(),
65        }
66    }
67
68    /// Replace the [`Metadata`] contained in this array.
69    pub fn with_metadata(&self, metadata: Arc<Metadata>) -> Self {
70        let mut arr = self.clone();
71        arr.data_type = self.data_type.clone().with_metadata(metadata);
72        arr
73    }
74}
75
76impl<O: OffsetSizeTrait> GeoArrowArray for GenericWktArray<O> {
77    fn as_any(&self) -> &dyn std::any::Any {
78        self
79    }
80
81    fn into_array_ref(self) -> ArrayRef {
82        Arc::new(self.into_arrow())
83    }
84
85    fn to_array_ref(&self) -> ArrayRef {
86        self.clone().into_array_ref()
87    }
88
89    #[inline]
90    fn len(&self) -> usize {
91        self.array.len()
92    }
93
94    #[inline]
95    fn logical_nulls(&self) -> Option<NullBuffer> {
96        self.array.logical_nulls()
97    }
98
99    #[inline]
100    fn logical_null_count(&self) -> usize {
101        self.array.logical_null_count()
102    }
103
104    #[inline]
105    fn is_null(&self, i: usize) -> bool {
106        self.array.is_null(i)
107    }
108
109    fn data_type(&self) -> GeoArrowType {
110        if O::IS_LARGE {
111            GeoArrowType::LargeWkt(self.data_type.clone())
112        } else {
113            GeoArrowType::Wkt(self.data_type.clone())
114        }
115    }
116
117    fn slice(&self, offset: usize, length: usize) -> Arc<dyn GeoArrowArray> {
118        Arc::new(self.slice(offset, length))
119    }
120
121    fn with_metadata(self, metadata: Arc<Metadata>) -> Arc<dyn GeoArrowArray> {
122        Arc::new(Self::with_metadata(&self, metadata))
123    }
124}
125
126impl<'a, O: OffsetSizeTrait> GeoArrowArrayAccessor<'a> for GenericWktArray<O> {
127    type Item = Wkt<f64>;
128
129    unsafe fn value_unchecked(&'a self, index: usize) -> GeoArrowResult<Self::Item> {
130        let s = unsafe { self.array.value_unchecked(index) };
131        Wkt::from_str(s).map_err(|err| GeoArrowError::Wkt(err.to_string()))
132    }
133}
134
135impl<O: OffsetSizeTrait> IntoArrow for GenericWktArray<O> {
136    type ArrowArray = GenericStringArray<O>;
137    type ExtensionType = WktType;
138
139    fn into_arrow(self) -> Self::ArrowArray {
140        GenericStringArray::new(
141            self.array.offsets().clone(),
142            self.array.values().clone(),
143            self.array.nulls().cloned(),
144        )
145    }
146
147    fn extension_type(&self) -> &Self::ExtensionType {
148        &self.data_type
149    }
150}
151
152impl<O: OffsetSizeTrait> From<(GenericStringArray<O>, WktType)> for GenericWktArray<O> {
153    fn from((value, typ): (GenericStringArray<O>, WktType)) -> Self {
154        Self::new(value, typ.metadata().clone())
155    }
156}
157
158impl TryFrom<(&dyn Array, WktType)> for GenericWktArray<i32> {
159    type Error = GeoArrowError;
160
161    fn try_from((value, typ): (&dyn Array, WktType)) -> GeoArrowResult<Self> {
162        match value.data_type() {
163            DataType::Utf8 => Ok((value.as_string::<i32>().clone(), typ).into()),
164            DataType::LargeUtf8 => {
165                let geom_array: GenericWktArray<i64> =
166                    (value.as_string::<i64>().clone(), typ).into();
167                geom_array.try_into()
168            }
169            dt => Err(GeoArrowError::InvalidGeoArrow(format!(
170                "Unexpected WktArray DataType: {dt:?}",
171            ))),
172        }
173    }
174}
175
176impl TryFrom<(&dyn Array, WktType)> for GenericWktArray<i64> {
177    type Error = GeoArrowError;
178
179    fn try_from((value, typ): (&dyn Array, WktType)) -> GeoArrowResult<Self> {
180        match value.data_type() {
181            DataType::Utf8 => {
182                let geom_array: GenericWktArray<i32> =
183                    (value.as_string::<i32>().clone(), typ).into();
184                Ok(geom_array.into())
185            }
186            DataType::LargeUtf8 => Ok((value.as_string::<i64>().clone(), typ).into()),
187            dt => Err(GeoArrowError::InvalidGeoArrow(format!(
188                "Unexpected WktArray DataType: {dt:?}",
189            ))),
190        }
191    }
192}
193
194impl TryFrom<(&dyn Array, &Field)> for GenericWktArray<i32> {
195    type Error = GeoArrowError;
196
197    fn try_from((arr, field): (&dyn Array, &Field)) -> GeoArrowResult<Self> {
198        let typ = field
199            .try_extension_type::<WktType>()
200            .ok()
201            .unwrap_or_default();
202        (arr, typ).try_into()
203    }
204}
205
206impl TryFrom<(&dyn Array, &Field)> for GenericWktArray<i64> {
207    type Error = GeoArrowError;
208
209    fn try_from((arr, field): (&dyn Array, &Field)) -> GeoArrowResult<Self> {
210        let typ = field
211            .try_extension_type::<WktType>()
212            .ok()
213            .unwrap_or_default();
214        (arr, typ).try_into()
215    }
216}
217
218impl From<GenericWktArray<i32>> for GenericWktArray<i64> {
219    fn from(value: GenericWktArray<i32>) -> Self {
220        let binary_array = value.array;
221        let (offsets, values, nulls) = binary_array.into_parts();
222        Self {
223            data_type: value.data_type,
224            array: LargeStringArray::new(offsets_buffer_i32_to_i64(&offsets), values, nulls),
225        }
226    }
227}
228
229impl TryFrom<GenericWktArray<i64>> for GenericWktArray<i32> {
230    type Error = GeoArrowError;
231
232    fn try_from(value: GenericWktArray<i64>) -> GeoArrowResult<Self> {
233        let binary_array = value.array;
234        let (offsets, values, nulls) = binary_array.into_parts();
235        Ok(Self {
236            data_type: value.data_type,
237            array: StringArray::new(offsets_buffer_i64_to_i32(&offsets)?, values, nulls),
238        })
239    }
240}
241
242impl<O: OffsetSizeTrait> From<WktViewArray> for GenericWktArray<O> {
243    fn from(value: WktViewArray) -> Self {
244        let wkb_type = value.data_type;
245        let binary_view_array = value.array;
246
247        // Copy the bytes from the binary view array into a new byte array
248        let mut builder = GenericStringBuilder::new();
249        binary_view_array
250            .iter()
251            .for_each(|value| builder.append_option(value));
252
253        Self {
254            data_type: wkb_type,
255            array: builder.finish(),
256        }
257    }
258}
259
260/// A [`GenericWktArray`] using `i32` offsets
261///
262/// The byte length of each element is represented by an i32.
263///
264/// See [`GenericWktArray`] for more information and examples
265pub type WktArray = GenericWktArray<i32>;
266
267/// A [`GenericWktArray`] using `i64` offsets
268///
269/// The byte length of each element is represented by an i64.
270///
271/// See [`GenericWktArray`] for more information and examples
272pub type LargeWktArray = GenericWktArray<i64>;
273
274#[cfg(test)]
275mod test {
276    use arrow_array::builder::{LargeStringBuilder, StringBuilder};
277    use geoarrow_schema::{CoordType, Dimension};
278
279    use super::*;
280    use crate::GeoArrowArray;
281    use crate::cast::to_wkt;
282    use crate::test::point;
283
284    fn wkt_data<O: OffsetSizeTrait>() -> GenericWktArray<O> {
285        to_wkt(&point::array(CoordType::Interleaved, Dimension::XY)).unwrap()
286    }
287
288    #[test]
289    fn parse_dyn_array_i32() {
290        let wkb_array = wkt_data::<i32>();
291        let array = wkb_array.to_array_ref();
292        let field = Field::new("geometry", array.data_type().clone(), true)
293            .with_extension_type(wkb_array.data_type.clone());
294        let wkb_array_retour: GenericWktArray<i32> = (array.as_ref(), &field).try_into().unwrap();
295
296        assert_eq!(wkb_array, wkb_array_retour);
297    }
298
299    #[test]
300    fn parse_dyn_array_i64() {
301        let wkb_array = wkt_data::<i64>();
302        let array = wkb_array.to_array_ref();
303        let field = Field::new("geometry", array.data_type().clone(), true)
304            .with_extension_type(wkb_array.data_type.clone());
305        let wkb_array_retour: GenericWktArray<i64> = (array.as_ref(), &field).try_into().unwrap();
306
307        assert_eq!(wkb_array, wkb_array_retour);
308    }
309
310    #[test]
311    fn convert_i32_to_i64() {
312        let wkb_array = wkt_data::<i32>();
313        let wkb_array_i64: GenericWktArray<i64> = wkb_array.clone().into();
314        let wkb_array_i32: GenericWktArray<i32> = wkb_array_i64.clone().try_into().unwrap();
315
316        assert_eq!(wkb_array, wkb_array_i32);
317    }
318
319    #[test]
320    fn convert_i64_to_i32_to_i64() {
321        let wkb_array = wkt_data::<i64>();
322        let wkb_array_i32: GenericWktArray<i32> = wkb_array.clone().try_into().unwrap();
323        let wkb_array_i64: GenericWktArray<i64> = wkb_array_i32.clone().into();
324
325        assert_eq!(wkb_array, wkb_array_i64);
326    }
327
328    /// Passing a field without an extension name should not panic
329    #[test]
330    fn allow_field_without_extension_name() {
331        // String array
332        let mut builder = StringBuilder::new();
333        builder.append_value("POINT(1 2)");
334        let array = Arc::new(builder.finish()) as ArrayRef;
335        let field = Field::new("geometry", array.data_type().clone(), true);
336        let _wkt_arr = GenericWktArray::<i32>::try_from((array.as_ref(), &field)).unwrap();
337
338        // Large string
339        let mut builder = LargeStringBuilder::new();
340        builder.append_value("POINT(1 2)");
341        let array = Arc::new(builder.finish()) as ArrayRef;
342        let field = Field::new("geometry", array.data_type().clone(), true);
343        let _wkt_arr = GenericWktArray::<i64>::try_from((array.as_ref(), &field)).unwrap();
344    }
345}