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

Replace Box<dyn Error + ...> with dedicated error type #1

Open
wants to merge 4 commits into
base: main
Choose a base branch
from
Open
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 Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ keywords = ["linux", "video", "webcam"]
log = "0.4.14"
nix = "0.25.0"
bitflags = "1.2.1"
thiserror = "1.0"

[dev-dependencies]
env_logger = { version = "0.9.0", default-features = false }
Expand Down
24 changes: 12 additions & 12 deletions examples/control.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,31 +2,31 @@ use std::{env, path::Path};

use linuxvideo::Device;

fn usage() -> String {
format!("usage: control <device> <control> [<value>]")
}

fn main() -> linuxvideo::Result<()> {
env_logger::init();

let mut args = env::args_os().skip(1);

let path = args.next().ok_or_else(usage)?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: control <device> <control> [<value>]");
std::process::exit(1);
}
};

let control_name = args.next();
let control_name = match control_name.as_ref() {
Some(name) => Some(
name.to_str()
.ok_or_else(|| format!("control name must be UTF-8"))?,
),
Some(name) => Some(name.to_str().expect("control name must be UTF-8")),
None => None,
};
let value = args.next();
let value = match value.as_ref() {
Some(value) => Some(
value
.to_str()
.ok_or_else(|| format!("control name must be UTF-8"))?
.parse()?,
.and_then(|id| id.parse().ok())
.expect("control name must be UTF-8"),
),
None => None,
};
Expand Down Expand Up @@ -72,7 +72,7 @@ fn main() -> linuxvideo::Result<()> {
println!("{:?} control value: {}", cid, value);
}
},
None => return Err(format!("device does not have control named {}", control_name).into()),
None => panic!("device does not have control named {}", control_name),
}

