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

About Stdin.read() is blocked. #9

Open
biluohc opened this issue Apr 21, 2018 · 0 comments
Open

About Stdin.read() is blocked. #9

biluohc opened this issue Apr 21, 2018 · 0 comments

Comments

@biluohc
Copy link
Owner

biluohc commented Apr 21, 2018

ripgrep: stdin_is_readable()

// same-file= "*"
extern crate same_file;

use std::io::*;

fn main() {
    if stdin_is_readable() {
        let mut bytes = Vec::new();
        let mut s = BufReader::new(stdin());
        let mut tmp = [0u8];
        while let Ok(n) = s.read(&mut tmp) {
            if n == 0 {
                break;
            }
            bytes.push(tmp[0]);
        }
        println!("{}", String::from_utf8_lossy(&bytes[..]));
    }
}

#[cfg(unix)]
fn stdin_is_readable() -> bool {
    use same_file::Handle;
    use std::os::unix::fs::FileTypeExt;

    let ft = match Handle::stdin().and_then(|h| h.as_file().metadata()) {
        Err(_) => return false,
        Ok(md) => md.file_type(),
    };
    ft.is_file() || ft.is_fifo()
}

/// Returns true if and only if stdin is deemed searchable.
#[cfg(windows)]
fn stdin_is_readable() -> bool {
    // On Windows, it's not clear what the possibilities are to me, so just
    // always return true.
    true
}
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

1 participant