Skip to main content

CStr

Trait CStr 

Source
pub trait CStr:
    Deref<Target = CStr>
    + Display
    + Debug
    + Send
    + Sync {
    // Required methods
    fn as_cstr(&self) -> &StdCStr;
    fn dyn_clone(&self) -> Box<dyn CStr>;

    // Provided methods
    fn as_bytes(&self) -> &[u8] ⓘ { ... }
    fn as_bytes_with_nul(&self) -> &[u8] ⓘ { ... }
    fn as_ptr(&self) -> *const c_char { ... }
    fn len(&self) -> usize { ... }
    fn is_empty(&self) -> bool { ... }
}
Available on crate features types-cstr and types only.
Expand description

安全 C 字符串的统一接口:只读视图,内部恒为合法 CStr(以 \0 结尾、无内部 NUL)。

注意:本 trait 名为 CStr,与 core::ffi::CStr 同名。取值时用 CStr::as_cstr 拿到底层 &core::ffi::CStr。

§Feature Requirement

需要启用 "types-cstr" 特性。

§Examples

use core::convert::TryInto;
use lib_unknown::types::cstr::{CStr, StackCStr};

let s: StackCStr<8> = "hi".try_into().unwrap();
assert_eq!(s.as_cstr().to_bytes(), b"hi");
assert_eq!(s.len(), 2);

Required Methods§

Source

fn as_cstr(&self) -> &StdCStr

以 &core::ffi::CStr 形式查看内容,可直接传给 sys_open 等。

§Feature Requirement

需要启用 "types-cstr" 特性。

Source

fn dyn_clone(&self) -> Box<dyn CStr>

Available on crate feature alloc only.

类型擦除的堆克隆,用于 Box<dyn CStr> 容器。

§Feature Requirement

需要启用 "types-cstr" 与 "alloc" 特性。

Provided Methods§

Source

fn as_bytes(&self) -> &[u8] ⓘ

以字节切片查看载荷(不含结尾 \0),允许非 UTF-8。

§Feature Requirement

需要启用 "types-cstr" 特性。

Source

fn as_bytes_with_nul(&self) -> &[u8] ⓘ

以字节切片查看含结尾 \0 的完整存储。

§Feature Requirement

需要启用 "types-cstr" 特性。

Source

fn as_ptr(&self) -> *const c_char

返回载荷的原始指针,指向容器内部存储(等价于 as_cstr().as_ptr())。

返回的指针仅在 self 存活且未被搬运/修改期间有效;self 移动、Drop 或任何 &mut self 操作后不得再使用旧指针。

§Feature Requirement

需要启用 "types-cstr" 特性。

Source

fn len(&self) -> usize

返回载荷的字节长度(不含结尾 \0)。

§Feature Requirement

需要启用 "types-cstr" 特性。

Source

fn is_empty(&self) -> bool

载荷是否为空。

§Feature Requirement

需要启用 "types-cstr" 特性。

Trait Implementations§

Source§

impl Clone for Box<dyn CStr>

Source§

fn clone(&self) -> Self

Returns a duplicate of the value. Read more
1.0.0 (const: unstable) · Source§

fn clone_from(&mut self, source: &Self)

Performs copy-assignment from source. Read more
Source§

impl Eq for Box<dyn CStr>

Source§

impl PartialEq for Box<dyn CStr>

Source§

fn eq(&self, other: &Self) -> bool

Equality operator ==. Read more
1.0.0 (const: unstable) · Source§

fn ne(&self, other: &Rhs) -> bool

Inequality operator !=. Read more

Dyn Compatibility§

This trait is dyn compatible.

In older versions of Rust, dyn compatibility was called "object safety".

Implementors§

Source§

impl<const N: usize> CStr for HeapCStr<N>

Source§

impl<const N: usize> CStr for StackCStr<N>