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

Improve the precision of error handling internally #92

Open
raphaelcohn opened this issue Jul 28, 2021 · 1 comment
Open

Improve the precision of error handling internally #92

raphaelcohn opened this issue Jul 28, 2021 · 1 comment

Comments

@raphaelcohn
Copy link

I was looking at the internals of Device.get_ports(), and it swallows all the error codes returned by libusb, and even those that can never be.

This means that an downstream user can enter a state of unknown validity or impossible validity after checking the Result<_, Error> returned; not doing so violates the fail fast maxim.

Instead, code calling a third party C library must explicitly check for the documented errors it can return. In this example, it should do something like:-

	let mut port_numbers  = ArrayVec::new_const();
	let result = unsafe { libusb_get_port_numbers(device.as_raw(), port_numbers.as_mut_ptr(), MaximumDevicePortNumbers as _) };
	if likely!(result >= 0)
	{
		let count = result as usize;
		unsafe { port_numbers.set_len(count) };
	}
	else if likely!(result == LIBUSB_ERROR_OVERFLOW)
	{
		panic!("USB violates specification with more than 7 ports")
	}
	else
	{
		unreachable!("Undocumented error code from libusb_get_port_numbers(), {}", result)
	}

(likely! is a macro I use). Obviously, coding this for every call is tedious and time-consuming, but that's the cost of wrapping third party C libraries with their naive error handling strategies and use of a shared pool of constants.

Likewise this implies that rusb should (indeed, must) have more than one kind of Error.

@mcuee
Copy link

mcuee commented Apr 30, 2023

Potential workaround is to use libusb debug info for troubleshooting purpose, by setting LIBUSB_DEBUG env variable to a suitable value (eg: LIBUSB_DEBUG = 4).

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants