use crate::context_handle::with_context;
use crate::enums::{ByteOrder, CoordDimensions};
use crate::functions::{errcheck, managed_vec, nullcheck, predicate};
use crate::traits::as_raw_mut_impl;
use crate::{AsRaw, AsRawMut, GResult, Geom};
use geos_sys::*;
use std::convert::TryFrom;
use std::ptr::NonNull;
pub struct WKBWriter {
ptr: NonNull<GEOSWKBWriter>,
}
impl WKBWriter {
#[cfg(not(feature = "tests"))]
pub fn new() -> GResult<Self> {
with_context(|ctx| unsafe {
let ptr = nullcheck!(GEOSWKBWriter_create_r(ctx.as_raw()))?;
Ok(Self { ptr })
})
}
#[cfg(feature = "tests")]
pub fn new() -> GResult<WKBWriter> {
with_context(|ctx| unsafe {
let ptr = nullcheck!(GEOSWKBWriter_create_r(ctx.as_raw()))?;
#[cfg(not(feature = "v3_12_0"))]
GEOSWKBWriter_setOutputDimension_r(ctx.as_raw(), ptr.as_ptr(), 3);
#[cfg(feature = "v3_12_0")]
GEOSWKBWriter_setOutputDimension_r(ctx.as_raw(), ptr.as_ptr(), 4);
Ok(WKBWriter { ptr })
})
}
pub fn write_wkb<G: Geom>(&mut self, geometry: &G) -> GResult<Vec<u8>> {
let mut size = 0;
with_context(|ctx| unsafe {
let ptr = nullcheck!(GEOSWKBWriter_write_r(
ctx.as_raw(),
self.as_raw_mut(),
geometry.as_raw(),
&mut size,
))?;
Ok(managed_vec(ptr, size, ctx))
})
}
pub fn write_hex<G: Geom>(&mut self, geometry: &G) -> GResult<Vec<u8>> {
let mut size = 0;
with_context(|ctx| unsafe {
let ptr = nullcheck!(GEOSWKBWriter_writeHEX_r(
ctx.as_raw(),
self.as_raw_mut(),
geometry.as_raw(),
&mut size,
))?;
Ok(managed_vec(ptr, size, ctx))
})
}
pub fn set_output_dimension(&mut self, dimension: CoordDimensions) {
with_context(|ctx| unsafe {
GEOSWKBWriter_setOutputDimension_r(ctx.as_raw(), self.as_raw_mut(), dimension.into());
});
}
pub fn get_out_dimension(&self) -> GResult<CoordDimensions> {
with_context(|ctx| unsafe {
let out = GEOSWKBWriter_getOutputDimension_r(ctx.as_raw(), self.as_raw());
CoordDimensions::try_from(out)
})
}
pub fn get_wkb_byte_order(&self) -> GResult<ByteOrder> {
with_context(|ctx| unsafe {
let out = GEOSWKBWriter_getByteOrder_r(ctx.as_raw(), self.as_raw());
ByteOrder::try_from(out)
})
}
pub fn set_wkb_byte_order(&mut self, byte_order: ByteOrder) {
with_context(|ctx| unsafe {
GEOSWKBWriter_setByteOrder_r(ctx.as_raw(), self.as_raw_mut(), byte_order.into());
});
}
#[allow(non_snake_case)]
pub fn get_include_SRID(&self) -> GResult<bool> {
with_context(|ctx| unsafe {
predicate!(GEOSWKBWriter_getIncludeSRID_r(ctx.as_raw(), self.as_raw()))
})
}
#[allow(non_snake_case)]
pub fn set_include_SRID(&mut self, include_SRID: bool) {
with_context(|ctx| unsafe {
GEOSWKBWriter_setIncludeSRID_r(ctx.as_raw(), self.as_raw_mut(), include_SRID.into());
});
}
}
unsafe impl Send for WKBWriter {}
unsafe impl Sync for WKBWriter {}
impl Drop for WKBWriter {
fn drop(&mut self) {
with_context(|ctx| unsafe { GEOSWKBWriter_destroy_r(ctx.as_raw(), self.as_raw_mut()) });
}
}
as_raw_mut_impl!(WKBWriter, GEOSWKBWriter);