| 51 | #[cfg(feature = "fs")] |
| 52 | #[allow(unsafe_code)] |
| 53 | fn _ttyname(fd: BorrowedFd<'_>, mut buffer: Vec<u8>) -> io::Result<CString> { |
| 54 | buffer.clear(); |
| 55 | buffer.reserve(SMALL_PATH_BUFFER_SIZE); |
| 56 | |
| 57 | loop { |
| 58 | match backend::termios::syscalls::ttyname(fd, buffer.spare_capacity_mut()) { |
| 59 | Err(io::Errno::RANGE) => { |
| 60 | // Use `Vec` reallocation strategy to grow capacity |
| 61 | // exponentially. |
| 62 | buffer.reserve(buffer.capacity() + 1); |
| 63 | } |
| 64 | Ok(len) => { |
| 65 | // SAFETY: Assume the backend returns the length of the string |
| 66 | // excluding the NUL. |
| 67 | unsafe { |
| 68 | buffer.set_len(len + 1); |
| 69 | } |
| 70 | |
| 71 | // SAFETY: |
| 72 | // - “ttyname_r stores this pathname in the buffer buf” |
| 73 | // - [POSIX definition 3.271: Pathname]: “A string that is |
| 74 | // used to identify a file.” |
| 75 | // - [POSIX definition 3.375: String]: “A contiguous sequence |
| 76 | // of bytes terminated by and including the first null byte.” |
| 77 | // |
| 78 | // Thus, there will be a single NUL byte at the end of the |
| 79 | // string. |
| 80 | // |
| 81 | // [POSIX definition 3.271: Pathname]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap03.html#tag_03_271 |
| 82 | // [POSIX definition 3.375: String]: https://pubs.opengroup.org/onlinepubs/9799919799/basedefs/V1_chap03.html#tag_03_375 |
| 83 | unsafe { |
| 84 | return Ok(CString::from_vec_with_nul_unchecked(buffer)); |
| 85 | } |
| 86 | } |
| 87 | Err(errno) => return Err(errno), |
| 88 | } |
| 89 | } |
| 90 | } |