Skip to content

Read::read_exact works with StdinLock, but not with Cursor<StdinLock>? #52470

Closed
@tko

Description

@tko

I've some code reading a stream from stdin. Wanted to wrap it in a Cursor to have it keep track of the number of bytes read already instead of having to do it manually, but started getting odd compiler errors.

Since read_exact works just fine with StdinLock (and Stdin) shouldn't it work just the same with Cursor<StdinLock>?

use std::io::{self, Cursor, Read};
fn main() {
    let mut stdin = io::stdin(); // works with this
    let mut stdin = stdin.lock(); // works with this too
    let mut stdin = Cursor::new(stdin); // but both/either become invalid if wrapped in Cursor?
    let _b = read_u8(&mut stdin).expect("ok");
}
fn read_u8<R: Read>(r: &mut R) -> io::Result<u8> {
    let mut buf = [0u8; 1];
    r.read_exact(&mut buf)?;
    Ok(buf[0])
}

(Playground)

Errors:

   Compiling playground v0.0.1 (file:///playground)
error[E0277]: the trait bound `std::io::StdinLock<'_>: std::convert::AsRef<[u8]>` is not satisfied
 --> src/main.rs:6:14
  |
6 |     let _b = read_u8(&mut stdin).expect("ok");
  |              ^^^^^^^ the trait `std::convert::AsRef<[u8]>` is not implemented for `std::io::StdinLock<'_>`
  |
  = note: required because of the requirements on the impl of `std::io::Read` for `std::io::Cursor<std::io::StdinLock<'_>>`
note: required by `read_u8`
 --> src/main.rs:8:1
  |
8 | fn read_u8<R: Read>(r: &mut R) -> io::Result<u8> {
  | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

error: aborting due to previous error

For more information about this error, try `rustc --explain E0277`.
error: Could not compile `playground`.

To learn more, run the command again with --verbose.

Metadata

Metadata

Assignees

No one assigned

    Labels

    A-docsArea: Documentation for any part of the project, including the compiler, standard library, and tools

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions