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

Consider making Reader and Writer generic in their type of error #18414

Closed
canndrew opened this issue Oct 29, 2014 · 3 comments
Closed

Consider making Reader and Writer generic in their type of error #18414

canndrew opened this issue Oct 29, 2014 · 3 comments

Comments

@canndrew
Copy link
Contributor

IoError doesn't make sense for all kinds of Reader and Writer. Instead, implementors should be able to choose what they return using an associated type.

For example, the Reader trait would look like this:

trait Reader {
    type Error;
    fn read(&mut self, buf: &mut [u8]) -> Result<uint, Error>;
    ...
}
@canndrew
Copy link
Contributor Author

It wouldn't be hard to convert most of the Readers and Writers in the standard library over to this. And some of them would be improved by it. For example, LimitReader could be implemented like this:

impl<R: Reader> Reader for LimitReader<R> {
    type Error = Option<R::Error>;
    ...
}

This would give the ability to distinguish between errors caused be exceeding the limit and errors raised by the underlying reader by returning None and Some(e) respectively. For types that never return an error (eg. NullWriter, MemWriter, ZeroReader), it would be useful to have a standard empty type that they could use as their error type...

enum Empty {}

impl Reader for ZeroReader {
    type Error = Empty;
    ...
}

Result could then be extended with safe_unwrap method that's guaranteed to never fail.

impl<T> Result<T, Empty> {
    fn safe_unwrap(self) -> T {
        match self {
            Ok(t) => t,
            Err(e) => match e {},
        }
    }
}

@canndrew
Copy link
Contributor Author

In addition to the above:

There are plenty of implementors of these traits that can only fail in one possible way. For these it would make sense to just use Error = (). Also, you could make non-blocking wrappers around Receiver and Sender that return TryRecvError and TrySendError respectively.

@steveklabnik
Copy link
Member

Hey @canndrew ! You should get involved over in rust-lang/rfcs#576 if this issue is still important to you, that's the right place to bring this up. Thank you!

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