/*! Utility functions */

/*
    Copyright (C) 2022 John Goerzen <jgoerzen@complete.org>

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
*/

use std::fs::File;
use std::io::stdin;
use std::os::unix::io::{AsRawFd, FromRawFd};

/// stdin is buffered by default on Rust, and you can't change it.  Since
/// we need to precisely read the header before letting a subprocess
/// handle the payload in stdin-process, we have to use trickery.  Bleh.
///
/// Take care not to let this value drop before spawning, because that would
/// cause stdin to be closed.
///
/// See: https://github.com/rust-lang/rust/issues/97855
pub fn get_unbuffered_stdin() -> File {
    let s = stdin();
    let locked = s.lock();
    let file = unsafe { File::from_raw_fd(locked.as_raw_fd()) };
    file
}
