Rust Libs Examples

Rust相关库的介绍

collections

BTreeSet

marker

表示类型的基本属性的原始特征和类型。 Rust 的类型依据其内在属性可以用各种各样的方法进行分类。这些分类以traits来表示。

PhantomData

  • 日期: 2022-03-08 11:58
  • 版本: Rust 1.58.1

简介

struct 类型,没有大小。


#![allow(unused)]

fn main() {
pub struct PhantomData<T>
 where
    T: ?Sized;
}

主要用来解决两个问题

  • 生命周期
  • 数据回收

生命周期

对于一些标记了生命周期,但是其内部没有使用的类型来说,此生命周期由于没有使用,从而导致没有边界,无法进行编译。例如:


#![allow(unused)]
fn main() {
struct Iter<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
}
}

所以需要修改为:


#![allow(unused)]
fn main() {
use std::marker;

struct Iter<'a, T: 'a> {
    ptr: *const T,
    end: *const T,
    _marker: marker::PhantomData<&'a T>,
}
}

数据回收

比如对于Vec类型来说


#![allow(unused)]
fn main() {
struct Vec<T> {
    data: *const T, // *const for variance!
    len: usize,
    cap: usize,
}
}

删除检查器确定Vec<T>没有拥有任何T类型的任何值。

为了让删除检查器确定我们拥有T类型的值,可以做如下修改


#![allow(unused)]
fn main() {
use std::marker;

struct Vec<T> {
    data: *const T, // *const for variance!
    len: usize,
    cap: usize,
    _marker: marker::PhantomData<T>,
}
}

使用场景

Phantom type'aT
PhantomData-covariant (with drop check)
PhantomData<&'a T>covariantcovariant
PhantomData<&'a mut T>covariantinvariant
PhantomData<*const T>-covariant
PhantomData<*mut T>-invariant
PhantomData<fn(T)>-contravariant
PhantomData<fn() -> T>-covariant
PhantomData<fn(T) -> T>-invariant
PhantomData<Cell<&'a ()>>invariant-

arrayvec

  • 日期: 2022-03-08 14:40
  • 版本: 0.7.2 repo docs

一、简介

  • 提供两个结构体:ArrayVecArrayString

  • 在内存中以固定长度按照数组形式存储,并且提供操作的方法。

  • CAP参数类型虽然是usize类型,但其实最大只有u32::MAX

二、ArrayVec

2.1 结构声明


#![allow(unused)]
fn main() {
pub struct ArrayVec<T, const CAP: usize> {
    // the `len` first elements of the array are initialized
    xs: [MaybeUninit<T>; CAP],
    len: LenUint,
}
}

2.2 常用方法

  • pub fn new() -> ArrayVec<T, CAP>
  • pub fn push(&mut self, element: T)
  • pub fn try_push(&mut self, element: T) -> Result<(), CapacityError<T>>
  • pub fn insert(&mut self, index: usize, element: T)
  • pub fn pop(&mut self) -> Option<T>
  • pub fn pop_at(&mut self, index: usize) -> Option<T>
  • pub fn remove(&mut self, index: usize) -> T
  • pub const fn len(&self) -> usize
  • pub const fn is_empty(&self) -> bool
  • pub const fn capacity(&self) -> usize

三、ArrayString

3.1 结构声明


#![allow(unused)]
fn main() {
#[derive(Copy)]
pub struct ArrayString<const CAP: usize> {
    // the `len` first elements of the array are initialized
    xs: [MaybeUninit<u8>; CAP],
    len: LenUint,
}
}

3.2 常用方法

  • pub fn new() -> ArrayString<CAP>
  • pub fn from(s: &str) -> Result<Self, CapacityError<&str>>
  • pub fn push(&mut self, c: char)
  • pub fn push_str(&mut self, s: &str)
  • pub fn try_push(&mut self, c: char) -> Result<(), CapacityError<char>>
  • pub fn try_push_str<'a>(&mut self,s: &'a str) -> Result<(), CapacityError<&'a str>>
  • pub fn pop(&mut self) -> Option<char>
  • pub fn truncate(&mut self, new_len: usize)
  • pub fn clear(&mut self)
  • pub fn remove(&mut self, idx: usize) -> char
  • pub const fn len(&self) -> usize
  • pub const fn is_empty(&self) -> bool
  • pub const fn capacity(&self) -> usize
  • pub const fn is_full(&self) -> bool

anyhow

  • 错误处理封装的一个库,相当于把 std::error::Error<T>封装了一把,封装了一个 Result<T, anyhow::Error>
  • anyhow::Error类型可以处理任何类型的错误。

基本用法:


#![allow(unused)]
fn main() {
use anyhow::Result;

fn get_file_info() -> Result<()> {
    let config = std::fs::read_to_string("cluster.json")?;
    println!("{}", config);
    Ok(())
}
}

cfg-if

  • 日期: 2022-03-08 11:23
  • 版本: 1.0.0 repo docs

用来做条件编译的宏。

示例:


#![allow(unused)]
fn main() {
cfg_if::cfg_if! {
    if #[cfg(unix)] {
        fn foo() { /* unix specific functionality */ }
    } else if #[cfg(target_pointer_width = "32")] {
        fn foo() { /* non-unix, 32-bit functionality */ }
    } else {
        fn foo() { /* fallback implementation */ }
    }
}
}

等价于


#![allow(unused)]
fn main() {
#[cfg(unix)]
fn foo() { /* unix specific functionality */ }
#[cfg(all(target_pointer_width = "32", not(unix)))]
fn foo() { /* non-unix, 32-bit functionality */ }
#[cfg(not(any(unix, target_pointer_width = "32")))]
fn foo() { /* fallback implementation */ }    
}