Skip to main content

libc/
stdio.rs

1// Copyright 2026 The Fuchsia Authors
2//
3// Use of this source code is governed by a MIT-style
4// license that can be found in the LICENSE file or at
5// https://opensource.org/licenses/MIT
6
7use core::ffi::{c_char, c_int, c_void};
8use core::fmt;
9use core::mem::{align_of, size_of};
10
11/// This represents the kernel `<stdio.h>` `FILE` type.
12#[repr(C)]
13pub struct FILE {
14    write: Option<unsafe extern "C" fn(*mut c_void, *const c_char, usize) -> c_int>,
15    ptr: *mut c_void,
16}
17
18const _: () = {
19    assert!(size_of::<FILE>() == 16);
20    assert!(align_of::<FILE>() == 8);
21};
22
23impl fmt::Write for FILE {
24    fn write_str(&mut self, s: &str) -> fmt::Result {
25        let Some(write) = self.write else {
26            return Err(fmt::Error);
27        };
28        if s.is_empty() {
29            return Ok(());
30        }
31        let c_chars = s.as_ptr().cast::<c_char>();
32        // SAFETY:
33        // - `self.ptr` is the context uniquely paired with `write` by the C API.
34        // - `s` is not empty, so `c_chars` points to a valid sequence of `s.len()` bytes.
35        // - The `s` memory region remains valid and immutable for the duration of the FFI call.
36        let ret = unsafe { write(self.ptr, c_chars, s.len()) };
37        if ret < 0 { Err(fmt::Error) } else { Ok(()) }
38    }
39}