Skip to main content

proctor_libc/stdio/
mod.rs

1//! Safe equivalents of functions declared in C's `stdio.h` header.
2
3pub mod printf;
4
5use std::io::{self, BufRead, Read, Seek, SeekFrom, Write};
6use std::{mem, ptr};
7
8#[cfg(target_os = "linux")]
9use std::{ffi::OsStr, fs, os::unix::ffi::OsStrExt, path::Path};
10
11/// Reads the next byte from `r`.
12///
13/// Returns the byte and success, `-1` and success at end-of-file, or `-1` and
14/// the I/O error.
15pub fn fgetc<R: Read + ?Sized>(r: &mut R) -> (i32, io::Result<()>) {
16    let mut byte = [0];
17
18    match r.read(&mut byte) {
19        Ok(0) => (-1, Ok(())),
20        Ok(_) => (i32::from(byte[0]), Ok(())),
21        Err(error) => (-1, Err(error)),
22    }
23}
24
25/// Writes `c`, converted to an unsigned byte, to `w`.
26///
27/// Returns the written byte and success, or `-1` and the I/O error.
28pub fn fputc<W: Write + ?Sized>(c: i32, w: &mut W) -> (i32, io::Result<()>) {
29    let byte = c as u8;
30
31    match w.write(&[byte]) {
32        Ok(0) => (
33            -1,
34            Err(io::Error::new(
35                io::ErrorKind::WriteZero,
36                "failed to write byte",
37            )),
38        ),
39        Ok(_) => (i32::from(byte), Ok(())),
40        Err(error) => (-1, Err(error)),
41    }
42}
43
44/// Writes the bytes in `buf` preceding the first null byte to `w`.
45///
46/// Returns zero and success, or `-1` and the I/O error.
47pub fn fputs<W: Write + ?Sized>(buf: &[i8], w: &mut W) -> (i32, io::Result<()>) {
48    let len = buf.iter().position(|&byte| byte == 0).unwrap_or(buf.len());
49    let mut bytes: &[u8] = bytemuck::cast_slice(&buf[..len]);
50
51    while !bytes.is_empty() {
52        match w.write(bytes) {
53            Ok(0) => {
54                return (
55                    -1,
56                    Err(io::Error::new(
57                        io::ErrorKind::WriteZero,
58                        "failed to write string",
59                    )),
60                );
61            }
62            Ok(written) => bytes = &bytes[written..],
63            Err(error) => return (-1, Err(error)),
64        }
65    }
66
67    (0, Ok(()))
68}
69
70/// Reads the next byte from standard input.
71///
72/// Returns the byte and success, `-1` and success at end-of-file, or `-1` and
73/// the I/O error.
74pub fn getchar() -> (i32, io::Result<()>) {
75    let stdin = io::stdin();
76    fgetc(&mut stdin.lock())
77}
78
79/// Writes `c`, converted to an unsigned byte, to standard output.
80///
81/// Returns the written byte and success, or `-1` and the I/O error.
82pub fn putchar(c: i32) -> (i32, io::Result<()>) {
83    let stdout = io::stdout();
84    fputc(c, &mut stdout.lock())
85}
86
87/// Writes the bytes in `buf` preceding the first null byte, followed by a
88/// newline, to standard output.
89///
90/// Returns zero and success, or `-1` and the I/O error.
91pub fn puts(buf: &[i8]) -> (i32, io::Result<()>) {
92    let stdout = io::stdout();
93    let mut stdout = stdout.lock();
94
95    if let Err(error) = fputs(buf, &mut stdout).1 {
96        return (-1, Err(error));
97    }
98    if let Err(error) = fputc(i32::from(b'\n'), &mut stdout).1 {
99        return (-1, Err(error));
100    }
101
102    (0, Ok(()))
103}
104
105/// Sets the position of `s` according to `pos`.
106///
107/// Returns zero and success, or `-1` and the seek or position-conversion error.
108pub fn fseek<S: Seek + ?Sized>(s: &mut S, pos: SeekFrom) -> (i32, io::Result<()>) {
109    let position = match s.seek(pos) {
110        Ok(position) => position,
111        Err(error) => return (-1, Err(error)),
112    };
113    if i64::try_from(position).is_err() {
114        return (
115            -1,
116            Err(io::Error::new(
117                io::ErrorKind::InvalidData,
118                "stream position does not fit in i64",
119            )),
120        );
121    }
122
123    (0, Ok(()))
124}
125
126/// Returns the current position of `s` as a byte offset from its beginning.
127///
128/// Returns the offset and success, or `-1` and the seek or position-conversion
129/// error.
130pub fn ftell<S: Seek + ?Sized>(s: &mut S) -> (i64, io::Result<()>) {
131    let position = match s.stream_position() {
132        Ok(position) => position,
133        Err(error) => return (-1, Err(error)),
134    };
135
136    match i64::try_from(position) {
137        Ok(position) => (position, Ok(())),
138        Err(_) => (
139            -1,
140            Err(io::Error::new(
141                io::ErrorKind::InvalidData,
142                "stream position does not fit in i64",
143            )),
144        ),
145    }
146}
147
148/// Sets the position of `s` to its beginning.
149pub fn rewind<S: Seek + ?Sized>(s: &mut S) -> io::Result<()> {
150    fseek(s, SeekFrom::Start(0)).1
151}
152
153/// Removes the file or empty directory named by `path`.
154///
155/// Returns zero and success, or `-1` and the filesystem error.
156#[cfg(target_os = "linux")]
157pub fn remove(path: &[i8]) -> (i32, io::Result<()>) {
158    let path = c_path(path);
159
160    match fs::remove_file(path) {
161        Ok(()) => (0, Ok(())),
162        Err(error) if error.kind() == io::ErrorKind::IsADirectory => match fs::remove_dir(path) {
163            Ok(()) => (0, Ok(())),
164            Err(error) => (-1, Err(error)),
165        },
166        Err(error) => (-1, Err(error)),
167    }
168}
169
170#[cfg(target_os = "linux")]
171fn c_path(path: &[i8]) -> &Path {
172    let len = path.iter().position(|&byte| byte == 0).unwrap();
173    Path::new(OsStr::from_bytes(bytemuck::cast_slice(&path[..len])))
174}
175
176/// Renames the file or directory named by `old` to `new`.
177///
178/// Returns zero and success, or `-1` and the filesystem error.
179#[cfg(target_os = "linux")]
180pub fn rename(old: &[i8], new: &[i8]) -> (i32, io::Result<()>) {
181    match fs::rename(c_path(old), c_path(new)) {
182        Ok(()) => (0, Ok(())),
183        Err(error) => (-1, Err(error)),
184    }
185}
186
187/// Reads a line from `r` into `buf`, including the newline and a trailing null byte.
188///
189/// Returns the buffer and success when it writes a null terminator, `None` and
190/// success at end-of-file before any input, or `None` and an error.
191pub fn fgets<'buf, R: BufRead + ?Sized>(
192    buf: &'buf mut [i8],
193    r: &mut R,
194) -> (Option<&'buf mut [i8]>, io::Result<()>) {
195    if buf.is_empty() {
196        return (
197            None,
198            Err(io::Error::new(
199                io::ErrorKind::InvalidInput,
200                "buffer must have room for a null byte",
201            )),
202        );
203    }
204
205    if buf.len() == 1 {
206        buf[0] = 0;
207        return (Some(buf), Ok(()));
208    }
209
210    let bytes: &mut [u8] = bytemuck::cast_slice_mut(buf);
211    let mut written = 0;
212
213    while written < bytes.len() - 1 {
214        let available = match r.fill_buf() {
215            Ok(available) => available,
216            Err(error) => return (None, Err(error)),
217        };
218        if available.is_empty() {
219            if written == 0 {
220                return (None, Ok(()));
221            }
222            break;
223        }
224
225        let available_len = available.len().min(bytes.len() - 1 - written);
226        let newline = available[..available_len]
227            .iter()
228            .position(|&byte| byte == b'\n');
229        let copied = newline.map_or(available_len, |index| index + 1);
230
231        bytes[written..written + copied].copy_from_slice(&available[..copied]);
232        written += copied;
233        r.consume(copied);
234
235        if newline.is_some() {
236            break;
237        }
238    }
239
240    bytes[written] = 0;
241    (Some(buf), Ok(()))
242}
243
244/// Reads binary input from `r` into `buf`.
245///
246/// Returns the number of complete elements read and any I/O error. A short
247/// count without an error means end-of-file.
248pub fn fread<T: bytemuck::AnyBitPattern, R: BufRead + ?Sized>(
249    buf: &mut [T],
250    r: &mut R,
251) -> (usize, io::Result<()>) {
252    let element_size = mem::size_of::<T>();
253    if element_size == 0 || buf.is_empty() {
254        return (0, Ok(()));
255    }
256
257    let byte_len = mem::size_of_val(buf);
258    let destination = buf.as_mut_ptr().cast::<u8>();
259    let mut bytes_read = 0;
260
261    while bytes_read < byte_len {
262        let available = match r.fill_buf() {
263            Ok([]) => break,
264            Ok(available) => available,
265            Err(error) => return (bytes_read / element_size, Err(error)),
266        };
267        let copied = available.len().min(byte_len - bytes_read);
268
269        // SAFETY: `destination` covers all `byte_len` bytes occupied by `buf`,
270        // and `copied` is limited to the unwritten portion. `AnyBitPattern`
271        // guarantees that changing any subset of an element's bytes leaves a
272        // valid `T`, including when the read ends with a partial element.
273        unsafe {
274            ptr::copy_nonoverlapping(available.as_ptr(), destination.add(bytes_read), copied);
275        }
276
277        bytes_read += copied;
278        r.consume(copied);
279    }
280
281    (bytes_read / element_size, Ok(()))
282}
283
284/// Writes binary output from `buf` to `w`.
285///
286/// Returns the number of complete elements written and any I/O error.
287pub fn fwrite<T: bytemuck::NoUninit, W: Write + ?Sized>(
288    buf: &[T],
289    w: &mut W,
290) -> (usize, io::Result<()>) {
291    let element_size = mem::size_of::<T>();
292    if element_size == 0 || buf.is_empty() {
293        return (0, Ok(()));
294    }
295
296    let bytes: &[u8] = bytemuck::cast_slice(buf);
297    let mut bytes_written = 0;
298
299    while bytes_written < bytes.len() {
300        match w.write(&bytes[bytes_written..]) {
301            Ok(0) => {
302                return (
303                    bytes_written / element_size,
304                    Err(io::Error::new(
305                        io::ErrorKind::WriteZero,
306                        "failed to write buffer",
307                    )),
308                );
309            }
310            Ok(written) => bytes_written += written,
311            Err(error) => return (bytes_written / element_size, Err(error)),
312        }
313    }
314
315    (buf.len(), Ok(()))
316}
317
318#[cfg(test)]
319mod tests;