1#![cfg_attr(not(io_safety_is_in_std), allow(unused_imports))]
2#![cfg(feature = "close")]
3
4#[cfg(any(unix, windows))]
5use io_lifetimes::example_ffi::*;
6#[cfg(windows)]
7use io_lifetimes::{InvalidHandleError, OwnedHandle};
8#[cfg(windows)]
9use std::{convert::TryInto, os::windows::io::RawHandle, ptr::null_mut};
10#[cfg(windows)]
11use windows_sys::Win32::Storage::FileSystem::{
12    FILE_ATTRIBUTE_NORMAL, FILE_GENERIC_READ, OPEN_EXISTING,
13};
14
15#[cfg(all(io_safety_is_in_std, unix))]
16#[test]
17fn test_file_not_found() {
18    assert!(unsafe {
19        open(
20            "/dev/no/such/file\0".as_ptr() as *const _,
21            O_RDONLY | O_CLOEXEC,
22        )
23    }
24    .is_none());
25}
26
27#[cfg(windows)]
28#[test]
29fn test_file_not_found() {
30    let handle: Result<OwnedHandle, InvalidHandleError> = unsafe {
31        CreateFileW(
32            [
33                'C' as u16, ':' as _, '/' as _, 'n' as _, 'o' as _, '/' as _, 's' as _, 'u' as _,
34                'c' as _, 'h' as _, '/' as _, 'f' as _, 'i' as _, 'l' as _, 'e' as _, 0,
35            ]
36            .as_ptr(),
37            FILE_GENERIC_READ,
38            0,
39            null_mut(),
40            OPEN_EXISTING,
41            FILE_ATTRIBUTE_NORMAL,
42            null_mut() as RawHandle as HANDLE,
43        )
44    }
45    .try_into();
46    assert!(handle.is_err());
47    assert_eq!(
48        std::io::Error::last_os_error().kind(),
49        std::io::ErrorKind::NotFound
50    );
51}
52
53#[cfg(all(io_safety_is_in_std, unix))]
54#[test]
55fn test_file_found() {
56    assert!(unsafe { open("Cargo.toml\0".as_ptr() as *const _, O_RDONLY | O_CLOEXEC) }.is_some());
57}
58
59#[cfg(windows)]
60#[test]
61fn test_file_found() {
62    let handle: Result<OwnedHandle, InvalidHandleError> = unsafe {
63        CreateFileW(
64            [
65                'C' as u16, 'a' as _, 'r' as _, 'g' as _, 'o' as _, '.' as _, 't' as _, 'o' as _,
66                'm' as _, 'l' as _, 0,
67            ]
68            .as_ptr(),
69            FILE_GENERIC_READ,
70            0,
71            null_mut(),
72            OPEN_EXISTING,
73            FILE_ATTRIBUTE_NORMAL,
74            null_mut() as RawHandle as HANDLE,
75        )
76    }
77    .try_into();
78    assert!(handle.is_ok());
79}
80