devela/sys/os/linux/fns/
write.rs

1// devela::sys::os::linux::fns::write
2//
3//! write related functions
4//
5
6use super::{linux_sys_exit, linux_sys_write, LINUX_FILENO as FILENO};
7
8/// Prints a string slice to standard output.
9///
10/// This function makes use of [`linux_sys_write`].
11///
12/// # Error Handling
13/// If the write fails, it prints an error message and exits with status code 10.
14pub fn linux_print(s: &str) {
15    let mut s = s.as_bytes();
16    while !s.is_empty() {
17        let n = unsafe { linux_sys_write(FILENO::STDOUT, s.as_ptr(), s.len()) };
18        if n < 0 || n as usize > s.len() {
19            linux_print("write failed");
20            unsafe { linux_sys_exit(10) };
21        }
22        // Update the byte slice to exclude the bytes that have been written
23        s = &s[n as usize..];
24    }
25}
26
27/// Prints a string slice to standard output, with a newline.
28///
29/// This function makes use of [`linux_sys_write`].
30///
31/// # Error Handling
32/// If the write fails, it prints an error message and exits with status code 10.
33pub fn linux_println(s: &str) {
34    linux_print(s);
35    linux_print("\n");
36}
37
38/// Prints a string slice to standard error.
39///
40/// This function makes use of [`linux_sys_write`].
41///
42/// # Error Handling
43/// If the write fails, it prints an error message and exits with status code 10.
44pub fn linux_eprint(s: &str) {
45    let mut s = s.as_bytes();
46    while !s.is_empty() {
47        let n = unsafe { linux_sys_write(FILENO::STDERR, s.as_ptr(), s.len()) };
48        if n < 0 || n as usize > s.len() {
49            linux_print("write failed");
50            unsafe { linux_sys_exit(10) };
51        }
52        // Update the byte slice to exclude the bytes that have been written
53        s = &s[n as usize..];
54    }
55}
56
57/// Prints a string slice to standard error, with a newline.
58///
59/// This function makes use of the [`linux_sys_write`] syscall to print a string.
60///
61/// # Error Handling
62/// If the write fails, it prints an error message and exits with status code 10.
63pub fn linux_eprintln(s: &str) {
64    linux_eprint(s);
65    linux_eprint("\n");
66}
67
68/// Prints a byte slice to *stdout*.
69///
70/// This function makes use of the [`linux_sys_write`] syscall to print bytes.
71///
72/// # Error Handling
73/// If the write fails, it prints an error message and exits with status code 10.
74pub fn linux_print_bytes(b: &[u8]) {
75    let mut b = b;
76    while !b.is_empty() {
77        let n = unsafe { linux_sys_write(FILENO::STDOUT, b.as_ptr(), b.len()) };
78        if n < 0 || n as usize > b.len() {
79            linux_print("write failed");
80            unsafe { linux_sys_exit(10) };
81        }
82        // Update the byte slice to exclude the bytes that have been written
83        b = &b[n as usize..];
84    }
85}