tipc-std 0.1.0

TIPC standard library type provider
Documentation
// SPDX-License-Identifier: Apache-2.0
// Copyright 2026 KylinSoft Co., Ltd. <https://www.kylinos.cn/>
// See LICENSES for license details.

//! FFI types for tipc-std.

pub use alloc_crate::ffi::CString;
use alloc_crate::vec::Vec;

use crate::alloc_crate;

/// Error returned when creating a `CString` fails.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum TryNewError {
    /// An interior nul byte was found at the given position.
    NulError(usize, Vec<u8>),
    /// Memory allocation failed.
    AllocError,
}

/// A CString-like type that uses fallible allocation.
pub struct FallibleCString(CString);

impl FallibleCString {
    /// Creates a new `FallibleCString` from a byte slice without nul check.
    ///
    /// # Safety
    ///
    /// The caller must ensure `v` contains no nul bytes and has a nul
    /// terminator.
    pub unsafe fn from_vec_unchecked(v: Vec<u8>) -> Result<Self, TryNewError> {
        // SAFETY: caller guarantees no interior nul + nul terminated.
        let cs = unsafe { CString::from_vec_unchecked(v) };
        Ok(FallibleCString(cs))
    }

    /// Creates a new `FallibleCString` from a byte slice.
    pub fn new(v: Vec<u8>) -> Result<Self, TryNewError> {
        match CString::new(v) {
            Ok(cs) => Ok(FallibleCString(cs)),
            Err(e) => Err(TryNewError::NulError(e.nul_position(), e.into_vec())),
        }
    }
}

impl core::ops::Deref for FallibleCString {
    type Target = CString;

    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

impl From<crate::alloc::AllocError> for TryNewError {
    fn from(_err: crate::alloc::AllocError) -> Self {
        TryNewError::AllocError
    }
}