Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix some clippy suggestions #20

Merged
merged 2 commits into from
Feb 5, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .clippy.toml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
msrv = "1.46.0"
4 changes: 2 additions & 2 deletions examples/riio_bufavg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -69,8 +69,8 @@ impl Averager {
// Creates a new averager with the specified offset and scale.
pub fn new(offset: f64, scale: f64) -> Self {
let (sender, receiver) = channel();
let thr = spawn(move || Averager::thread_func(receiver, offset, scale));
Averager { sender, thr }
let thr = spawn(move || Self::thread_func(receiver, offset, scale));
Self { sender, thr }
}

// The internal thread function.
Expand Down
10 changes: 5 additions & 5 deletions src/bin/iio_info_rs.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
use industrial_io as iio;
use std::process;

fn main() -> iio::Result<()> {
fn main() {
let lib_ver = iio::library_version();
println!("Library version: {}", lib_ver);

Expand All @@ -27,7 +27,7 @@ fn main() -> iio::Result<()> {

println!("{} context attribute(s) found", ctx.num_attrs());
for attr in ctx.attributes() {
println!("\t{}: {}", attr.0, attr.1)
println!("\t{}: {}", attr.0, attr.1);
}

println!("IIO context has {} device(s):", ctx.num_devices());
Expand Down Expand Up @@ -69,11 +69,11 @@ fn main() -> iio::Result<()> {
if dev.has_attrs() {
println!("\t\tAttributes:");
for attr in dev.attributes() {
let val_str = dev.attr_read_str(&attr).unwrap_or("Unknown".into());
let val_str = dev
.attr_read_str(&attr)
.unwrap_or_else(|_| String::from("Unknown"));
println!("\t\t\t{}: {}", attr, val_str);
}
}
}

Ok(())
}
8 changes: 4 additions & 4 deletions src/buffer.rs
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ use std::{
collections::HashMap,
marker::PhantomData,
mem,
os::raw::{c_int, c_longlong, c_void},
os::raw::{c_int, c_longlong},
ptr,
};

Expand Down Expand Up @@ -262,7 +262,7 @@ impl Buffer {
/// retrieve all the attributes with a single call.
pub fn attr_read_all(&self) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();
let pmap = &mut map as *mut _ as *mut c_void;
let pmap = (&mut map as *mut HashMap<_, _>).cast();
let ret = unsafe {
ffi::iio_device_buffer_attr_read_all(self.dev.dev, Some(attr_read_all_cb), pmap)
};
Expand Down Expand Up @@ -338,7 +338,7 @@ impl Buffer {
/// Gets an iterator for the data from a channel.
pub fn channel_iter<T>(&self, chan: &Channel) -> IntoIter<T> {
unsafe {
let begin = ffi::iio_buffer_first(self.buf, chan.chan) as *mut T;
let begin = ffi::iio_buffer_first(self.buf, chan.chan).cast();
let end = ffi::iio_buffer_end(self.buf) as *const T;
let ptr = begin;
let step: isize = ffi::iio_buffer_step(self.buf) / mem::size_of::<T>() as isize;
Expand Down Expand Up @@ -377,7 +377,7 @@ impl<T> Iterator for IntoIter<T> {

fn next(&mut self) -> Option<T> {
unsafe {
if self.ptr as *const _ >= self.end {
if self.ptr.cast() >= self.end {
None
}
else {
Expand Down
41 changes: 17 additions & 24 deletions src/channel.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ pub struct DataFormat {
impl DataFormat {
/// Creates a new data format from the underlyinh library type.
fn new(data_fmt: ffi::iio_data_format) -> Self {
DataFormat { data_fmt }
Self { data_fmt }
}

/// Gets total length of the sample, in bits.
Expand Down Expand Up @@ -108,7 +108,7 @@ impl DataFormat {
self.data_fmt.with_scale
}

/// Contains the scale to apply if with_scale is set
/// Contains the scale to apply if `with_scale` is set
pub fn scale(&self) -> f64 {
self.data_fmt.scale
}
Expand All @@ -124,9 +124,9 @@ impl DataFormat {
nbytes as usize
}

/// Gets the TypeId for a single sample from the channel.
/// Gets the `TypeId` for a single sample from the channel.
///
/// This will get the TypeId for a sample if it can fit into a standard
/// This will get the `TypeId` for a sample if it can fit into a standard
/// integer type, signed or unsigned, of 8, 16, 32, or 64 bits.
pub fn type_of(&self) -> Option<TypeId> {
let nbytes = self.byte_length();
Expand Down Expand Up @@ -297,7 +297,7 @@ impl Channel {
let attr = CStr::from_ptr(attr).to_string_lossy().to_string();
// TODO: We could/should check val[len-1] == '\x0'
let val = CStr::from_ptr(val).to_string_lossy().to_string();
let map: &mut HashMap<String, String> = &mut *(pmap as *mut _);
let map: &mut HashMap<String, String> = &mut *pmap.cast();
map.insert(attr, val);
0
}
Expand All @@ -307,7 +307,7 @@ impl Channel {
/// retrieve all the attributes with a single call.
pub fn attr_read_all(&self) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();
let pmap = &mut map as *mut _ as *mut c_void;
let pmap = (&mut map as *mut HashMap<_, _>).cast();
let ret = unsafe {
ffi::iio_channel_attr_read_all(self.chan, Some(Channel::attr_read_all_cb), pmap)
};
Expand Down Expand Up @@ -397,9 +397,9 @@ impl Channel {
}
}

/// Gets the TypeId for a single sample from the channel.
/// Gets the `TypeId` for a single sample from the channel.
///
/// This will get the TypeId for a sample if it can fit into a standard
/// This will get the `TypeId` for a sample if it can fit into a standard
/// integer type, signed or unsigned, of 8, 16, 32, or 64 bits.
pub fn type_of(&self) -> Option<TypeId> {
let dfmt = self.data_format();
Expand Down Expand Up @@ -429,8 +429,8 @@ impl Channel {
unsafe {
ffi::iio_channel_convert(
self.chan,
&mut retval as *mut T as *mut c_void,
&val as *const T as *const c_void,
(&mut retval as *mut T).cast(),
(&val as *const T).cast(),
);
}
}
Expand All @@ -451,8 +451,8 @@ impl Channel {
unsafe {
ffi::iio_channel_convert_inverse(
self.chan,
&mut retval as *mut T as *mut c_void,
&val as *const T as *const c_void,
(&mut retval as *mut T).cast(),
(&val as *const T).cast(),
);
}
}
Expand All @@ -473,9 +473,7 @@ impl Channel {
let sz_in = n * sz_item;

let mut v = vec![T::default(); n];
let sz = unsafe {
ffi::iio_channel_read(self.chan, buf.buf, v.as_mut_ptr() as *mut c_void, sz_in)
};
let sz = unsafe { ffi::iio_channel_read(self.chan, buf.buf, v.as_mut_ptr().cast(), sz_in) };

if sz > sz_in {
return Err(Error::BadReturnSize); // This should never happen.
Expand All @@ -501,9 +499,8 @@ impl Channel {
let sz_in = n * sz_item;

let mut v = vec![T::default(); n];
let sz = unsafe {
ffi::iio_channel_read_raw(self.chan, buf.buf, v.as_mut_ptr() as *mut c_void, sz_in)
};
let sz =
unsafe { ffi::iio_channel_read_raw(self.chan, buf.buf, v.as_mut_ptr().cast(), sz_in) };

if sz > sz_in {
return Err(Error::BadReturnSize); // This should never happen.
Expand All @@ -528,9 +525,7 @@ impl Channel {
let sz_item = mem::size_of::<T>();
let sz_in = data.len() * sz_item;

let sz = unsafe {
ffi::iio_channel_write(self.chan, buf.buf, data.as_ptr() as *const c_void, sz_in)
};
let sz = unsafe { ffi::iio_channel_write(self.chan, buf.buf, data.as_ptr().cast(), sz_in) };

Ok(sz / sz_item)
}
Expand All @@ -548,9 +543,7 @@ impl Channel {
let sz_item = mem::size_of::<T>();
let sz_in = data.len() * sz_item;

let sz = unsafe {
ffi::iio_channel_write(self.chan, buf.buf, data.as_ptr() as *const c_void, sz_in)
};
let sz = unsafe { ffi::iio_channel_write(self.chan, buf.buf, data.as_ptr().cast(), sz_in) };

Ok(sz / sz_item)
}
Expand Down
32 changes: 17 additions & 15 deletions src/context.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ use std::{
/// Sync.
///
/// This object maintains a reference counted pointer to the context object
/// of the underlying library's iio_context object. Once all references to
/// the Context object have been dropped, the underlying iio_context will be
/// of the underlying library's `iio_context` object. Once all references to
/// the Context object have been dropped, the underlying `iio_context` will be
/// destroyed. This is done to make creation and use of a single Device more
/// ergonomic by removing the need to manage the lifetime of the Context.
#[derive(Debug, Clone)]
Expand Down Expand Up @@ -116,9 +116,11 @@ impl InnerContext {
/// This should be called _right after_ creating the C context as it
/// will use the last error on failure.
fn new(ctx: *mut ffi::iio_context) -> Result<Self> {
match ctx.is_null() {
true => Err(Error::from(Errno::last())),
false => Ok(Self { ctx }),
if ctx.is_null() {
Err(Error::from(Errno::last()))
}
else {
Ok(Self { ctx })
}
}

Expand Down Expand Up @@ -153,12 +155,12 @@ impl Context {
///
/// # Notes
///
/// This will create a network context if the IIOD_REMOTE
/// This will create a network context if the `IIOD_REMOTE`
/// environment variable is set to the hostname where the IIOD server
/// runs. If set to an empty string, the server will be discovered using
/// ZeroConf. If the environment variable is not set, a local context
/// `ZeroConf`. If the environment variable is not set, a local context
/// will be created instead.
pub fn new() -> Result<Context> {
pub fn new() -> Result<Self> {
Self::from_ptr(unsafe { ffi::iio_create_default_context() })
}

Expand Down Expand Up @@ -200,7 +202,7 @@ impl Context {
///
/// let ctx = iio::Context::with_backend(iio::Backend::Uri("ip:192.168.2.1"));
/// ```
pub fn with_backend(be: Backend) -> Result<Context> {
pub fn with_backend(be: Backend) -> Result<Self> {
Self::from_ptr(unsafe {
match be {
Backend::Default => ffi::iio_create_default_context(),
Expand Down Expand Up @@ -264,15 +266,15 @@ impl Context {
/// This attempts to release and return the [`InnerContext`], which
/// succeeds if this is the only [`Context`] referring to it. If there are
/// other references, an error is returned with a [`Context`].
pub fn try_release_inner(self) -> std::result::Result<InnerContext, Context> {
pub fn try_release_inner(self) -> std::result::Result<InnerContext, Self> {
match Arc::try_unwrap(self.inner) {
Ok(inner) => Ok(inner),
Err(inner_ptr) => Err(Context { inner: inner_ptr }),
Err(inner_ptr) => Err(Self { inner: inner_ptr }),
}
}

/// Make a new context based on a full copy of underlying C context.
pub fn try_deep_clone(&self) -> Result<Context> {
pub fn try_deep_clone(&self) -> Result<Self> {
let inner = self.inner.try_clone()?;
Ok(Self {
inner: Arc::new(inner),
Expand All @@ -298,7 +300,7 @@ impl Context {
let mut minor: c_uint = 0;

const BUF_SZ: usize = 8;
let mut buf = vec![' ' as c_char; BUF_SZ];
let mut buf = vec![b' ' as c_char; BUF_SZ];
let pbuf = buf.as_mut_ptr();

unsafe { ffi::iio_context_get_version(self.inner.ctx, &mut major, &mut minor, pbuf) };
Expand All @@ -308,7 +310,7 @@ impl Context {
CStr::from_ptr(pbuf).to_owned()
}
else {
let slc = str::from_utf8(slice::from_raw_parts(pbuf as *mut u8, BUF_SZ)).unwrap();
let slc = str::from_utf8(slice::from_raw_parts(pbuf.cast(), BUF_SZ)).unwrap();
CString::new(slc).unwrap()
}
};
Expand Down Expand Up @@ -428,7 +430,7 @@ impl Context {
impl PartialEq for Context {
/// Two contexts are the same if they refer to the same underlying
/// object in the library.
fn eq(&self, other: &Context) -> bool {
fn eq(&self, other: &Self) -> bool {
self.inner.ctx == other.inner.ctx
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/device.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ use nix::errno::Errno;
use std::{
collections::HashMap,
ffi::CString,
os::raw::{c_char, c_longlong, c_uint, c_void},
os::raw::{c_char, c_longlong, c_uint},
ptr,
};

Expand Down Expand Up @@ -68,7 +68,7 @@ impl Device {

/// Associate a trigger for this device.
/// `trigger` The device to be used as a trigger.
pub fn set_trigger(&self, trigger: &Device) -> Result<()> {
pub fn set_trigger(&self, trigger: &Self) -> Result<()> {
let ret = unsafe { ffi::iio_device_set_trigger(self.dev, trigger.dev) };
sys_result(ret, ())
}
Expand Down Expand Up @@ -172,7 +172,7 @@ impl Device {
/// retrieve all the attributes with a single call.
pub fn attr_read_all(&self) -> Result<HashMap<String, String>> {
let mut map = HashMap::new();
let pmap = &mut map as *mut _ as *mut c_void;
let pmap = (&mut map as *mut HashMap<_, _>).cast();
let ret = unsafe { ffi::iio_device_attr_read_all(self.dev, Some(attr_read_all_cb), pmap) };
sys_result(ret, map)
}
Expand Down Expand Up @@ -320,7 +320,7 @@ unsafe impl Send for Device {}
impl PartialEq for Device {
/// Two devices are the same if they refer to the same underlying
/// object in the library.
fn eq(&self, other: &Device) -> bool {
fn eq(&self, other: &Self) -> bool {
self.dev == other.dev
}
}
Expand Down
8 changes: 4 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ impl ToAttribute for bool {
}

impl FromAttribute for bool {
fn from_attr(s: &str) -> Result<bool> {
Ok(if s.trim() == "0" { false } else { true })
fn from_attr(s: &str) -> Result<Self> {
Ok(s.trim() != "0")
}
}

Expand Down Expand Up @@ -163,7 +163,7 @@ pub(crate) unsafe extern "C" fn attr_read_all_cb(
let attr = CStr::from_ptr(attr).to_string_lossy().to_string();
// TODO: We could/should check val[len-1] == '\x0'
let val = CStr::from_ptr(val).to_string_lossy().to_string();
let map: &mut HashMap<String, String> = &mut *(pmap as *mut _);
let map: &mut HashMap<String, String> = &mut *pmap.cast();
map.insert(attr, val);
0
}
Expand Down Expand Up @@ -205,7 +205,7 @@ pub fn library_version() -> Version {
CStr::from_ptr(pbuf).to_owned()
}
else {
let slc = str::from_utf8(slice::from_raw_parts(pbuf as *mut u8, BUF_SZ)).unwrap();
let slc = str::from_utf8(slice::from_raw_parts(pbuf.cast(), BUF_SZ)).unwrap();
CString::new(slc).unwrap()
}
};
Expand Down