### get example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSlice.html Demonstrates safe indexing of a slice using positions or ranges. ```rust let v = [10, 40, 30]; assert_eq!(Some(&40), v.get(1)); assert_eq!(Some(&[10, 40][..]), v.get(0..2)); assert_eq!(None, v.get(3)); assert_eq!(None, v.get(0..4)); ``` -------------------------------- ### Example for MetadataExt::size Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the total size of the file in bytes. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let file_size = meta.size(); Ok(()) } ``` -------------------------------- ### read_at example Source: https://docs.rs/rustix/latest/rustix/fs/trait.FileExt.html Example for read_at: reads 8 bytes from offset 10, prints the number of bytes read and the buffer. The offset is relative to the file start and does not affect the file cursor. ```rust use std::io; use std::fs::File; use std::os::unix::prelude::FileExt; fn main() -> io::Result<()> { let mut buf = [0u8; 8]; let file = File::open("foo.txt")?; // We now read 8 bytes from the offset 10. let num_bytes_read = file.read_at(&mut buf, 10)?; println!("read {num_bytes_read} bytes: {buf:?}"); Ok(()) } ``` -------------------------------- ### Example for MetadataExt::nlink Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the number of hard links. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let nb_hard_links = meta.nlink(); Ok(()) } ``` -------------------------------- ### write_at example Source: https://docs.rs/rustix/latest/rustix/fs/trait.FileExt.html Example for write_at: writes the bytes "sushi" at offset 10 in a newly created file. The offset is relative to the file start and does not affect the file cursor. ```rust use std::fs::File; use std::io; use std::os::unix::prelude::FileExt; fn main() -> io::Result<()> { let file = File::create("foo.txt")?; // We now write at the offset 10. file.write_at(b"sushi", 10)?; Ok(()) } ``` -------------------------------- ### Example: Using RawDir with a stack buffer (non-per) Source: https://docs.rs/rustix/latest/src/rustix/fs/raw_dir.rs.html Alternate simple non-portable example using a fixed-size array of MaybeUninit::uninit() of 2048 elements. Uses the same openat pattern and prints each entry. ```rust let fd = openat( CWD, cstr!("."), OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC, Mode::empty(), ) .unwrap(); let mut buf = [MaybeUninit::uninit(); 2048]; let mut iter = RawDir::new(fd, &mut buf); while let Some(entry) = iter.next() { let entry = entry.unwrap(); dbg!(&entry); } ``` -------------------------------- ### Example: Using IntoRawFd with File Source: https://docs.rs/rustix/latest/rustix/fd/trait.IntoRawFd.html Example from the documentation showing how to consume a File and obtain its raw file descriptor using into_raw_fd. The example uses cfg attributes to conditionally import the trait on Unix and WASI. ```rust use std::fs::File; #[cfg(any(unix, target_os = "wasi"))] use std::os::fd::{IntoRawFd, RawFd}; let f = File::open("foo.txt")?; #[cfg(any(unix, target_os = "wasi"))] let raw_fd: RawFd = f.into_raw_fd(); ``` -------------------------------- ### is_documentation method example (nightly) Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_documentation method, a nightly-only experimental API, available on non-WASI, showing it returns true for documentation-designated addresses. ```rust #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_documentation(), true); assert_eq!( IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_documentation(), true ); ``` -------------------------------- ### Example: implementing AsRawFd on Arc Source: https://docs.rs/rustix/latest/rustix/fd/trait.AsRawFd.html Example showing how to implement a trait that requires AsRawFd on Arc and Box. ```rust use std::net::UdpSocket; use std::sync::Arc; trait MyTrait: AsRawFd { } impl MyTrait for Arc {} impl MyTrait for Box {} ``` -------------------------------- ### is_benchmarking method example (nightly) Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_benchmarking method, a nightly-only experimental API, available on non-WASI, showing it returns true for benchmarking-designated addresses. ```rust #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(198, 19, 255, 255)).is_benchmarking(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0x2, 0, 0, 0, 0, 0, 0)).is_benchmarking(), true); ``` -------------------------------- ### Example: touch function using Arg Source: https://docs.rs/rustix/latest/rustix/path/trait.Arg.html Shows how to use the `Arg` trait to accept various path types and convert them to a `CStr` for further processing. The example defines a `touch` function that calls `into_c_str` and then a private `_touch` implementation. ```rust use rustix::ffi::CStr; use rustix::io; use rustix::path::Arg; pub fn touch(path: P) -> io::Result<()> { let path = path.into_c_str()?; _touch(&path) } fn _touch(path: &CStr) -> io::Result<()> { // implementation goes here Ok(()) } ``` -------------------------------- ### FromIterator implementation examples Source: https://docs.rs/rustix/latest/rustix/io/type.Result.html Examples showing how FromIterator collects Results, including short-circuiting behavior on Err. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### is_multicast method example Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_multicast method, available on non-WASI, showing it returns true for multicast addresses. ```rust use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(224, 254, 0, 0)).is_multicast(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0xff00, 0, 0, 0, 0, 0, 0, 0)).is_multicast(), true); ``` -------------------------------- ### is_loopback method example Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_loopback method, available on non-WASI, showing it returns true for loopback addresses. ```rust use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)).is_loopback(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 0x1)).is_loopback(), true); ``` -------------------------------- ### is_ipv4 method example Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_ipv4 method, available on non-WASI, showing it returns true for IPv4 addresses and false for IPv6 addresses. ```rust use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 6)).is_ipv4(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 0)).is_ipv4(), false); ``` -------------------------------- ### Example: using as_raw_fd on a File Source: https://docs.rs/rustix/latest/rustix/fd/trait.AsRawFd.html Example showing how to extract a raw file descriptor from a File. The raw_fd is only valid as long as the File exists. The code uses cfg attributes for Unix and WASI. ```rust use std::fs::File; #[cfg(any(unix, target_os = "wasi"))] use std::os::fd::{AsRawFd, RawFd}; let mut f = File::open("foo.txt")?; // Note that `raw_fd` is only valid as long as `f` exists. #[cfg(any(unix, target_os = "wasi"))] let raw_fd: RawFd = f.as_raw_fd(); ``` -------------------------------- ### is_global method example (nightly) Source: https://docs.rs/rustix/latest/rustix/net/enum.IpAddr.html Example for the is_global method, a nightly-only experimental API, available on non-WASI, showing it returns true for globally routable addresses. ```rust #![feature(ip)] use std::net::{IpAddr, Ipv4Addr, Ipv6Addr}; assert_eq!(IpAddr::V4(Ipv4Addr::new(80, 9, 12, 3)).is_global(), true); assert_eq!(IpAddr::V6(Ipv6Addr::new(0, 0, 0x1c9, 0, 0, 0xafc8, 0, 0x1)).is_global(), true); ``` -------------------------------- ### as_rchunks example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSlice.html Splits a slice into N-element arrays starting from the end. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (remainder, chunks) = slice.as_rchunks(); assert_eq!(remainder, &['l']); assert_eq!(chunks, &[['o', 'r'], ['e', 'm']]); ``` -------------------------------- ### io_uring_setup Source: https://docs.rs/rustix/latest/rustix/io_uring/fn.io_uring_setup.html Sets up a context for performing asynchronous I/O using io_uring. ```APIDOC ## io_uring_setup ### Description Sets up a context for performing asynchronous I/O. Available on crate feature `io_uring` only. ### Function Signature ```rust pub unsafe fn io_uring_setup( entries: u32, params: &mut io_uring_params, ) -> Result ``` ### Parameters - **entries** (u32) - The number of entries for the io_uring setup. - **params** (&mut io_uring_params) - Mutated parameters for the io_uring setup. If the `ATTACH_WQ` flag is set, the `wq_fd` field must be an open file descriptor. ### Returns - **Result** - A result containing an owned file descriptor on success or an error. ### Safety If `IoringSetupFlags::ATTACH_WQ` is set, the `wq_fd` field of `io_uring_params` must be an open file descriptor. ### References - Linux ``` -------------------------------- ### io_uring_setup Source: https://docs.rs/rustix/latest/src/rustix/io_uring/mod.rs.html Sets up a context for performing asynchronous I/O. This function is unsafe and requires that if IoringSetupFlags::ATTACH_WQ is set, the wq_fd field of io_uring_params must be an open file descriptor. ```APIDOC ## io_uring_setup ### Description Sets up a context for performing asynchronous I/O. ### Function Signature pub unsafe fn io_uring_setup(entries: u32, params: &mut io_uring_params) -> io::Result ### Parameters - **entries** (u32) - Required - Number of entries for the io_uring setup. - **params** (&mut io_uring_params) - Required - Pointer to io_uring_params structure. ### Safety If IoringSetupFlags::ATTACH_WQ is set, the wq_fd field of io_uring_params must be an open file descriptor. ### Return Value Returns io::Result - On success, returns an OwnedFd representing the io_uring context. ### References - [Linux io_uring_setup man page](https://www.man7.org/linux/man-pages/man2/io_uring_setup.2.html) ``` -------------------------------- ### as_chunks example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSlice.html Splits a slice into N-element arrays starting from the beginning. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let (chunks, remainder) = slice.as_chunks(); assert_eq!(chunks, &[['l', 'o'], ['r', 'e']]); assert_eq!(remainder, &['m']); ``` -------------------------------- ### rchunks example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSlice.html Returns an iterator over chunks of a specified size starting from the end. ```rust let slice = ['l', 'o', 'r', 'e', 'm']; let mut iter = slice.rchunks(2); assert_eq!(iter.next().unwrap(), &['e', 'm']); assert_eq!(iter.next().unwrap(), &['o', 'r']); assert_eq!(iter.next().unwrap(), &['l']); assert!(iter.next().is_none()); ``` -------------------------------- ### Example: new method Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV4.html Creates a new socket address from an IPv4 address and port number. ```rust use std::net::{SocketAddrV4, Ipv4Addr}; let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); ``` -------------------------------- ### Example: Constructing a File from a raw file descriptor Source: https://docs.rs/rustix/latest/rustix/fd/trait.FromRawFd.html Shows how to use `FromRawFd` to construct a `File` from a raw file descriptor, with a safety comment. ```rust use std::fs::File; #[cfg(any(unix, target_os = "wasi"))] use std::os::fd::{FromRawFd, IntoRawFd, RawFd}; let f = File::open("foo.txt")?; let raw_fd: RawFd = f.into_raw_fd(); // SAFETY: no other functions should call `from_raw_fd`, so there // is only one owner for the file descriptor. let f = unsafe { File::from_raw_fd(raw_fd) }; ``` -------------------------------- ### Example: Creating and using SocketAddrV4 Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV4.html Demonstrates creating a socket address with `new`, parsing from a string, and accessing IP and port. ```rust use std::net::{Ipv4Addr, SocketAddrV4}; let socket = SocketAddrV4::new(Ipv4Addr::new(127, 0, 0, 1), 8080); assert_eq!("127.0.0.1:8080".parse(), Ok(socket)); assert_eq!(socket.ip(), &Ipv4Addr::new(127, 0, 0, 1)); assert_eq!(socket.port(), 8080); ``` -------------------------------- ### rchunks_mut Example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSliceMut.html Iterates over a mutable slice in chunks of a specified size starting from the end. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[3, 2, 2, 1, 1]); ``` -------------------------------- ### Example for MetadataExt::rdev Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the device ID if the file is a special file. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let device_id = meta.rdev(); Ok(()) } ``` -------------------------------- ### Initialize and use inotify Source: https://docs.rs/rustix/latest/src/rustix/fs/inotify.rs.html Demonstrates creating an inotify instance with non-blocking flags, adding a directory watch, and iterating over pending events. ```rust use rustix::fs::inotify; use rustix::io; use std::mem::MaybeUninit; # fn test() -> io::Result<()> { // Create an inotify object. In this example, we use `NONBLOCK` so that the // reader fails with `WOULDBLOCK` when no events are ready. Otherwise it // will block until at least one event is ready. let inotify = inotify::init(inotify::CreateFlags::NONBLOCK)?; // Add a directory to watch. inotify::add_watch( &inotify, "/path/to/some/directory/to/watch", inotify::WatchFlags::ALL_EVENTS, )?; // Generate some events in the watched directory… // Loop over pending events. let mut buf = [MaybeUninit::uninit(); 512]; let mut iter = inotify::Reader::new(inotify, &mut buf); loop { let entry = match iter.next() { // Stop iterating if there are no more events for now. Err(io::Errno::WOULDBLOCK) => break, Err(e) => return Err(e), Ok(entry) => entry, }; // Use `entry`… } # Ok(()) # } ``` -------------------------------- ### CStr count_bytes Example Source: https://docs.rs/rustix/latest/rustix/ffi/struct.CString.html Shows how to get the length of a CStr without the nul terminator. ```rust assert_eq!(c"foo".count_bytes(), 3); assert_eq!(c"".count_bytes(), 0); ``` -------------------------------- ### PartialEq implementation for IoringSetupFlags Source: https://docs.rs/rustix/latest/rustix/io_uring/struct.IoringSetupFlags.html Provides equality comparison for IoringSetupFlags. ```APIDOC ## PartialEq implementation for IoringSetupFlags ### Description Provides equality comparison for IoringSetupFlags. ### Methods #### `fn eq(&self, other: &IoringSetupFlags) -> bool` - Tests for `self` and `other` values to be equal, and is used by `==`. #### `fn ne(&self, other: &Rhs) -> bool` - Tests for `!=`. The default implementation is almost always sufficient, and should not be overridden without very good reason. ``` -------------------------------- ### IoringSetupFlags Source: https://docs.rs/rustix/latest/rustix/io_uring/struct.IoringSetupFlags.html Documentation for the IoringSetupFlags struct, including its associated constants and methods. ```APIDOC ## Struct IoringSetupFlags ### Description Represents `IORING_SETUP_*` flags for use with `io_uring_params`. Available on crate feature `io_uring` only. ### Associated Constants - `ATTACH_WQ` - `IORING_SETUP_ATTACH_WQ` - `CLAMP` - `IORING_SETUP_CLAMP` - `CQSIZE` - `IORING_SETUP_CQSIZE` - `IOPOLL` - `IORING_SETUP_IOPOLL` - `R_DISABLED` - `IORING_SETUP_R_DISABLED` - `SQPOLL` - `IORING_SETUP_SQPOLL` - `SQ_AFF` - `IORING_SETUP_SQ_AFF` - `SQE128` - `IORING_SETUP_SQE128` - `CQE32` - `IORING_SETUP_CQE32` - `SUBMIT_ALL` - `IORING_SETUP_SUBMIT_ALL` - `COOP_TASKRUN` - `IORING_SETUP_COOP_TRASKRUN` - `TASKRUN_FLAG` - `IORING_SETUP_TASKRUN_FLAG` - `SINGLE_ISSUER` - `IORING_SETUP_SINGLE_ISSUER` - `DEFER_TASKRUN` - `IORING_SETUP_DEFER_TASKRUN` - `NO_MMAP` - `IORING_SETUP_NO_MMAP` - `REGISTERED_FD_ONLY` - `IORING_SETUP_REGISTERED_FD_ONLY` - `NO_SQARRAY` - `IORING_SETUP_NO_SQARRAY` ### Methods #### `empty()` - Signature: `pub const fn empty() -> Self` - Description: Get a flags value with all bits unset. #### `all()` - Signature: `pub const fn all() -> Self` - Description: Get a flags value with all known bits set. #### `bits(&self)` - Signature: `pub const fn bits(&self) -> u32` - Description: Get the underlying bits value. The returned value is exactly the bits set in this flags value. #### `from_bits(bits: u32)` - Signature: `pub const fn from_bits(bits: u32) -> Option` - Description: Convert from a bits value. Returns `None` if any unknown bits are set. #### `from_bits_truncate(bits: u32)` - Signature: `pub const fn from_bits_truncate(bits: u32) -> Self` - Description: Convert from a bits value, unsetting any unknown bits. #### `from_bits_retain(bits: u32)` - Signature: `pub const fn from_bits_retain(bits: u32) -> Self` - Description: Convert from a bits value exactly. #### `from_name(name: &str)` - Signature: `pub fn from_name(name: &str) -> Option` - Description: Get a flags value with the bits of a flag with the given name set. Returns `None` if `name` is empty or doesn't correspond to any named flag. #### `is_empty(&self)` - Signature: `pub const fn is_empty(&self) -> bool` - Description: Whether all bits in this flags value are unset. #### `is_all(&self)` - Signature: `pub const fn is_all(&self) -> bool` - Description: Whether all known bits in this flags value are set. #### `intersects(&self, other: Self)` - Signature: `pub const fn intersects(&self, other: Self) -> bool` - Description: Whether any set bits in a source flags value are also set in a target flags value. #### `contains(&self, other: Self)` - Signature: `pub const fn contains(&self, other: Self) -> bool` - Description: Whether all set bits in a source flags value are also set in a target flags value. #### `insert(&mut self, other: Self)` - Signature: `pub fn insert(&mut self, other: Self)` - Description: The bitwise or (`|`) of the bits in two flags values. #### `remove(&mut self, other: Self)` - Signature: `pub fn remove(&mut self, other: Self)` - Description: The intersection of a source flags value with the complement of a target flags value (`&!`). This method is not equivalent to `self & !other` when `other` has unknown bits set. `remove` won't truncate `other`, but the `!` operator will. #### `toggle(&mut self, other: Self)` - Signature: `pub fn toggle(&mut self, other: Self)` - Description: The bitwise exclusive-or (`^`) of the bits in two flags values. #### `set(&mut self, other: Self, value: bool)` - Signature: `pub fn set(&mut self, other: Self, value: bool)` - Description: Call `insert` when `value` is `true` or `remove` when `value` is `false`. #### `intersection(self, other: Self)` - Signature: `pub const fn intersection(self, other: Self) -> Self` - Description: The bitwise and (`&`) of the bits in two flags values. #### `union(self, other: Self)` - Signature: `pub const fn union(self, other: Self) -> Self` - Description: The bitwise or (`|`) of the bits in two flags values. #### `difference(self, other: Self)` - Signature: `pub const fn difference(self, other: Self) -> Self` - Description: The intersection of a source flags value with the complement of a target flags value (`&!`). This method is not equivalent to `self & !other` when `other` has unknown bits set. `difference` won't truncate `other`, but the `!` operator will. #### `symmetric_difference(self, other: Self)` - Signature: `pub const fn symmetric_difference(self, other: Self) -> Self` - Description: The bitwise exclusive-or (`^`) of the bits in two flags values. #### `complement(self)` - Signature: `pub const fn complement(self) -> Self` - Description: The bitwise negation (`!`) of the bits in a flags value, truncating the result. #### `iter(&self)` - Signature: `pub const fn iter(&self) -> Iter` - Description: Yield a set of contained flags values. Each yielded flags value will correspond to a defined named flag. Any unknown bits will be yielded together as a final flags value. #### `iter_names(&self)` - Signature: `pub const fn iter_names(&self) -> IterNames` - Description: Yield a set of contained named flags values. This method is like `iter`, except only yields bits in contained named flags. Any unknown bits, or bits not corresponding to a contained flag will not be yielded. ``` -------------------------------- ### fsconfig_create syscall wrapper Source: https://docs.rs/rustix/latest/src/rustix/backend/linux_raw/mount/syscalls.rs.html Creates a filesystem configuration using the fsconfig syscall with the Create command. ```rust #[inline] pub(crate) fn fsconfig_create(fs_fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_fsconfig, fs_fd, super::types::FsConfigCmd::Create, zero(), zero(), zero() )) } } ``` -------------------------------- ### rsplit example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSliceMut.html Demonstrates splitting a slice into subslices starting from the end, excluding the matched element. ```rust let slice = [11, 22, 33, 0, 44, 55]; let mut iter = slice.rsplit(|num| *num == 0); assert_eq!(iter.next().unwrap(), &[44, 55]); assert_eq!(iter.next().unwrap(), &[11, 22, 33]); assert_eq!(iter.next(), None); ``` ```rust let v = &[0, 1, 1, 2, 3, 5, 8]; let mut it = v.rsplit(|n| *n % 2 == 0); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next().unwrap(), &[3, 5]); assert_eq!(it.next().unwrap(), &[1, 1]); assert_eq!(it.next().unwrap(), &[]); assert_eq!(it.next(), None); ``` -------------------------------- ### rchunks_exact_mut Example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSliceMut.html Iterates over a mutable slice in exact chunks starting from the end, with a remainder method. ```rust let v = &mut [0, 0, 0, 0, 0]; let mut count = 1; for chunk in v.rchunks_exact_mut(2) { for elem in chunk.iter_mut() { *elem += count; } count += 1; } assert_eq!(v, &[0, 2, 2, 1, 1]); ``` -------------------------------- ### Example for MetadataExt::mtime_nsec Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the last modification time in nanoseconds since mtime. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let nano_last_modification_time = meta.mtime_nsec(); Ok(()) } ``` -------------------------------- ### Example for MetadataExt::atime_nsec Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the last access time in nanoseconds since atime. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let nano_last_access_time = meta.atime_nsec(); Ok(()) } ``` -------------------------------- ### rsplit_mut example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSliceMut.html Demonstrates splitting a mutable slice into subslices starting from the end, excluding the matched element. ```rust let mut v = [100, 400, 300, 200, 600, 500]; let mut count = 0; for group in v.rsplit_mut(|num| *num % 3 == 0) { count += 1; group[0] = count; } assert_eq!(v, [3, 400, 300, 2, 600, 1]); ``` -------------------------------- ### fs::mkdir Source: https://docs.rs/rustix/latest/rustix/all.html Creates a directory. Wraps the mkdir system call. ```APIDOC ## fs::mkdir ### Description Creates a directory. ### Function Signature `pub fn mkdir(path: &Path, mode: Mode) -> io::Result<()>` ### Parameters - `path` (Path) - Required - Path to create. - `mode` (Mode) - Required - Permissions. ### Return Value Returns `io::Result<()>`. ``` -------------------------------- ### Example for MetadataExt::mtime Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the last modification time in seconds since Unix Epoch. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let last_modification_time = meta.mtime(); Ok(()) } ``` -------------------------------- ### Example for MetadataExt::atime Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the last access time in seconds since Unix Epoch. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let last_access_time = meta.atime(); Ok(()) } ``` -------------------------------- ### Example for MetadataExt::dev Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Shows how to get the device ID containing the file using the dev method. ```rust use std::io; use std::fs; use std::os::unix::fs::MetadataExt; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let dev_id = meta.dev(); Ok(()) } ``` -------------------------------- ### fs::inotify::init Source: https://docs.rs/rustix/latest/rustix/all.html Creates an inotify instance. Wraps the inotify_init1 system call. ```APIDOC ## fs::inotify::init ### Description Creates an inotify instance. ### Function Signature `pub fn init(flags: InotifyCreateFlags) -> io::Result` ### Parameters - `flags` (InotifyCreateFlags) - Required - Flags. ### Return Value Returns an owned file descriptor. ``` -------------------------------- ### Retaking ownership with CString::from_raw Source: https://docs.rs/rustix/latest/rustix/ffi/struct.CString.html Example setup for retaking ownership of a CString pointer previously passed to an external function. ```rust use std::ffi::CString; use std::os::raw::c_char; extern "C" { fn some_extern_function(s: *mut c_char); } ``` -------------------------------- ### Create Ipv6Addr with new Source: https://docs.rs/rustix/latest/rustix/net/struct.Ipv6Addr.html Shows how to create an IPv6 address from eight 16-bit segments using the new constructor. The example creates an address with segments 0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff. ```rust use std::net::Ipv6Addr; let addr = Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff); ``` -------------------------------- ### Create Directory Source: https://docs.rs/rustix/latest/src/rustix/backend/linux_raw/fs/syscalls.rs.html Creates a new directory with the specified mode. ```rust #[inline] pub(crate) fn mkdir(path: &CStr, mode: Mode) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_mkdirat, raw_fd(AT_FDCWD), path, mode )) } } ``` -------------------------------- ### read_buf_exact_at example Source: https://docs.rs/rustix/latest/rustix/fs/trait.FileExt.html Reads exactly 10 bytes starting from offset 2 into a BorrowedBuf. Requires nightly features core_io_borrowed_buf and read_buf_at. ```rust #![feature(core_io_borrowed_buf)] #![feature(read_buf_at)] use std::io; use std::io::BorrowedBuf; use std::fs::File; use std::mem::MaybeUninit; use std::os::unix::prelude::*; fn main() -> io::Result<()> { let mut file = File::open("pi.txt")?; // Read exactly 10 bytes starting from offset 2 let mut buf: [MaybeUninit; 10] = [MaybeUninit::uninit(); 10]; let mut buf = BorrowedBuf::from(buf.as_mut_slice()); file.read_buf_exact_at(buf.unfilled(), 2)?; assert_eq!(buf.filled(), b"1415926535"); Ok(()) } ``` -------------------------------- ### read_buf_at example Source: https://docs.rs/rustix/latest/rustix/fs/trait.FileExt.html Reads bytes starting from offset 2 into a BorrowedBuf, allowing use with uninitialized memory. Requires nightly features core_io_borrowed_buf and read_buf_at. ```rust #![feature(core_io_borrowed_buf)] #![feature(read_buf_at)] use std::io; use std::io::BorrowedBuf; use std::fs::File; use std::mem::MaybeUninit; use std::os::unix::prelude::*; fn main() -> io::Result<()> { let mut file = File::open("pi.txt")?; // Read some bytes starting from offset 2 let mut buf: [MaybeUninit; 10] = [MaybeUninit::uninit(); 10]; let mut buf = BorrowedBuf::from(buf.as_mut_slice()); file.read_buf_at(buf.unfilled(), 2)?; assert!(buf.filled().starts_with(b"1")); Ok(()) } ``` -------------------------------- ### fsconfig_create_excl syscall wrapper Source: https://docs.rs/rustix/latest/src/rustix/backend/linux_raw/mount/syscalls.rs.html Creates a filesystem configuration exclusively using the fsconfig syscall with the CreateExclusive command. ```rust #[inline] pub(crate) fn fsconfig_create_excl(fs_fd: BorrowedFd<'_>) -> io::Result<()> { unsafe { ret(syscall_readonly!( __NR_fsconfig, fs_fd, super::types::FsConfigCmd::CreateExclusive, zero(), zero(), zero() )) } } ``` -------------------------------- ### Get port with SocketAddrV6::port Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV6.html Returns the port number of the socket address. The example creates a socket with port 8080 and asserts that `socket.port()` equals 8080. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); assert_eq!(socket.port(), 8080); ``` -------------------------------- ### Get scope_id with SocketAddrV6::scope_id Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV6.html Returns the scope ID (sin6_scope_id) of the socket address. The example creates a socket with scope_id 78 and asserts that `socket.scope_id()` equals 78. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 78); assert_eq!(socket.scope_id(), 78); ``` -------------------------------- ### IoringSetupFlags Source: https://docs.rs/rustix/latest/src/rustix/io_uring/mod.rs.html Bitflags struct for IORING_SETUP_* flags used with io_uring_params. ```APIDOC ## IoringSetupFlags ### Description Bitflags struct for IORING_SETUP_* flags used with io_uring_params. ### Flags - **ATTACH_WQ** - Corresponds to IORING_SETUP_ATTACH_WQ. - **CLAMP** - Corresponds to IORING_SETUP_CLAMP. - **CQSIZE** - Corresponds to IORING_SETUP_CQSIZE. - **IOPOLL** - Corresponds to IORING_SETUP_IOPOLL. - **R_DISABLED** - Corresponds to IORING_SETUP_R_DISABLED. - **SQPOLL** - Corresponds to IORING_SETUP_SQPOLL. - **SQ_AFF** - Corresponds to IORING_SETUP_SQ_AFF. - **SQE128** - Corresponds to IORING_SETUP_SQE128. - **CQE32** - Corresponds to IORING_SETUP_CQE32. - **SUBMIT_ALL** - Corresponds to IORING_SETUP_SUBMIT_ALL. - **COOP_TASKRUN** - Corresponds to IORING_SETUP_COOP_TRASKRUN. - **TASKRUN_FLAG** - Corresponds to IORING_SETUP_TASKRUN_FLAG. - **SINGLE_ISSUER** - Corresponds to IORING_SETUP_SINGLE_ISSUER. - **DEFER_TASKRUN** - Corresponds to IORING_SETUP_DEFER_TASKRUN. - **NO_MMAP** - Corresponds to IORING_SETUP_NO_MMAP. - **REGISTERED_FD_ONLY** - Corresponds to IORING_SETUP_REGISTERED_FD_ONLY. - **NO_SQARRAY** - Corresponds to IORING_SETUP_NO_SQARRAY. ### Notes - The struct is defined using the bitflags crate and includes an external flag constant. ``` -------------------------------- ### Get flowinfo with SocketAddrV6::flowinfo Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV6.html Returns the flow information (sin6_flowinfo) of the socket address. The example creates a socket with flowinfo 10 and asserts that `socket.flowinfo()` equals 10. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 10, 0); assert_eq!(socket.flowinfo(), 10); ``` -------------------------------- ### iter example Source: https://docs.rs/rustix/latest/rustix/io/struct.IoSlice.html Demonstrates iterating over the elements of a slice. ```rust let x = &[1, 2, 4]; let mut iterator = x.iter(); assert_eq!(iterator.next(), Some(&1)); assert_eq!(iterator.next(), Some(&2)); assert_eq!(iterator.next(), Some(&4)); assert_eq!(iterator.next(), None); ``` -------------------------------- ### Get IP address with SocketAddrV6::ip Source: https://docs.rs/rustix/latest/rustix/net/struct.SocketAddrV6.html Returns the IP address associated with the socket address. The example creates a socket and asserts that `socket.ip()` equals the expected Ipv6Addr. ```rust use std::net::{SocketAddrV6, Ipv6Addr}; let socket = SocketAddrV6::new(Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1), 8080, 0, 0); assert_eq!(socket.ip(), &Ipv6Addr::new(0, 0, 0, 0, 0, 0, 0, 1)); ``` -------------------------------- ### Get segments of Ipv6Addr Source: https://docs.rs/rustix/latest/rustix/net/struct.Ipv6Addr.html Shows how to retrieve the eight 16-bit segments of an IPv6 address using the segments method. The example asserts the returned array matches the expected segments. ```rust use std::net::Ipv6Addr; assert_eq!(Ipv6Addr::new(0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff).segments(), [0, 0, 0, 0, 0, 0xffff, 0xc00a, 0x2ff]); ``` -------------------------------- ### Implement From for Mode with doc example Source: https://docs.rs/rustix/latest/src/rustix/backend/linux_raw/fs/types.rs.html Implements conversion from raw mode values to Mode, with a doc test showing that Mode::from(0o700) equals Mode::RWXU. ```rust impl From for Mode { /// Support conversions from raw mode values to `Mode`. /// /// ``` /// use rustix::fs::{Mode, RawMode}; /// assert_eq!(Mode::from(0o700), Mode::RWXU); /// ``` #[inline] fn from(st_mode: RawMode) -> Self { Self::from_raw_mode(st_mode) } } ``` -------------------------------- ### Get filesystem I/O block size with MetadataExt::blksize Source: https://docs.rs/rustix/latest/rustix/fs/trait.MetadataExt.html Returns the block size for filesystem I/O. The example uses std::fs::metadata and the MetadataExt trait to retrieve the value. ```rust use std::fs; use std::os::unix::fs::MetadataExt; use std::io; fn main() -> io::Result<()> { let meta = fs::metadata("some_file")?; let block_size = meta.blksize(); Ok(()) } ```