mod common;
use std::fs::File;
use std::io::{Read, Seek, Write};
use oscall::io::{self, IoSlice, IoSliceMut, SeekFrom};
use oscall::{AsHandle, BorrowedHandle, ErrorKind, RawHandle};
use common::handle_of;
fn create(path: &std::path::Path) -> File {
File::options()
.read(true)
.write(true)
.create(true)
.truncate(true)
.open(path)
.unwrap()
}
fn write_all(handle: impl AsHandle, mut buf: &[u8]) {
while !buf.is_empty() {
let n = io::write(handle.as_handle(), buf).unwrap();
assert!(n > 0 && n <= buf.len());
buf = &buf[n..];
}
}
fn read_full(handle: impl AsHandle, buf: &mut [u8]) -> usize {
let mut done = 0;
while done < buf.len() {
match io::read(handle.as_handle(), &mut buf[done..]).unwrap() {
0 => break,
n => done += n,
}
}
done
}
fn invalid_handle() -> BorrowedHandle<'static> {
#[cfg(target_os = "wasi")]
let raw: RawHandle = 123_456;
#[cfg(windows)]
let raw = 0x7ffc_0000usize as RawHandle;
#[cfg(not(any(windows, target_os = "wasi")))]
let raw: RawHandle = -1;
unsafe { BorrowedHandle::borrow_raw(raw) }
}
#[test]
fn read_write() {
let dir = common::tmp_dir("io-read-write");
let path = dir.join("file");
let mut file = create(&path);
write_all(handle_of(&file), b"hello, ");
write_all(handle_of(&file), b"world");
assert_eq!(io::write(handle_of(&file), b"").unwrap(), 0);
assert_eq!(std::fs::read(&path).unwrap(), b"hello, world");
assert_eq!(file.stream_position().unwrap(), 12);
file.rewind().unwrap();
let mut buf = [0u8; 5];
assert_eq!(read_full(handle_of(&file), &mut buf), 5);
assert_eq!(&buf, b"hello");
let mut rest = [0u8; 64];
assert_eq!(read_full(handle_of(&file), &mut rest), 7);
assert_eq!(&rest[..7], b", world");
assert_eq!(io::read(handle_of(&file), &mut rest).unwrap(), 0);
assert_eq!(io::read(handle_of(&file), &mut []).unwrap(), 0);
file.write_all(b"!").unwrap();
file.rewind().unwrap();
let mut all = Vec::new();
file.read_to_end(&mut all).unwrap();
assert_eq!(all, b"hello, world!");
}
#[test]
fn bad_handle() {
let bad = invalid_handle();
let mut buf = [0u8; 4];
assert_eq!(io::read(bad, &mut buf).unwrap_err(), ErrorKind::BadHandle);
assert_eq!(io::write(bad, b"x").unwrap_err(), ErrorKind::BadHandle);
assert_eq!(
io::read_at(bad, &mut buf, 0).unwrap_err(),
ErrorKind::BadHandle
);
assert_eq!(
io::write_at(bad, b"x", 0).unwrap_err(),
ErrorKind::BadHandle
);
assert_eq!(
io::seek(bad, SeekFrom::Start(0)).unwrap_err(),
ErrorKind::BadHandle
);
assert_eq!(
io::write_vectored(bad, &[IoSlice::new(b"x")]).unwrap_err(),
ErrorKind::BadHandle
);
assert_eq!(
io::read_vectored(bad, &mut [IoSliceMut::new(&mut buf)]).unwrap_err(),
ErrorKind::BadHandle
);
assert!(!io::is_terminal(bad));
#[cfg(not(target_os = "wasi"))]
{
assert_eq!(io::duplicate(bad).unwrap_err(), ErrorKind::BadHandle);
assert_eq!(io::is_inheritable(bad).unwrap_err(), ErrorKind::BadHandle);
assert_eq!(
io::set_inheritable(bad, true).unwrap_err(),
ErrorKind::BadHandle
);
}
}
#[test]
fn positional() {
let dir = common::tmp_dir("io-positional");
let path = dir.join("file");
let mut file = create(&path);
file.write_all(b"0123456789").unwrap();
let mut buf = [0u8; 4];
assert_eq!(io::read_at(handle_of(&file), &mut buf, 3).unwrap(), 4);
assert_eq!(&buf, b"3456");
assert_eq!(io::read_at(handle_of(&file), &mut buf, 8).unwrap(), 2);
assert_eq!(&buf[..2], b"89");
assert_eq!(io::read_at(handle_of(&file), &mut buf, 10).unwrap(), 0);
assert_eq!(io::read_at(handle_of(&file), &mut buf, 1000).unwrap(), 0);
assert_eq!(io::write_at(handle_of(&file), b"ab", 2).unwrap(), 2);
assert_eq!(io::write_at(handle_of(&file), b"z", 12).unwrap(), 1);
assert_eq!(std::fs::read(&path).unwrap(), b"01ab456789\0\0z");
#[cfg(not(windows))]
assert_eq!(file.stream_position().unwrap(), 10);
}
#[cfg(windows)]
fn make_sparse(file: &File) {
use std::os::windows::io::AsRawHandle;
#[link(name = "kernel32")]
unsafe extern "system" {
fn DeviceIoControl(
handle: *mut core::ffi::c_void,
code: u32,
input: *const core::ffi::c_void,
input_len: u32,
output: *mut core::ffi::c_void,
output_len: u32,
returned: *mut u32,
overlapped: *mut core::ffi::c_void,
) -> i32;
}
const FSCTL_SET_SPARSE: u32 = 0x000900c4;
let mut returned = 0;
let ok = unsafe {
DeviceIoControl(
file.as_raw_handle(),
FSCTL_SET_SPARSE,
std::ptr::null(),
0,
std::ptr::null_mut(),
0,
&mut returned,
std::ptr::null_mut(),
)
};
assert_ne!(ok, 0, "{}", std::io::Error::last_os_error());
}
#[cfg(not(windows))]
fn make_sparse(_: &File) {}
#[test]
fn large_offsets() {
const FAR: u64 = (5 << 30) + 3;
let dir = common::tmp_dir("io-large-offsets");
let path = dir.join("file");
let mut file = create(&path);
make_sparse(&file);
assert_eq!(io::write_at(handle_of(&file), b"far", FAR).unwrap(), 3);
assert_eq!(file.metadata().unwrap().len(), FAR + 3);
let mut buf = [0u8; 8];
assert_eq!(io::read_at(handle_of(&file), &mut buf, FAR - 2).unwrap(), 5);
assert_eq!(&buf[..5], b"\0\0far");
assert_eq!(io::read_at(handle_of(&file), &mut buf, FAR + 3).unwrap(), 0);
assert_eq!(io::read_at(handle_of(&file), &mut buf, 3).unwrap(), 8);
assert_eq!(buf, [0; 8]);
let h = handle_of(&file);
assert_eq!(io::seek(h, SeekFrom::Start(FAR)).unwrap(), FAR);
assert_eq!((&file).stream_position().unwrap(), FAR);
assert_eq!(io::seek(h, SeekFrom::Current(1)).unwrap(), FAR + 1);
assert_eq!(io::read(h, &mut buf).unwrap(), 2);
assert_eq!(&buf[..2], b"ar");
assert_eq!(io::seek(h, SeekFrom::End(0)).unwrap(), FAR + 3);
assert_eq!(io::seek(h, SeekFrom::End(-3)).unwrap(), FAR);
assert_eq!(io::seek(h, SeekFrom::Current(-(FAR as i64))).unwrap(), 0);
assert_eq!(
io::seek(h, SeekFrom::Current((6 << 30) + 1)).unwrap(),
(6 << 30) + 1
);
assert_eq!(io::seek(h, SeekFrom::Start(FAR + 3)).unwrap(), FAR + 3);
write_all(h, b"ther");
file.seek(std::io::SeekFrom::Start(FAR)).unwrap();
let mut end = Vec::new();
file.read_to_end(&mut end).unwrap();
assert_eq!(end, b"farther");
drop(file);
std::fs::remove_file(&path).unwrap();
}
#[test]
fn seek() {
let dir = common::tmp_dir("io-seek");
let mut file = create(&dir.join("file"));
file.write_all(b"0123456789").unwrap();
let h = handle_of(&file);
assert_eq!(io::seek(h, SeekFrom::Current(0)).unwrap(), 10);
assert_eq!(io::seek(h, SeekFrom::Start(4)).unwrap(), 4);
assert_eq!((&file).stream_position().unwrap(), 4);
assert_eq!(io::seek(h, SeekFrom::Current(-3)).unwrap(), 1);
assert_eq!(io::seek(h, SeekFrom::End(-1)).unwrap(), 9);
let mut buf = [0u8; 4];
assert_eq!(io::read(h, &mut buf).unwrap(), 1);
assert_eq!(buf[0], b'9');
assert_eq!(io::seek(h, SeekFrom::End(5)).unwrap(), 15);
assert_eq!(io::read(h, &mut buf).unwrap(), 0);
assert_eq!(
io::seek(h, SeekFrom::Current(-16)).unwrap_err(),
ErrorKind::InvalidInput
);
assert_eq!(
io::seek(h, SeekFrom::End(-11)).unwrap_err(),
ErrorKind::InvalidInput
);
assert_eq!(
io::seek(h, SeekFrom::Start(u64::MAX)).unwrap_err(),
ErrorKind::InvalidInput
);
assert_eq!(io::seek(h, SeekFrom::Current(0)).unwrap(), 15);
}
#[test]
fn vectored() {
let dir = common::tmp_dir("io-vectored");
let path = dir.join("file");
let mut file = create(&path);
let parts: [&[u8]; 4] = [b"", b"one ", b"two ", b"three"];
let total: usize = parts.iter().map(|p| p.len()).sum();
let mut done = 0;
while done < total {
let mut skip = done;
let mut slices = Vec::new();
for part in parts {
let cut = skip.min(part.len());
skip -= cut;
slices.push(IoSlice::new(&part[cut..]));
}
let n = io::write_vectored(handle_of(&file), &slices).unwrap();
assert!(n > 0 && done + n <= total);
#[cfg(not(any(windows, target_os = "wasi")))]
assert_eq!(n, total);
done += n;
}
assert_eq!(std::fs::read(&path).unwrap(), b"one two three");
assert_eq!(io::write_vectored(handle_of(&file), &[]).unwrap(), 0);
assert_eq!(
io::write_vectored(handle_of(&file), &[IoSlice::new(b"")]).unwrap(),
0
);
file.rewind().unwrap();
let mut a = [0u8; 4];
let mut b = [0u8; 0];
let mut c = [0u8; 20];
let n = {
let mut bufs = [
IoSliceMut::new(&mut a),
IoSliceMut::new(&mut b),
IoSliceMut::new(&mut c),
];
io::read_vectored(handle_of(&file), &mut bufs).unwrap()
};
#[cfg(not(any(windows, target_os = "wasi")))]
{
assert_eq!(n, 13);
assert_eq!(&c[..9], b"two three");
}
#[cfg(windows)]
assert_eq!(n, 4);
assert!(n == 4 || n == 13);
assert_eq!(&a, b"one ");
assert_eq!(io::read_vectored(handle_of(&file), &mut []).unwrap(), 0);
}
#[test]
fn io_slices() {
let data = *b"abc";
let slice = IoSlice::new(&data);
assert_eq!(slice.as_slice(), b"abc");
assert_eq!(&*slice, b"abc");
assert_eq!(slice.len(), 3);
let copy = slice;
assert_eq!(format!("{copy:?}"), format!("{:?}", b"abc"));
let inner: &[u8] = IoSlice::new(&data).as_slice();
assert_eq!(inner, b"abc");
let mut buf = *b"xyz";
let mut slice = IoSliceMut::new(&mut buf);
assert_eq!(slice.as_slice(), b"xyz");
slice.as_mut_slice()[0] = b'X';
slice[1] = b'Y';
assert_eq!(&*slice, b"XYz");
assert_eq!(format!("{slice:?}"), format!("{:?}", b"XYz"));
assert_eq!(&buf, b"XYz");
#[cfg(not(windows))]
assert_eq!(size_of::<IoSlice<'_>>(), size_of::<std::io::IoSlice<'_>>());
assert_eq!(
size_of::<IoSliceMut<'_>>(),
size_of::<std::io::IoSliceMut<'_>>()
);
fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<IoSlice<'_>>();
assert_send_sync::<IoSliceMut<'_>>();
}
#[cfg(target_os = "wasi")]
#[test]
fn unsupported() {
let dir = common::tmp_dir("io-unsupported");
let file = create(&dir.join("file"));
assert_eq!(io::pipe().unwrap_err(), ErrorKind::Unsupported);
assert_eq!(
io::duplicate(handle_of(&file)).unwrap_err(),
ErrorKind::Unsupported
);
assert_eq!(
io::is_inheritable(handle_of(&file)).unwrap_err(),
ErrorKind::Unsupported
);
assert_eq!(
io::set_inheritable(handle_of(&file), true).unwrap_err(),
ErrorKind::Unsupported
);
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn pipe() {
let (reader, writer) = io::pipe().unwrap();
write_all(&writer, b"through the pipe");
let mut buf = [0u8; 64];
let n = io::read(&reader, &mut buf).unwrap();
assert_eq!(&buf[..n], b"through the pipe");
let n = io::write_vectored(&writer, &[IoSlice::new(b"ab"), IoSlice::new(b"cd")]).unwrap();
#[cfg(not(windows))]
assert_eq!(n, 4);
#[cfg(windows)]
assert_eq!(n, 2);
let mut small = [0u8; 4];
let got = io::read_vectored(&reader, &mut [IoSliceMut::new(&mut small)]).unwrap();
assert_eq!(got, n);
assert_eq!(&small[..n], &b"abcd"[..n]);
#[cfg(not(windows))]
{
assert_eq!(
io::seek(&reader, SeekFrom::Current(0)).unwrap_err(),
ErrorKind::NotSeekable
);
assert_eq!(
io::read_at(&reader, &mut buf, 0).unwrap_err(),
ErrorKind::NotSeekable
);
}
assert!(!io::is_terminal(&reader));
assert!(!io::is_terminal(&writer));
write_all(&writer, b"last");
drop(writer);
assert_eq!(read_full(&reader, &mut buf), 4);
assert_eq!(&buf[..4], b"last");
assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
let (reader, writer) = io::pipe().unwrap();
drop(reader);
assert_eq!(io::write(&writer, b"x").unwrap_err(), ErrorKind::BrokenPipe);
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn nonblocking_pipe() {
let (reader, writer) = io::pipe().unwrap();
let mut buf = [0u8; 4096];
io::set_nonblocking(&reader, true).unwrap();
let error = io::read(&reader, &mut buf).unwrap_err();
assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
let error = io::read_vectored(&reader, &mut [IoSliceMut::new(&mut buf)]).unwrap_err();
assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
write_all(&writer, b"some data");
let n = io::read(&reader, &mut buf).unwrap();
assert_eq!(&buf[..n], b"some data");
assert_eq!(
io::read(&reader, &mut buf).unwrap_err(),
ErrorKind::WouldBlock
);
io::set_nonblocking(&reader, true).unwrap();
let duplicate = io::duplicate(&reader).unwrap();
assert_eq!(
io::read(&duplicate, &mut buf).unwrap_err(),
ErrorKind::WouldBlock
);
drop(duplicate);
io::set_nonblocking(&writer, true).unwrap();
let chunk = [0x5au8; 65536];
let mut written = 0usize;
let error = loop {
match io::write(&writer, &chunk) {
Ok(n) => {
assert!(n > 0 && n <= chunk.len(), "{n} after {written}");
written += n;
assert!(written < 64 << 20, "the pipe never fills");
}
Err(error) => break error,
}
};
assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {written}");
assert!(written > 0);
let error = io::write_vectored(&writer, &[IoSlice::new(&chunk)]).unwrap_err();
assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
assert_eq!(io::write(&writer, &[]).unwrap(), 0);
let mut read = 0usize;
let error = loop {
match io::read(&reader, &mut buf) {
Ok(n) => {
assert!(n > 0);
assert!(buf[..n].iter().all(|&byte| byte == 0x5a));
read += n;
}
Err(error) => break error,
}
};
assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {read}");
assert_eq!(read, written);
assert_eq!(io::write(&writer, b"more").unwrap(), 4);
let n = io::read(&reader, &mut buf).unwrap();
assert_eq!(&buf[..n], b"more");
io::set_nonblocking(&reader, false).unwrap();
io::set_nonblocking(&writer, false).unwrap();
std::thread::scope(|scope| {
scope.spawn(|| {
std::thread::sleep(std::time::Duration::from_millis(100));
write_all(&writer, b"late");
});
let n = io::read(&reader, &mut buf).unwrap();
assert_eq!(&buf[..n], b"late");
});
io::set_nonblocking(&reader, true).unwrap();
write_all(&writer, b"last");
drop(writer);
let n = io::read(&reader, &mut buf).unwrap();
assert_eq!(&buf[..n], b"last");
assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
assert_eq!(io::read(&reader, &mut buf).unwrap(), 0);
let (reader, writer) = io::pipe().unwrap();
io::set_nonblocking(&writer, true).unwrap();
drop(reader);
let error = io::write(&writer, b"x").unwrap_err();
assert_eq!(error, ErrorKind::BrokenPipe, "{error:?}");
assert_eq!(
io::set_nonblocking(invalid_handle(), true).unwrap_err(),
ErrorKind::BadHandle
);
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn nonblocking_end_to_blocking_end() {
use std::time::{Duration, Instant};
const TOTAL: usize = 1 << 20;
let data: Vec<u8> = (0..TOTAL).map(|i| (i % 253) as u8).collect();
for (read_size, write_size) in [(4096, 65536), (65536, 4096), (300, 100_000), (100_000, 300)] {
let (reader, writer) = io::pipe().unwrap();
io::set_nonblocking(&writer, true).unwrap();
std::thread::scope(|scope| {
let received = scope.spawn(|| {
let mut all = Vec::new();
let mut buf = vec![0u8; read_size];
loop {
match io::read(&reader, &mut buf).unwrap() {
0 => return all,
n => all.extend_from_slice(&buf[..n]),
}
}
});
let mut sent = 0;
let mut last_progress = Instant::now();
while sent < TOTAL {
let end = (sent + write_size).min(TOTAL);
match io::write(&writer, &data[sent..end]) {
Ok(n) => {
assert!(n > 0 && n <= end - sent);
sent += n;
last_progress = Instant::now();
}
Err(error) => {
assert_eq!(error, ErrorKind::WouldBlock, "{error:?} after {sent}");
assert!(
last_progress.elapsed() < Duration::from_secs(20),
"nothing written for 20 s after {sent} bytes \
({read_size}, {write_size})"
);
std::thread::yield_now();
}
}
}
drop(writer);
assert!(
received.join().unwrap() == data,
"({read_size}, {write_size})"
);
});
let (reader, writer) = io::pipe().unwrap();
io::set_nonblocking(&reader, true).unwrap();
std::thread::scope(|scope| {
scope.spawn(|| {
for chunk in data.chunks(write_size) {
write_all(&writer, chunk);
}
drop(writer);
});
let mut all = Vec::new();
let mut buf = vec![0u8; read_size];
let mut last_progress = Instant::now();
loop {
match io::read(&reader, &mut buf) {
Ok(0) => break,
Ok(n) => {
all.extend_from_slice(&buf[..n]);
last_progress = Instant::now();
}
Err(error) => {
assert_eq!(error, ErrorKind::WouldBlock, "{error:?}");
assert!(
last_progress.elapsed() < Duration::from_secs(20),
"nothing read for 20 s after {} bytes ({read_size}, {write_size})",
all.len()
);
std::thread::yield_now();
}
}
}
assert!(all == data, "({read_size}, {write_size})");
});
}
}
#[test]
fn nonblocking_file() {
let dir = common::tmp_dir("io-nonblocking-file");
let file = create(&dir.join("file"));
let handle = handle_of(&file);
let result = io::set_nonblocking(handle, true);
if cfg!(windows) {
let error = result.unwrap_err();
eprintln!("set_nonblocking on a file: {error:?}");
} else {
result.unwrap();
io::set_nonblocking(handle, false).unwrap();
}
write_all(handle, b"content");
io::seek(handle, SeekFrom::Start(0)).unwrap();
let mut buf = [0u8; 16];
assert_eq!(read_full(handle, &mut buf), 7);
assert_eq!(io::read(handle, &mut buf).unwrap(), 0);
assert_eq!(
io::set_nonblocking(invalid_handle(), false).unwrap_err(),
ErrorKind::BadHandle
);
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn pipe_between_threads() {
let (reader, writer) = io::pipe().unwrap();
let total = 1 << 20; let thread = std::thread::spawn(move || {
let chunk: Vec<u8> = (0..4096u32).map(|i| i as u8).collect();
for _ in 0..total / chunk.len() {
write_all(&writer, &chunk);
}
});
let mut buf = vec![0u8; 10000];
let mut received = 0usize;
loop {
let n = io::read(&reader, &mut buf).unwrap();
if n == 0 {
break;
}
for (i, &byte) in buf[..n].iter().enumerate() {
assert_eq!(byte, ((received + i) % 4096) as u8);
}
received += n;
}
assert_eq!(received, total);
thread.join().unwrap();
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn duplicate() {
let dir = common::tmp_dir("io-duplicate");
let path = dir.join("file");
let mut file = create(&path);
file.write_all(b"0123456789").unwrap();
file.rewind().unwrap();
let dup = io::duplicate(handle_of(&file)).unwrap();
assert_ne!(dup.as_raw(), handle_of(&file).as_raw());
assert!(!io::is_inheritable(&dup).unwrap());
let mut buf = [0u8; 4];
assert_eq!(io::read(&dup, &mut buf).unwrap(), 4);
assert_eq!(file.stream_position().unwrap(), 4);
file.seek(std::io::SeekFrom::Start(8)).unwrap();
assert_eq!(io::read(&dup, &mut buf).unwrap(), 2);
assert_eq!(&buf[..2], b"89");
drop(file);
write_all(&dup, b"ab");
let again = io::duplicate(&dup).unwrap();
drop(dup);
assert_eq!(io::seek(&again, SeekFrom::Current(0)).unwrap(), 12);
assert_eq!(std::fs::read(&path).unwrap(), b"0123456789ab");
let (reader, writer) = io::pipe().unwrap();
let writer2 = io::duplicate(&writer).unwrap();
drop(writer);
write_all(&writer2, b"x");
drop(writer2);
assert_eq!(read_full(&reader, &mut buf), 1);
}
#[cfg(not(target_os = "wasi"))]
#[test]
fn inheritable() {
let (reader, writer) = io::pipe().unwrap();
assert!(!io::is_inheritable(&reader).unwrap());
assert!(!io::is_inheritable(&writer).unwrap());
let dir = common::tmp_dir("io-inheritable");
let file = create(&dir.join("file"));
assert!(!io::is_inheritable(handle_of(&file)).unwrap());
io::set_inheritable(&reader, true).unwrap();
assert!(io::is_inheritable(&reader).unwrap());
assert!(!io::is_inheritable(&writer).unwrap());
let dup = io::duplicate(&reader).unwrap();
assert!(!io::is_inheritable(&dup).unwrap());
io::set_inheritable(&reader, true).unwrap();
assert!(io::is_inheritable(&reader).unwrap());
io::set_inheritable(&reader, false).unwrap();
assert!(!io::is_inheritable(&reader).unwrap());
io::set_inheritable(&reader, false).unwrap();
assert!(!io::is_inheritable(&reader).unwrap());
}
#[test]
fn standard_handles() {
use std::io::IsTerminal;
let stdin = io::stdin().unwrap();
let stdout = io::stdout().unwrap();
let stderr = io::stderr().unwrap();
#[cfg(not(windows))]
{
assert_eq!(stdin.as_raw(), 0);
assert_eq!(stdout.as_raw(), 1);
assert_eq!(stderr.as_raw(), 2);
}
#[cfg(windows)]
{
use std::os::windows::io::AsRawHandle;
assert_eq!(stdin.as_raw(), std::io::stdin().as_raw_handle());
assert_eq!(stdout.as_raw(), std::io::stdout().as_raw_handle());
assert_eq!(stderr.as_raw(), std::io::stderr().as_raw_handle());
}
assert_eq!(io::is_terminal(stdin), std::io::stdin().is_terminal());
assert_eq!(io::is_terminal(stdout), std::io::stdout().is_terminal());
assert_eq!(io::is_terminal(stderr), std::io::stderr().is_terminal());
assert_eq!(io::write(stderr, b"").unwrap(), 0);
let dir = common::tmp_dir("io-standard-handles");
let file = create(&dir.join("file"));
assert!(!io::is_terminal(handle_of(&file)));
}
#[cfg(windows)]
mod overlapped {
use std::ffi::c_void;
use std::fs::File;
use std::os::windows::ffi::OsStrExt;
use std::os::windows::fs::OpenOptionsExt;
use std::os::windows::io::FromRawHandle;
use std::path::PathBuf;
use std::thread;
use std::time::{Duration, Instant};
use oscall::io;
use super::common::{self, handle_of};
const FILE_FLAG_OVERLAPPED: u32 = 0x4000_0000;
const PIPE_ACCESS_DUPLEX: u32 = 3;
const PIPE_TYPE_MESSAGE: u32 = 4;
const PIPE_READMODE_MESSAGE: u32 = 2;
const GENERIC_READ: u32 = 0x8000_0000;
const GENERIC_WRITE: u32 = 0x4000_0000;
const OPEN_EXISTING: u32 = 3;
const ERROR_INVALID_PARAMETER: i32 = 87;
const SETTLE: Duration = Duration::from_millis(300);
#[link(name = "kernel32")]
unsafe extern "system" {
fn CreateNamedPipeW(
name: *const u16,
open_mode: u32,
pipe_mode: u32,
max_instances: u32,
out_buffer_size: u32,
in_buffer_size: u32,
default_timeout: u32,
security: *const c_void,
) -> *mut c_void;
fn CreateFileW(
name: *const u16,
access: u32,
share: u32,
security: *const c_void,
creation: u32,
flags: u32,
template: *mut c_void,
) -> *mut c_void;
}
fn pipe_pair(name: &str, flags: u32, mode: u32) -> (File, File) {
let name = format!(r"\\.\pipe\oscall-test-{}-{name}", std::process::id());
let name: Vec<u16> = std::ffi::OsStr::new(&name)
.encode_wide()
.chain([0])
.collect();
unsafe {
let server = CreateNamedPipeW(
name.as_ptr(),
PIPE_ACCESS_DUPLEX | flags,
mode,
1,
4096,
4096,
0,
std::ptr::null(),
);
assert_ne!(server as isize, -1, "{}", std::io::Error::last_os_error());
let server = File::from_raw_handle(server);
let client = CreateFileW(
name.as_ptr(),
GENERIC_READ | GENERIC_WRITE,
0,
std::ptr::null(),
OPEN_EXISTING,
flags,
std::ptr::null_mut(),
);
assert_ne!(client as isize, -1, "{}", std::io::Error::last_os_error());
(server, File::from_raw_handle(client))
}
}
fn overlapped_file(name: &str) -> (File, PathBuf) {
let path = common::tmp_dir(name).join("file");
let file = File::options()
.read(true)
.write(true)
.create(true)
.truncate(true)
.custom_flags(FILE_FLAG_OVERLAPPED)
.open(&path)
.unwrap();
(file, path)
}
#[test]
fn file_at_offsets() {
let (file, path) = overlapped_file("io-overlapped-file");
let handle = handle_of(&file);
assert_eq!(io::write_at(handle, b"hello world", 0).unwrap(), 11);
assert_eq!(io::write_at(handle, b"HELLO", 100).unwrap(), 5);
let mut buf = [0xffu8; 32];
assert_eq!(io::read_at(handle, &mut buf, 0).unwrap(), 32);
assert_eq!(&buf[..11], b"hello world");
assert_eq!(&buf[11..], &[0; 21]);
assert_eq!(io::read_at(handle, &mut buf, 98).unwrap(), 7);
assert_eq!(&buf[..7], b"\0\0HELLO");
assert_eq!(io::read_at(handle, &mut buf, 105).unwrap(), 0);
assert_eq!(io::read_at(handle, &mut buf, 1 << 40).unwrap(), 0);
assert_eq!(std::fs::metadata(path).unwrap().len(), 105);
}
#[test]
fn file_without_offset() {
let (file, _) = overlapped_file("io-overlapped-file-no-offset");
let handle = handle_of(&file);
assert_eq!(io::write_at(handle, b"0123456789", 0).unwrap(), 10);
let mut buf = [0xffu8; 4];
let read = io::read(handle, &mut buf).map_err(|e| e.raw_os_error());
assert_eq!(read, Err(ERROR_INVALID_PARAMETER), "read: {read:?}");
assert_eq!(buf, [0xff; 4]);
let written = io::write(handle, b"abcd").map_err(|e| e.raw_os_error());
assert_eq!(written, Err(ERROR_INVALID_PARAMETER), "write: {written:?}");
let mut buf = [0u8; 16];
assert_eq!(io::read_at(handle, &mut buf, 0).unwrap(), 10);
assert_eq!(&buf[..10], b"0123456789");
}
#[test]
fn file_from_several_threads() {
let (file, _) = overlapped_file("io-overlapped-file-threads");
thread::scope(|scope| {
for thread in 0..4u8 {
let file = &file;
scope.spawn(move || {
let handle = handle_of(file);
let block = [b'a' + thread; 8192];
let mut buf = [0u8; 8192];
for round in 0..64u64 {
let offset = (round * 4 + u64::from(thread)) * 8192;
assert_eq!(io::write_at(handle, &block, offset).unwrap(), 8192);
assert_eq!(io::read_at(handle, &mut buf, offset).unwrap(), 8192);
assert!(buf == block, "thread {thread}, round {round}");
buf.fill(0);
}
});
}
});
}
#[test]
fn pipe_read_completes_later() {
let (server, client) = pipe_pair("later", FILE_FLAG_OVERLAPPED, 0);
thread::scope(|scope| {
scope.spawn(|| {
thread::sleep(SETTLE);
assert_eq!(io::write(handle_of(&client), b"late").unwrap(), 4);
});
let start = Instant::now();
let mut buf = [0u8; 16];
let read = io::read(handle_of(&server), &mut buf);
let elapsed = start.elapsed();
let read = read.map_err(|e| e.raw_os_error());
assert_eq!(read, Ok(4), "read: {read:?} after {elapsed:?}");
assert_eq!(&buf[..4], b"late");
assert!(elapsed >= SETTLE - Duration::from_millis(50), "{elapsed:?}");
});
assert_eq!(io::write(handle_of(&server), b"back").unwrap(), 4);
let mut buf = [0u8; 16];
assert_eq!(io::read(handle_of(&client), &mut buf).unwrap(), 4);
assert_eq!(&buf[..4], b"back");
drop(client);
assert_eq!(io::read(handle_of(&server), &mut buf).unwrap(), 0);
}
#[test]
fn pipe_read_among_other_operations() {
let (server, client) = pipe_pair("among", FILE_FLAG_OVERLAPPED, 0);
thread::scope(|scope| {
let reader = scope.spawn(|| {
let start = Instant::now();
let mut buf = [0u8; 16];
let read = io::read(handle_of(&server), &mut buf);
let elapsed = start.elapsed();
let read = read.map_err(|e| e.raw_os_error());
assert_eq!(read, Ok(4), "read: {read:?} after {elapsed:?}");
assert_eq!(&buf[..4], b"done");
elapsed
});
let start = Instant::now();
let mut buf = [0u8; 16];
while start.elapsed() < SETTLE {
assert_eq!(io::write(handle_of(&server), b"noise").unwrap(), 5);
assert_eq!(io::read(handle_of(&client), &mut buf).unwrap(), 5);
assert_eq!(&buf[..5], b"noise");
thread::sleep(Duration::from_millis(5));
}
assert!(!reader.is_finished());
assert_eq!(io::write(handle_of(&client), b"done").unwrap(), 4);
let elapsed = reader.join().unwrap();
assert!(elapsed >= SETTLE - Duration::from_millis(50), "{elapsed:?}");
});
}
#[test]
fn message_pipe_in_pieces() {
for (name, flags) in [("message", 0), ("message-ov", FILE_FLAG_OVERLAPPED)] {
let mode = PIPE_TYPE_MESSAGE | PIPE_READMODE_MESSAGE;
let (server, client) = pipe_pair(name, flags, mode);
assert_eq!(io::write(handle_of(&client), b"0123456789").unwrap(), 10);
assert_eq!(io::write(handle_of(&client), b"abc").unwrap(), 3);
let read = |len: usize| {
let mut buf = [0u8; 16];
let result = io::read(handle_of(&server), &mut buf[..len]);
let done = result.unwrap_or_else(|e| panic!("{name}: {}", e.raw_os_error()));
buf[..done].to_vec()
};
assert_eq!(read(4), b"0123");
assert_eq!(read(4), b"4567");
assert_eq!(read(4), b"89");
assert_eq!(read(16), b"abc");
}
}
}