lx 0.4.0

A no_std crate to use Linux system calls
Documentation
use core::mem::{
    self,
    MaybeUninit,
};

use super::{
    SockAddr,
    AF_UNIX,
};

#[repr(C)]
#[derive(Clone, Copy)]
pub struct SockAddrUn {
    family: u16,
    pub path: [MaybeUninit<u8>; 108],
}

#[derive(Debug)]
pub enum FromPathError {
    NulByte,
    TooLarge,
}

impl SockAddrUn {
    pub fn new(path: [MaybeUninit<u8>; 108]) -> Self {
        Self {
            family: AF_UNIX.into(),
            path,
        }
    }

    /// Creates a UNIX socket address corresponding to the filesystem pathname `path`.
    ///
    /// # Errors
    ///
    /// An error is returned if the path contains the nul byte or is larger than 107 bytes.
    pub fn from_path(path: impl AsRef<[u8]>) -> Result<Self, FromPathError> {
        let path = path.as_ref();
        if path.contains(&0) {
            return Err(FromPathError::NulByte);
        }
        let mut buf = [MaybeUninit::uninit(); 108];
        if path.len() >= buf.len() {
            return Err(FromPathError::TooLarge);
        }
        buf[..path.len()].copy_from_slice(unsafe { mem::transmute(path) });
        buf[path.len()] = MaybeUninit::new(0);
        Ok(Self::new(buf))
    }

    /// Creates an abstract UNIX socket address.
    pub fn from_abstract_addr(addr: [u8; 107]) -> Self {
        let mut buf = [0; 108];
        buf[1..].copy_from_slice(&addr);
        Self::new(unsafe { mem::transmute(buf) })
    }
}

unsafe impl SockAddr for SockAddrUn {
    fn family() -> u8 {
        AF_UNIX
    }
}