chore: run cargo fmt on everything

This commit is contained in:
Nathan Fiedler
2024-05-25 10:50:27 -07:00
parent 320cfb6e62
commit aedcfcd8f7
42 changed files with 637 additions and 777 deletions

View File

@ -37,13 +37,13 @@ use libc::size_t;
pub use conversions::ToMagick;
pub use result::MagickError;
use result::Result;
pub use wand::*;
pub use types::*;
pub use wand::*;
mod conversions;
mod result;
mod wand;
mod types;
mod wand;
include!(concat!(env!("OUT_DIR"), "/bindings.rs"));
/// This function must be called before any other ImageMagick operations
@ -73,7 +73,9 @@ pub fn magick_query_fonts(pattern: &str) -> Result<Vec<String>> {
let ptr =
unsafe { bindings::MagickQueryFonts(c_string.as_ptr(), &mut number_fonts as *mut size_t) };
if ptr.is_null() {
Err(MagickError("null ptr returned by magick_query_fonts".to_string()))
Err(MagickError(
"null ptr returned by magick_query_fonts".to_string(),
))
} else {
let mut v = Vec::new();
let c_str_ptr_slice = unsafe { ::std::slice::from_raw_parts(ptr, number_fonts as usize) };

View File

@ -39,32 +39,32 @@ impl Default for ChannelType {
impl From<ChannelType> for bindings::ChannelType {
fn from(value: ChannelType) -> Self {
match value {
ChannelType::Undefined => { bindings::ChannelType_UndefinedChannel },
ChannelType::RedChannel => { bindings::ChannelType_RedChannel },
ChannelType::GrayChannel => { bindings::ChannelType_GrayChannel },
ChannelType::CyanChannel => { bindings::ChannelType_CyanChannel },
ChannelType::LChannel => { bindings::ChannelType_LChannel },
ChannelType::GreenChannel => { bindings::ChannelType_GreenChannel },
ChannelType::MagentaChannel => { bindings::ChannelType_MagentaChannel },
ChannelType::aChannel => { bindings::ChannelType_aChannel },
ChannelType::BlueChannel => { bindings::ChannelType_BlueChannel },
ChannelType::bChannel => { bindings::ChannelType_bChannel },
ChannelType::YellowChannel => { bindings::ChannelType_YellowChannel },
ChannelType::BlackChannel => { bindings::ChannelType_BlackChannel },
ChannelType::AlphaChannel => { bindings::ChannelType_AlphaChannel },
ChannelType::OpacityChannel => { bindings::ChannelType_OpacityChannel },
ChannelType::IndexChannel => { bindings::ChannelType_IndexChannel },
ChannelType::ReadMaskChannel => { bindings::ChannelType_ReadMaskChannel },
ChannelType::WriteMaskChannel => { bindings::ChannelType_WriteMaskChannel },
ChannelType::MetaChannel => { bindings::ChannelType_MetaChannel },
ChannelType::CompositeMaskChannel => { bindings::ChannelType_CompositeMaskChannel },
ChannelType::CompositeChannels => { bindings::ChannelType_CompositeChannels },
ChannelType::AllChannels => { bindings::ChannelType_AllChannels },
ChannelType::TrueAlphaChannel => { bindings::ChannelType_TrueAlphaChannel },
ChannelType::RGBChannels => { bindings::ChannelType_RGBChannels },
ChannelType::GrayChannels => { bindings::ChannelType_GrayChannels },
ChannelType::SyncChannels => { bindings::ChannelType_SyncChannels },
ChannelType::DefaultChannels => { bindings::ChannelType_DefaultChannels },
ChannelType::Undefined => bindings::ChannelType_UndefinedChannel,
ChannelType::RedChannel => bindings::ChannelType_RedChannel,
ChannelType::GrayChannel => bindings::ChannelType_GrayChannel,
ChannelType::CyanChannel => bindings::ChannelType_CyanChannel,
ChannelType::LChannel => bindings::ChannelType_LChannel,
ChannelType::GreenChannel => bindings::ChannelType_GreenChannel,
ChannelType::MagentaChannel => bindings::ChannelType_MagentaChannel,
ChannelType::aChannel => bindings::ChannelType_aChannel,
ChannelType::BlueChannel => bindings::ChannelType_BlueChannel,
ChannelType::bChannel => bindings::ChannelType_bChannel,
ChannelType::YellowChannel => bindings::ChannelType_YellowChannel,
ChannelType::BlackChannel => bindings::ChannelType_BlackChannel,
ChannelType::AlphaChannel => bindings::ChannelType_AlphaChannel,
ChannelType::OpacityChannel => bindings::ChannelType_OpacityChannel,
ChannelType::IndexChannel => bindings::ChannelType_IndexChannel,
ChannelType::ReadMaskChannel => bindings::ChannelType_ReadMaskChannel,
ChannelType::WriteMaskChannel => bindings::ChannelType_WriteMaskChannel,
ChannelType::MetaChannel => bindings::ChannelType_MetaChannel,
ChannelType::CompositeMaskChannel => bindings::ChannelType_CompositeMaskChannel,
ChannelType::CompositeChannels => bindings::ChannelType_CompositeChannels,
ChannelType::AllChannels => bindings::ChannelType_AllChannels,
ChannelType::TrueAlphaChannel => bindings::ChannelType_TrueAlphaChannel,
ChannelType::RGBChannels => bindings::ChannelType_RGBChannels,
ChannelType::GrayChannels => bindings::ChannelType_GrayChannels,
ChannelType::SyncChannels => bindings::ChannelType_SyncChannels,
ChannelType::DefaultChannels => bindings::ChannelType_DefaultChannels,
}
}
}
@ -73,33 +73,33 @@ impl From<bindings::ChannelType> for ChannelType {
fn from(value: bindings::ChannelType) -> Self {
// Unreachable match arms commented out
match value {
bindings::ChannelType_UndefinedChannel => { ChannelType::Undefined },
bindings::ChannelType_RedChannel => { ChannelType::RedChannel },
bindings::ChannelType_UndefinedChannel => ChannelType::Undefined,
bindings::ChannelType_RedChannel => ChannelType::RedChannel,
// bindings::ChannelType_GrayChannel => { ChannelType::GrayChannel },
// bindings::ChannelType_CyanChannel => { ChannelType::CyanChannel },
// bindings::ChannelType_LChannel => { ChannelType::LChannel },
bindings::ChannelType_GreenChannel => { ChannelType::GreenChannel },
bindings::ChannelType_GreenChannel => ChannelType::GreenChannel,
// bindings::ChannelType_MagentaChannel => { ChannelType::MagentaChannel },
// bindings::ChannelType_aChannel => { ChannelType::aChannel },
bindings::ChannelType_BlueChannel => { ChannelType::BlueChannel },
bindings::ChannelType_BlueChannel => ChannelType::BlueChannel,
// bindings::ChannelType_bChannel => { ChannelType::bChannel },
// bindings::ChannelType_YellowChannel => { ChannelType::YellowChannel },
bindings::ChannelType_BlackChannel => { ChannelType::BlackChannel },
bindings::ChannelType_AlphaChannel => { ChannelType::AlphaChannel },
bindings::ChannelType_BlackChannel => ChannelType::BlackChannel,
bindings::ChannelType_AlphaChannel => ChannelType::AlphaChannel,
// bindings::ChannelType_OpacityChannel => { ChannelType::OpacityChannel },
bindings::ChannelType_IndexChannel => { ChannelType::IndexChannel },
bindings::ChannelType_ReadMaskChannel => { ChannelType::ReadMaskChannel },
bindings::ChannelType_WriteMaskChannel => { ChannelType::WriteMaskChannel },
bindings::ChannelType_MetaChannel => { ChannelType::MetaChannel },
bindings::ChannelType_CompositeMaskChannel => { ChannelType::CompositeMaskChannel },
bindings::ChannelType_CompositeChannels => { ChannelType::CompositeChannels },
bindings::ChannelType_AllChannels => { ChannelType::AllChannels },
bindings::ChannelType_IndexChannel => ChannelType::IndexChannel,
bindings::ChannelType_ReadMaskChannel => ChannelType::ReadMaskChannel,
bindings::ChannelType_WriteMaskChannel => ChannelType::WriteMaskChannel,
bindings::ChannelType_MetaChannel => ChannelType::MetaChannel,
bindings::ChannelType_CompositeMaskChannel => ChannelType::CompositeMaskChannel,
bindings::ChannelType_CompositeChannels => ChannelType::CompositeChannels,
bindings::ChannelType_AllChannels => ChannelType::AllChannels,
// bindings::ChannelType_TrueAlphaChannel => { ChannelType::TrueAlphaChannel },
// bindings::ChannelType_RGBChannels => { ChannelType::RGBChannels },
bindings::ChannelType_GrayChannels => { ChannelType::GrayChannels },
bindings::ChannelType_SyncChannels => { ChannelType::SyncChannels },
bindings::ChannelType_GrayChannels => ChannelType::GrayChannels,
bindings::ChannelType_SyncChannels => ChannelType::SyncChannels,
// bindings::ChannelType_DefaultChannels => { ChannelType::DefaultChannels },
_ => { ChannelType::Undefined },
_ => ChannelType::Undefined,
}
}
}

View File

@ -11,7 +11,7 @@ impl Image<'_> {
pub unsafe fn new(img: *mut bindings::Image) -> Self {
Image {
image: img,
phantom_data: PhantomData
phantom_data: PhantomData,
}
}

View File

@ -1,7 +1,7 @@
use std::ffi::CString;
use crate::bindings;
use crate::{Result, MagickError};
use crate::{MagickError, Result};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
@ -58,9 +58,6 @@ impl From<KernelInfoType> for bindings::KernelInfoType {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u32)]
pub enum MorphologyMethod {
@ -101,9 +98,6 @@ impl From<MorphologyMethod> for bindings::KernelInfoType {
}
}
/// Builder, that creates instances of [KernelInfo](self::KernelInfo)
///
/// # Examples
@ -197,28 +191,25 @@ impl KernelBuilder {
}
pub fn build(&self) -> Result<KernelInfo> {
let size = self.size.ok_or(MagickError("no kernel size given".to_string()))?;
let values = self.values.as_ref().ok_or(MagickError("no kernel values given".to_string()))?;
let size = self
.size
.ok_or(MagickError("no kernel size given".to_string()))?;
let values = self
.values
.as_ref()
.ok_or(MagickError("no kernel values given".to_string()))?;
if values.len() != size.0 * size.1 {
return Err(MagickError("kernel size doesn't match kernel values size".to_string()));
return Err(MagickError(
"kernel size doesn't match kernel values size".to_string(),
));
}
// Create kernel string
let mut kernel_string = if let Some(center) = self.center {
format!(
"{}x{}+{}+{}:",
size.0,
size.1,
center.0,
center.1
)
format!("{}x{}+{}+{}:", size.0, size.1, center.0, center.1)
} else {
format!(
"{}x{}:",
size.0,
size.1,
)
format!("{}x{}:", size.0, size.1,)
};
// Add values
@ -233,12 +224,8 @@ impl KernelBuilder {
let c_kernel_string = CString::new(kernel_string).expect("CString::new() has failed");
// Create kernel info
let kernel_info = unsafe {
bindings::AcquireKernelInfo(
c_kernel_string.as_ptr(),
std::ptr::null_mut()
)
};
let kernel_info =
unsafe { bindings::AcquireKernelInfo(c_kernel_string.as_ptr(), std::ptr::null_mut()) };
if kernel_info.is_null() {
return Err(MagickError("failed to acquire kernel info".to_string()));
@ -260,20 +247,22 @@ impl KernelBuilder {
}
pub fn build_builtin(&self) -> Result<KernelInfo> {
let info_type = self.info_type.ok_or(MagickError("no info type given".to_string()))?;
let mut geom_info = self.geom_info.ok_or(MagickError("no geometry info given".to_string()))?;
let info_type = self
.info_type
.ok_or(MagickError("no info type given".to_string()))?;
let mut geom_info = self
.geom_info
.ok_or(MagickError("no geometry info given".to_string()))?;
// Create kernel info
let kernel_info = unsafe {
bindings::AcquireKernelBuiltIn(
info_type.into(),
&mut geom_info,
std::ptr::null_mut()
)
bindings::AcquireKernelBuiltIn(info_type.into(), &mut geom_info, std::ptr::null_mut())
};
if kernel_info.is_null() {
return Err(MagickError("failed to acquire builtin kernel info".to_string()));
return Err(MagickError(
"failed to acquire builtin kernel info".to_string(),
));
}
Ok(KernelInfo::new(kernel_info))
@ -286,20 +275,12 @@ pub struct KernelInfo {
impl KernelInfo {
fn new(kernel_info: *mut bindings::KernelInfo) -> KernelInfo {
return KernelInfo {
kernel_info
};
return KernelInfo { kernel_info };
}
/// The values within the kernel is scaled directly using given scaling factor without change.
pub fn scale(&mut self, factor: f64) {
unsafe {
bindings::ScaleKernelInfo(
self.kernel_info,
factor,
0
)
}
unsafe { bindings::ScaleKernelInfo(self.kernel_info, factor, 0) }
}
/// Kernel normalization is designed to ensure that any use of the kernel scaling factor with
@ -323,7 +304,7 @@ impl KernelInfo {
bindings::ScaleKernelInfo(
self.kernel_info,
1.0,
bindings::GeometryFlags_NormalizeValue
bindings::GeometryFlags_NormalizeValue,
)
}
}
@ -337,7 +318,7 @@ impl KernelInfo {
bindings::ScaleKernelInfo(
self.kernel_info,
1.0,
bindings::GeometryFlags_CorrelateNormalizeValue
bindings::GeometryFlags_CorrelateNormalizeValue,
)
}
}
@ -350,12 +331,7 @@ impl KernelInfo {
/// The resulting effect is to convert the defined kernels into blended soft-blurs, unsharp
/// kernels or into sharpening kernels.
pub fn unity_add(&mut self, scale: f64) {
unsafe {
bindings::UnityAddKernelInfo(
self.kernel_info,
scale
)
}
unsafe { bindings::UnityAddKernelInfo(self.kernel_info, scale) }
}
pub unsafe fn get_ptr(&self) -> *mut bindings::KernelInfo {
@ -371,9 +347,7 @@ impl Drop for KernelInfo {
impl Clone for KernelInfo {
fn clone(&self) -> Self {
let kernel_info = unsafe {
bindings::CloneKernelInfo(self.kernel_info)
};
let kernel_info = unsafe { bindings::CloneKernelInfo(self.kernel_info) };
if kernel_info.is_null() {
panic!("failed to clone kernel info");

View File

@ -7,7 +7,8 @@ pub enum MetricType {
MeanAbsolute = bindings::MetricType_MeanAbsoluteErrorMetric as isize,
MeanErrorPerPixel = bindings::MetricType_MeanErrorPerPixelErrorMetric as isize,
MeanSquared = bindings::MetricType_MeanSquaredErrorMetric as isize,
NormalizedCrossCorrelation = bindings::MetricType_NormalizedCrossCorrelationErrorMetric as isize,
NormalizedCrossCorrelation =
bindings::MetricType_NormalizedCrossCorrelationErrorMetric as isize,
PeakAbsolute = bindings::MetricType_PeakAbsoluteErrorMetric as isize,
PeakSignalToNoiseRatio = bindings::MetricType_PeakSignalToNoiseRatioErrorMetric as isize,
PerceptualHash = bindings::MetricType_PerceptualHashErrorMetric as isize,

View File

@ -21,16 +21,8 @@ use bindings;
use crate::result::MagickError;
use crate::result::Result;
use crate::{
AlignType,
ClipPathUnits,
DecorationType,
DirectionType,
FillRule,
GravityType,
LineCap,
LineJoin,
StretchType,
StyleType,
AlignType, ClipPathUnits, DecorationType, DirectionType, FillRule, GravityType, LineCap,
LineJoin, StretchType, StyleType,
};
wand_common!(

View File

@ -40,11 +40,9 @@ macro_rules! wand_common {
pub fn clear_exception(&mut self) -> Result<()> {
match unsafe { ::bindings::$clear_exc(self.wand) } {
::bindings::MagickBooleanType_MagickTrue => Ok(()),
_ => Err(MagickError(concat!(
"failed to clear",
stringify!($wand),
"exception"
).to_string())),
_ => Err(MagickError(
concat!("failed to clear", stringify!($wand), "exception").to_string(),
)),
}
}
@ -58,17 +56,14 @@ macro_rules! wand_common {
let ptr = unsafe { ::bindings::$get_exc(self.wand, &mut severity as *mut _) };
if ptr.is_null() {
Err(MagickError(concat!(
"null ptr returned by",
stringify!($wand),
"get_exception"
).to_string()))
Err(MagickError(
concat!("null ptr returned by", stringify!($wand), "get_exception")
.to_string(),
))
} else {
let c_str = unsafe { CStr::from_ptr(ptr) };
let exception = c_str.to_string_lossy().into_owned();
unsafe {
::bindings::RelinquishMagickMemory(ptr as *mut ::libc::c_void)
};
unsafe { ::bindings::RelinquishMagickMemory(ptr as *mut ::libc::c_void) };
Ok((exception, severity))
}
}
@ -76,7 +71,9 @@ macro_rules! wand_common {
pub fn is_wand(&self) -> Result<()> {
match unsafe { ::bindings::$is_wand(self.wand) } {
::bindings::MagickBooleanType_MagickTrue => Ok(()),
_ => Err(MagickError(concat!(stringify!($wand), " not a wand").to_string())),
_ => Err(MagickError(
concat!(stringify!($wand), " not a wand").to_string(),
)),
}
}
}
@ -159,10 +156,9 @@ macro_rules! string_get {
pub fn $get(&self) -> Result<String> {
let ptr = unsafe { ::bindings::$c_get(self.wand) };
if ptr.is_null() {
Err(MagickError(concat!(
"null ptr returned by ",
stringify!($get)
).to_string()))
Err(MagickError(
concat!("null ptr returned by ", stringify!($get)).to_string(),
))
} else {
let c_str = unsafe { ::std::ffi::CStr::from_ptr(ptr) };
let result: String = c_str.to_string_lossy().into_owned();

View File

@ -26,38 +26,16 @@ use result::MagickError;
#[cfg(not(target_os = "freebsd"))]
use size_t;
use super::{MagickFalse, MagickTrue};
use crate::result::Result;
use super::{MagickTrue, MagickFalse};
use super::{DrawingWand, PixelWand};
use crate::{
AlphaChannelOption,
AutoThresholdMethod,
ChannelType,
ColorspaceType,
CompositeOperator,
CompressionType,
DisposeType,
DitherMethod,
EndianType,
FilterType,
GravityType,
Image,
ImageType,
InterlaceType,
KernelInfo,
LayerMethod,
MagickEvaluateOperator,
MagickFunction,
MetricType,
MorphologyMethod,
OrientationType,
PixelInterpolateMethod,
PixelMask,
RenderingIntent,
ResolutionType,
ResourceType,
StatisticType,
AlphaChannelOption, AutoThresholdMethod, ChannelType, ColorspaceType, CompositeOperator,
CompressionType, DisposeType, DitherMethod, EndianType, FilterType, GravityType, Image,
ImageType, InterlaceType, KernelInfo, LayerMethod, MagickEvaluateOperator, MagickFunction,
MetricType, MorphologyMethod, OrientationType, PixelInterpolateMethod, PixelMask,
RenderingIntent, ResolutionType, ResourceType, StatisticType,
};
wand_common!(
@ -83,19 +61,21 @@ impl MagickWand {
///
/// * `img`: the image.
pub fn new_from_image(img: &Image<'_>) -> Result<MagickWand> {
let result = unsafe {
bindings::NewMagickWandFromImage(img.get_ptr())
};
let result = unsafe { bindings::NewMagickWandFromImage(img.get_ptr()) };
return if result.is_null() {
Err(MagickError("failed to create magick wand from image".to_string()))
Err(MagickError(
"failed to create magick wand from image".to_string(),
))
} else {
Ok(MagickWand { wand: result })
}
};
}
pub fn new_image(&self, columns: usize, rows: usize, background: &PixelWand) -> Result<()> {
match unsafe { bindings::MagickNewImage(self.wand, columns.into(), rows.into(), background.wand) } {
match unsafe {
bindings::MagickNewImage(self.wand, columns.into(), rows.into(), background.wand)
} {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -105,10 +85,7 @@ impl MagickWand {
#[cfg(any(target_os = "linux", target_os = "macos"))]
pub fn set_resource_limit(resource: ResourceType, limit: u64) -> Result<()> {
let result = unsafe {
bindings::SetMagickResourceLimit(
resource.into(),
limit as bindings::MagickSizeType,
)
bindings::SetMagickResourceLimit(resource.into(), limit as bindings::MagickSizeType)
};
match result {
MagickTrue => Ok(()),
@ -261,9 +238,7 @@ impl MagickWand {
/// MosaicLayer: Start with the virtual canvas of the first image, enlarging left and right
/// edges to contain all images. Images with negative offsets will be clipped.
pub fn merge_image_layers(&self, method: LayerMethod) -> Result<MagickWand> {
let result = unsafe {
bindings::MagickMergeImageLayers(self.wand, method.into())
};
let result = unsafe { bindings::MagickMergeImageLayers(self.wand, method.into()) };
if result.is_null() {
return Err(MagickError("failed to merge image layers".to_string()));
}
@ -357,11 +332,7 @@ impl MagickWand {
}
// Replaces colors in the image from a color lookup table.
pub fn clut_image(
&self,
clut_wand: &MagickWand,
method: PixelInterpolateMethod,
) -> Result<()> {
pub fn clut_image(&self, clut_wand: &MagickWand, method: PixelInterpolateMethod) -> Result<()> {
let result = unsafe { bindings::MagickClutImage(self.wand, clut_wand.wand, method.into()) };
match result {
MagickTrue => Ok(()),
@ -378,7 +349,8 @@ impl MagickWand {
}
pub fn fx(&mut self, expression: &str) -> Result<MagickWand> {
let c_expression = CString::new(expression).map_err(|_| "expression string contains null byte")?;
let c_expression =
CString::new(expression).map_err(|_| "expression string contains null byte")?;
let wand = unsafe { bindings::MagickFxImage(self.wand, c_expression.as_ptr()) };
if wand.is_null() {
Err(MagickError("failed to fx the image".to_string()))
@ -411,7 +383,9 @@ impl MagickWand {
16 => Ok(65535.0f64),
32 => Ok(4294967295.0f64),
64 => Ok(18446744073709551615.0f64),
_ => Err(MagickError("Quantum depth must be one of 8, 16, 32 or 64".to_string())),
_ => Err(MagickError(
"Quantum depth must be one of 8, 16, 32 or 64".to_string(),
)),
}
}
@ -456,14 +430,8 @@ impl MagickWand {
//MagickNormalizeImage enhances the contrast of a color image by adjusting the pixels color
//to span the entire range of colors available
pub fn normalize_image(
&self,
) -> Result<()> {
let result = unsafe {
bindings::MagickNormalizeImage(
self.wand,
)
};
pub fn normalize_image(&self) -> Result<()> {
let result = unsafe { bindings::MagickNormalizeImage(self.wand) };
match result {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
@ -473,18 +441,12 @@ impl MagickWand {
//MagickOrderedDitherImage performs an ordered dither based on a number of pre-defined
//dithering threshold maps, but over multiple intensity levels, which can be different for
//different channels, according to the input arguments.
pub fn ordered_dither_image(
&self,
threshold_map: &str,
) -> Result<()> {
let c_threshold_map = CString::new(threshold_map).map_err(|_| "threshold_map string contains null byte")?;
pub fn ordered_dither_image(&self, threshold_map: &str) -> Result<()> {
let c_threshold_map =
CString::new(threshold_map).map_err(|_| "threshold_map string contains null byte")?;
let result = unsafe {
bindings::MagickOrderedDitherImage(
self.wand,
c_threshold_map.as_ptr(),
)
};
let result =
unsafe { bindings::MagickOrderedDitherImage(self.wand, c_threshold_map.as_ptr()) };
match result {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
@ -576,9 +538,7 @@ impl MagickWand {
}
pub fn negate_image(&self) -> Result<()> {
let result = unsafe {
bindings::MagickNegateImage(self.wand, MagickTrue)
};
let result = unsafe { bindings::MagickNegateImage(self.wand, MagickTrue) };
match result {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
@ -625,7 +585,7 @@ impl MagickWand {
self.wand,
statistic_type.into(),
width.into(),
height.into()
height.into(),
)
} {
MagickTrue => Ok(()),
@ -687,12 +647,11 @@ impl MagickWand {
/// Reset the Wand page canvas and position.
pub fn reset_image_page(&self, page_geometry: &str) -> Result<()> {
let c_page_geometry = CString::new(page_geometry).map_err(|_| "page_geometry contains null byte")?;
match unsafe {
bindings::MagickResetImagePage(self.wand, c_page_geometry.as_ptr())
} {
let c_page_geometry =
CString::new(page_geometry).map_err(|_| "page_geometry contains null byte")?;
match unsafe { bindings::MagickResetImagePage(self.wand, c_page_geometry.as_ptr()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0))
_ => Err(MagickError(self.get_exception()?.0)),
}
}
@ -700,20 +659,18 @@ impl MagickWand {
///
/// * `artifact`: the artifact.
pub fn get_image_artifact(&self, artifact: &str) -> Result<String> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_artifact =
CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_value = unsafe {
bindings::MagickGetImageArtifact(
self.wand,
c_artifact.as_ptr()
)
};
let c_value = unsafe { bindings::MagickGetImageArtifact(self.wand, c_artifact.as_ptr()) };
if c_value.is_null() {
return Err(MagickError(format!("missing artifact: {}", artifact)));
}
// convert (and copy) the C string to a Rust string
let value = unsafe { CStr::from_ptr(c_value) }.to_string_lossy().into_owned();
let value = unsafe { CStr::from_ptr(c_value) }
.to_string_lossy()
.into_owned();
unsafe {
bindings::MagickRelinquishMemory(c_value as *mut c_void);
@ -723,15 +680,12 @@ impl MagickWand {
}
pub fn get_image_artifacts(&self, pattern: &str) -> Result<Vec<String>> {
let c_pattern = CString::new(pattern).map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let c_pattern = CString::new(pattern)
.map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let mut num_of_artifacts: size_t = 0;
let c_values = unsafe {
bindings::MagickGetImageArtifacts(
self.wand,
c_pattern.as_ptr(),
&mut num_of_artifacts
)
bindings::MagickGetImageArtifacts(self.wand, c_pattern.as_ptr(), &mut num_of_artifacts)
};
if c_values.is_null() {
@ -782,20 +736,13 @@ impl MagickWand {
/// Ok(())
/// }
/// ```
pub fn set_image_artifact(
&mut self,
artifact: &str,
value: &str
) -> Result<()> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
pub fn set_image_artifact(&mut self, artifact: &str, value: &str) -> Result<()> {
let c_artifact =
CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_value = CString::new(value).map_err(|_| "value string contains null byte")?;
let result = unsafe {
bindings::MagickSetImageArtifact(
self.wand,
c_artifact.as_ptr(),
c_value.as_ptr()
)
bindings::MagickSetImageArtifact(self.wand, c_artifact.as_ptr(), c_value.as_ptr())
};
match result {
@ -808,14 +755,10 @@ impl MagickWand {
///
/// * `artifact`: the artifact.
pub fn delete_image_artifact(&mut self, artifact: &str) -> Result<()> {
let c_artifact = CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
let c_artifact =
CString::new(artifact).map_err(|_| "artifact string contains null byte")?;
match unsafe {
bindings::MagickDeleteImageArtifact(
self.wand,
c_artifact.as_ptr()
)
} {
match unsafe { bindings::MagickDeleteImageArtifact(self.wand, c_artifact.as_ptr()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(format!("missing artifact: {}", artifact))),
}
@ -831,7 +774,9 @@ impl MagickWand {
}
// convert (and copy) the C string to a Rust string
let value = unsafe { CStr::from_ptr(c_value) }.to_string_lossy().into_owned();
let value = unsafe { CStr::from_ptr(c_value) }
.to_string_lossy()
.into_owned();
unsafe {
bindings::MagickRelinquishMemory(c_value as *mut c_void);
@ -841,15 +786,12 @@ impl MagickWand {
}
pub fn get_image_properties(&self, pattern: &str) -> Result<Vec<String>> {
let c_pattern = CString::new(pattern).map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let c_pattern = CString::new(pattern)
.map_err(|_| MagickError("artifact string contains null byte".to_string()))?;
let mut num_of_artifacts: size_t = 0;
let c_values = unsafe {
bindings::MagickGetImageProperties(
self.wand,
c_pattern.as_ptr(),
&mut num_of_artifacts
)
bindings::MagickGetImageProperties(self.wand, c_pattern.as_ptr(), &mut num_of_artifacts)
};
if c_values.is_null() {
@ -886,9 +828,7 @@ impl MagickWand {
pub fn get_image_pixel_color(&self, x: isize, y: isize) -> Option<PixelWand> {
let pw = PixelWand::new();
match unsafe {
bindings::MagickGetImagePixelColor(self.wand, x, y, pw.wand)
} {
match unsafe { bindings::MagickGetImagePixelColor(self.wand, x, y, pw.wand) } {
MagickTrue => Some(pw),
_ => None,
}
@ -972,9 +912,7 @@ impl MagickWand {
/// Sets the image resolution
pub fn set_image_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> {
match unsafe {
bindings::MagickSetImageResolution(self.wand, x_resolution, y_resolution)
} {
match unsafe { bindings::MagickSetImageResolution(self.wand, x_resolution, y_resolution) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -982,9 +920,7 @@ impl MagickWand {
/// Sets the wand resolution
pub fn set_resolution(&self, x_resolution: f64, y_resolution: f64) -> Result<()> {
match unsafe {
bindings::MagickSetResolution(self.wand, x_resolution, y_resolution)
} {
match unsafe { bindings::MagickSetResolution(self.wand, x_resolution, y_resolution) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1085,7 +1021,8 @@ impl MagickWand {
&self,
width_scale: f64,
height_scale: f64,
filter: FilterType) -> Result<()> {
filter: FilterType,
) -> Result<()> {
if width_scale < 0.0 {
return Err(MagickError("negative width scale given".to_string()));
}
@ -1106,9 +1043,7 @@ impl MagickWand {
/// 'thumbnail' optimizations which remove a lot of image meta-data with the goal
/// of producing small low cost images suited for display on the web.
pub fn thumbnail_image(&self, width: usize, height: usize) -> Result<()> {
match unsafe {
bindings::MagickThumbnailImage(self.wand, width.into(), height.into())
} {
match unsafe { bindings::MagickThumbnailImage(self.wand, width.into(), height.into()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1218,9 +1153,7 @@ impl MagickWand {
///
/// Returns `true` if successful or `false` if an error occurred.
pub fn auto_orient(&self) -> bool {
unsafe {
bindings::MagickAutoOrientImage(self.wand) == MagickTrue
}
unsafe { bindings::MagickAutoOrientImage(self.wand) == MagickTrue }
}
/// Write the current image to the provided path.
@ -1309,28 +1242,16 @@ impl MagickWand {
///
/// * `pixel_mask`: type of mask, Read or Write.
/// * `clip_mask`: the clip_mask wand.
pub fn set_image_mask(
&mut self,
pixel_mask: PixelMask,
clip_mask: &MagickWand
) -> Result<()> {
match unsafe {
bindings::MagickSetImageMask(
self.wand,
pixel_mask.into(),
clip_mask.wand
)
} {
pub fn set_image_mask(&mut self, pixel_mask: PixelMask, clip_mask: &MagickWand) -> Result<()> {
match unsafe { bindings::MagickSetImageMask(self.wand, pixel_mask.into(), clip_mask.wand) }
{
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
}
/// Set image channel mask
pub fn set_image_channel_mask(
&mut self,
option: ChannelType,
) -> ChannelType {
pub fn set_image_channel_mask(&mut self, option: ChannelType) -> ChannelType {
unsafe { bindings::MagickSetImageChannelMask(self.wand, option.into()).into() }
}
@ -1365,9 +1286,7 @@ impl MagickWand {
/// Simulate an image shadow
pub fn shadow_image(&self, alpha: f64, sigma: f64, x: isize, y: isize) -> Result<()> {
match unsafe {
bindings::MagickShadowImage(self.wand, alpha, sigma, x, y)
} {
match unsafe { bindings::MagickShadowImage(self.wand, alpha, sigma, x, y) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1471,14 +1390,18 @@ impl MagickWand {
colorspace: ColorspaceType,
tree_depth: usize,
dither_method: DitherMethod,
measure_error: bool) -> Result<()> {
match unsafe { bindings::MagickQuantizeImage(
measure_error: bool,
) -> Result<()> {
match unsafe {
bindings::MagickQuantizeImage(
self.wand,
number_of_colors.into(),
colorspace.into(),
tree_depth.into(),
dither_method.into(),
measure_error.to_magick()) } {
measure_error.to_magick(),
)
} {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1491,14 +1414,18 @@ impl MagickWand {
colorspace: ColorspaceType,
tree_depth: usize,
dither_method: DitherMethod,
measure_error: bool) -> Result<()> {
match unsafe { bindings::MagickQuantizeImages(
measure_error: bool,
) -> Result<()> {
match unsafe {
bindings::MagickQuantizeImages(
self.wand,
number_of_colors.into(),
colorspace.into(),
tree_depth.into(),
dither_method.into(),
measure_error.to_magick()) } {
measure_error.to_magick(),
)
} {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1529,19 +1456,10 @@ impl MagickWand {
/// Ok(())
/// }
/// ```
pub fn function_image(
&self,
function: MagickFunction,
args: &[f64]
) -> Result<()> {
pub fn function_image(&self, function: MagickFunction, args: &[f64]) -> Result<()> {
let num_of_args: size_t = args.len().into();
match unsafe {
bindings::MagickFunctionImage(
self.wand,
function.into(),
num_of_args,
args.as_ptr()
)
bindings::MagickFunctionImage(self.wand, function.into(), num_of_args, args.as_ptr())
} {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
@ -1557,13 +1475,7 @@ impl MagickWand {
return Err(MagickError("no constant coefficient given".to_string()));
}
let num_of_terms: size_t = (terms.len() >> 1).into();
match unsafe {
bindings::MagickPolynomialImage(
self.wand,
num_of_terms,
terms.as_ptr()
)
} {
match unsafe { bindings::MagickPolynomialImage(self.wand, num_of_terms, terms.as_ptr()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1573,12 +1485,7 @@ impl MagickWand {
///
/// * `kernel_info`: An array of doubles representing the convolution kernel.
pub fn convolve_image(&self, kernel_info: &KernelInfo) -> Result<()> {
match unsafe {
bindings::MagickConvolveImage(
self.wand,
kernel_info.get_ptr()
)
} {
match unsafe { bindings::MagickConvolveImage(self.wand, kernel_info.get_ptr()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1593,14 +1500,14 @@ impl MagickWand {
&self,
morphology_method: MorphologyMethod,
iterations: isize,
kernel_info: &KernelInfo
kernel_info: &KernelInfo,
) -> Result<()> {
match unsafe {
bindings::MagickMorphologyImage(
self.wand,
morphology_method.into(),
iterations.into(),
kernel_info.get_ptr()
kernel_info.get_ptr(),
)
} {
MagickTrue => Ok(()),
@ -1617,12 +1524,7 @@ impl MagickWand {
///
/// * `color_matrix`: the color matrix.
pub fn color_matrix_image(&self, color_matrix: &KernelInfo) -> Result<()> {
match unsafe {
bindings::MagickColorMatrixImage(
self.wand,
color_matrix.get_ptr()
)
} {
match unsafe { bindings::MagickColorMatrixImage(self.wand, color_matrix.get_ptr()) } {
MagickTrue => Ok(()),
_ => Err(MagickError(self.get_exception()?.0)),
}
@ -1640,14 +1542,10 @@ impl MagickWand {
///
/// * `expression`: the expression.
pub fn channel_fx_image(&self, expression: &str) -> Result<MagickWand> {
let c_expression = CString::new(expression).map_err(|_| "artifact string contains null byte")?;
let c_expression =
CString::new(expression).map_err(|_| "artifact string contains null byte")?;
let result = unsafe {
bindings::MagickChannelFxImage(
self.wand,
c_expression.as_ptr()
)
};
let result = unsafe { bindings::MagickChannelFxImage(self.wand, c_expression.as_ptr()) };
return if result.is_null() {
Err(MagickError(self.get_exception()?.0))
@ -1662,28 +1560,24 @@ impl MagickWand {
///
/// * `colorspace`: the colorspace.
pub fn combine_images(&self, colorspace: ColorspaceType) -> Result<MagickWand> {
let result = unsafe {
bindings::MagickCombineImages(self.wand, colorspace.into())
};
let result = unsafe { bindings::MagickCombineImages(self.wand, colorspace.into()) };
return if result.is_null() {
Err(MagickError(self.get_exception()?.0))
} else {
Ok(MagickWand { wand: result })
}
};
}
/// Returns the current image from the magick wand.
pub fn get_image<'wand>(&'wand self) -> Result<Image<'wand>> {
let result = unsafe {
bindings::GetImageFromMagickWand(self.wand)
};
let result = unsafe { bindings::GetImageFromMagickWand(self.wand) };
return if result.is_null() {
Err(MagickError(self.get_exception()?.0))
} else {
unsafe { Ok(Image::new(result)) }
}
};
}
mutations!(

View File

@ -23,5 +23,5 @@ pub use self::drawing::DrawingWand;
pub use self::magick::MagickWand;
pub use self::pixel::{PixelWand, HSL};
use bindings::MagickBooleanType_MagickTrue as MagickTrue;
use bindings::MagickBooleanType_MagickFalse as MagickFalse;
use bindings::MagickBooleanType_MagickTrue as MagickTrue;

View File

@ -19,8 +19,8 @@ use std::fmt;
use bindings;
use result::MagickError;
use crate::result::Result;
use super::MagickTrue;
use crate::result::Result;
#[derive(Default, Debug)]
pub struct HSL {

View File

@ -22,8 +22,8 @@ use std::io::Read;
use std::path::Path;
use std::sync::Once;
use magick_rust::{magick_wand_genesis, MagickWand, PixelWand};
use magick_rust::MagickError;
use magick_rust::{magick_wand_genesis, MagickWand, PixelWand};
// Used to make sure MagickWand is initialized exactly once. Note that we
// do not bother shutting down, we simply exit when the tests are done.
@ -54,7 +54,9 @@ fn test_resize_image() {
1 => 1,
height => height / 2,
};
assert!(wand.resize_image(halfwidth, halfheight, magick_rust::FilterType::Lanczos).is_ok());
assert!(wand
.resize_image(halfwidth, halfheight, magick_rust::FilterType::Lanczos)
.is_ok());
assert_eq!(256, wand.get_image_width());
assert_eq!(192, wand.get_image_height());
}
@ -171,7 +173,10 @@ fn test_get_image_property() {
// retrieve a property that does not exist
let missing_value = wand.get_image_property("exif:Foobar");
assert!(missing_value.is_err());
assert_eq!(MagickError("missing property: exif:Foobar".to_string()), missing_value.unwrap_err());
assert_eq!(
MagickError("missing property: exif:Foobar".to_string()),
missing_value.unwrap_err()
);
}
#[test]
@ -208,8 +213,7 @@ fn test_compare_images() {
assert!(wand2.read_image("tests/data/IMG_5745_rotl.JPG").is_ok());
wand2.auto_orient();
let (distortion, diff) =
wand1.compare_images(&wand2, magick_rust::MetricType::RootMeanSquared);
let (distortion, diff) = wand1.compare_images(&wand2, magick_rust::MetricType::RootMeanSquared);
assert!(distortion < 0.01);
assert!(diff.is_some());
}
@ -362,10 +366,7 @@ fn test_clut_image() {
assert!(gradient.read_image("gradient:black-yellow").is_ok());
assert!(wand
.clut_image(
&gradient,
magick_rust::PixelInterpolateMethod::Bilinear
)
.clut_image(&gradient, magick_rust::PixelInterpolateMethod::Bilinear)
.is_ok());
}