Ok(())
Expand Down
10 changes: 7 additions & 3 deletions examples/drain-read.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ fn main() -> linuxvideo::Result<()> {

let mut args = env::args_os().skip(1);

let path = args
.next()
.ok_or_else(|| format!("usage: drain-read <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: drain-read <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;

Expand Down
10 changes: 7 additions & 3 deletions examples/drain-stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -21,9 +21,13 @@ fn main() -> linuxvideo::Result<()> {

let mut args = env::args_os().skip(1);

let path = args
.next()
.ok_or_else(|| format!("usage: drain-stream <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: drain-stream <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;

Expand Down
8 changes: 7 additions & 1 deletion examples/info.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,13 @@ fn main() -> linuxvideo::Result<()> {

let mut args = env::args_os().skip(1);

let path = args.next().ok_or_else(|| format!("usage: info <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: info <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;

Expand Down
17 changes: 9 additions & 8 deletions examples/output-stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -30,28 +30,29 @@ const TRANSPARENT: [u8; 4] = [0, 0, 0, 0];
fn main() -> linuxvideo::Result<()> {
let mut args = env::args_os().skip(1);

let path = args
.next()
.ok_or_else(|| format!("usage: write <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: write <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;
if !device
.capabilities()?
.device_capabilities()
.contains(CapabilityFlags::VIDEO_OUTPUT)
{
return Err(format!(
"cannot write data: selected device does not support `VIDEO_OUTPUT` capability"
)
.into());
panic!("cannot write data: selected device does not support `VIDEO_OUTPUT` capability");
}

let output = device.video_output(PixFormat::new(WIDTH, HEIGHT, PIXFMT))?;
let fmt = output.format();
println!("set format: {:?}", fmt);

if fmt.pixelformat() != PIXFMT {
return Err(format!("driver does not support the requested parameters").into());
panic!("driver does not support the requested parameters");
}

let mut image = (0..fmt.height())
Expand Down
17 changes: 9 additions & 8 deletions examples/output-write.rs
Original file line number Diff line number Diff line change
Expand Up @@ -28,28 +28,29 @@ const TRANSPARENT: [u8; 4] = [0, 0xff, 0xff, 120];
fn main() -> linuxvideo::Result<()> {
let mut args = env::args_os().skip(1);

let path = args
.next()
.ok_or_else(|| format!("usage: write <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: write <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;
if !device
.capabilities()?
.device_capabilities()
.contains(CapabilityFlags::VIDEO_OUTPUT)
{
return Err(format!(
"cannot write data: selected device does not support `VIDEO_OUTPUT` capability"
)
.into());
panic!("cannot write data: selected device does not support `VIDEO_OUTPUT` capability");
}

let mut output = device.video_output(PixFormat::new(WIDTH, HEIGHT, PIXFMT))?;
let fmt = output.format();
println!("set format: {:?}", fmt);

if fmt.pixelformat() != PIXFMT {
return Err(format!("driver does not support the requested parameters").into());
panic!("driver does not support the requested parameters");
}

let mut image = (0..fmt.height())
Expand Down
13 changes: 7 additions & 6 deletions examples/save-jpeg.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,13 +15,14 @@ fn main() -> linuxvideo::Result<()> {

let mut args = env::args_os().skip(1);

let device = args
.next()
.ok_or_else(|| format!("usage: save-stream <device> <file>"))?;
let (device, file_path) = match (args.next(), args.next()) {
(Some(device), Some(file_path)) => (device, file_path),
_ => {
println!("usage: save-stream <device> <file>");
std::process::exit(1);
}
};

let file_path = args
.next()
.ok_or_else(|| format!("usage: save-stream <device> <file>"))?;
let mut file = File::create(file_path)?;

let device = Device::open(Path::new(&device))?;
Expand Down
18 changes: 10 additions & 8 deletions examples/uvc-xu.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@ use std::{env, path::Path};

use linuxvideo::{uvc::UvcExt, Device};

fn usage() -> String {
format!("usage: uvc-xu <device> <extension unit ID>")
}

fn main() -> linuxvideo::Result<()> {
env_logger::init();

let mut args = env::args_os().skip(1);

let path = args.next().ok_or_else(usage)?;
let unit_id = args.next().ok_or_else(usage)?;
let (path, unit_id) = match (args.next(), args.next()) {
(Some(path), Some(unit_id)) => (path, unit_id),
_ => {
println!("usage: uvc-xu <device> <extension unit ID>");
std::process::exit(1);
}
};

let unit_id: u8 = unit_id
.to_str()
.ok_or_else(|| format!("unit ID must be an integer"))?
.parse()?;
.and_then(|id| id.parse().ok())
.expect("unit ID must be an integer");

let device = Device::open(Path::new(&path))?;

Expand Down
10 changes: 8 additions & 2 deletions examples/uvc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,13 @@ fn main() -> linuxvideo::Result<()> {

let mut args = env::args_os().skip(1);

let path = args.next().ok_or_else(|| format!("usage: uvc <device>"))?;
let path = match args.next() {
Some(path) => path,
None => {
println!("usage: uvc <device>");
std::process::exit(1);
}
};

let device = Device::open(Path::new(&path))?;

Expand All @@ -22,7 +28,7 @@ fn main() -> linuxvideo::Result<()> {
.device_capabilities()
.contains(CapabilityFlags::META_CAPTURE)
{
return Err("device does not support `META_CAPTURE` capability".into());
panic!("device does not support `META_CAPTURE` capability");
}

let meta = device.meta_capture(MetaFormat::new(Pixelformat::UVC))?;
Expand Down
27 changes: 27 additions & 0 deletions src/error.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
use thiserror::Error;

use crate::BufType;

/// The error type for interactions with this library.
#[derive(Error, Debug)]
#[non_exhaustive]
pub enum Error {
/// The number of allocated buffers was less than the amount requested.
#[error("failed to allocate {required_count} buffers (driver only allocated {actual_count})")]
BufferAllocationFailed {
required_count: u32,
actual_count: u32,
},
/// The requested buffer type is not supported.
#[error("unsupported buffer type {0:?}")]
UnsupportedBufferType(BufType),
/// An underlying I/O error has occurred.
#[error(transparent)]
Io(#[from] std::io::Error),
}

impl From<nix::Error> for Error {
fn from(error: nix::Error) -> Self {
Error::Io(std::io::Error::from_raw_os_error(error as i32))
}
}
9 changes: 5 additions & 4 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
mod macros;
mod buf_type;
pub mod controls;
mod error;
pub mod format;
mod pixelformat;
mod raw;
Expand All @@ -34,12 +35,12 @@ use shared::{CaptureParamFlags, Memory, StreamParamCaps};
use stream::{ReadStream, WriteStream};

pub use buf_type::*;
pub use error::Error;
pub use shared::{
AnalogStd, CapabilityFlags, Fract, InputCapabilities, InputStatus, InputType,
OutputCapabilities, OutputType,
};

pub type Error = Box<dyn std::error::Error + Send + Sync>;
pub type Result<T> = std::result::Result<T, Error>;

/// Returns an iterator over all connected V4L2 devices.
Expand Down Expand Up @@ -197,16 +198,16 @@ impl Device {
///
/// The returned `Format` variant will match `buf_type`.
///
/// If no format is set, this returns `EINVAL`.
/// If no format is set, this returns [`Error::UnsupportedBufferType`].
pub fn format(&self, buf_type: BufType) -> Result<Format> {
unsafe {
let mut format = raw::Format {
type_: buf_type,
..mem::zeroed()
};
raw::g_fmt(self.fd(), &mut format)?;
let fmt = Format::from_raw(format)
.ok_or_else(|| format!("unsupported buffer type {:?}", buf_type))?;
let fmt =
Format::from_raw(format).ok_or_else(|| Error::UnsupportedBufferType(buf_type))?;
Ok(fmt)
}
}
Expand Down
11 changes: 5 additions & 6 deletions src/stream.rs
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ use nix::sys::mman::{mmap, munmap, MapFlags, ProtFlags};

use crate::buf_type::BufType;
use crate::shared::{BufFlag, Memory};
use crate::{raw, Result};
use crate::{raw, Error, Result};

enum AllocType {
/// The buffer was `mmap`ped into our address space, use `munmap` to free it.
Expand Down Expand Up @@ -55,11 +55,10 @@ impl Buffers {
log::debug!("{:?}", req_bufs);

if req_bufs.count < buffer_count {
return Err(format!(
"failed to allocate {} buffers (driver only allocated {})",
buffer_count, req_bufs.count
)
.into());
return Err(Error::BufferAllocationFailed {
required_count: buffer_count,
actual_count: req_bufs.count,
});
}

// Query the buffer locations and map them into our process.
Expand Down