Rust数组处理库array_tool的使用,高效数组操作与工具函数扩展,增强Rust标准库功能

Rust数组处理库array_tool的使用,高效数组操作与工具函数扩展,增强Rust标准库功能

array_tool是一个Rust数组处理库,提供了许多常用的数组操作方法,增强了Rust标准库的功能。它为向量(Vec)提供了许多你在其他语言中常用的数组方法。

安装

在Cargo.toml文件中添加以下依赖:

[dependencies]
array_tool = "1.0.0"

在需要使用它的Rust文件中,添加以下代码:

extern crate array_tool;

如果你想使用所有可用的向量辅助方法,可以这样做:

use array_tool::vec::*;

这个库也提供了一些有用的字符串处理方法。

迭代器使用

use array_tool::iter::ZipOpt;
fn zip_option<U: Iterator>(self, other: U) -> ZipOption<Self, U>
  where Self: Sized, U: IntoIterator;
  //  let a = vec![1];
  //  let b = vec![];
  //  a.zip_option(b).next()      // input
  //  Some((Some(1), None))       // return value

向量使用

pub fn uniques<T: PartialEq + Clone>(a: Vec<T>, b: Vec<T>) -> Vec<Vec<T>>
  //  array_tool::uniques(vec![1,2,3,4,5], vec![2,5,6,7,8]) // input
  //  vec![vec![1,3,4], vec![6,7,8]]                        // return value

use array_tool::vec::Uniq;
fn uniq(&self, other: Vec<T>) -> Vec<T>;
  //  vec![1,2,3,4,5,6].uniq( vec![1,2,5,7,9] ) // input
  //  vec![3,4,6]                               // return value
fn uniq_via<F: Fn(&T, &T) -> bool>(&self, other: Self, f: F) -> Self;
  //  vec![1,2,3,4,5,6].uniq_via( vec![1,2,5,7,9], |&l, r| l == r + 2 ) // input 
  //  vec![1,2,4,6]                                                     // return value
fn unique(&self) -> Vec<T>;
  //  vec![1,2,1极,3,2,3,4,5,6].unique()          // input
  //  vec![1,2,3,4,5,6]                         // return value
fn unique_via<F: Fn(&T, &T) -> bool>(&self, f: F) -> Self;
  //  vec![1.0,2.0,1.4,3.3,2.1,3.5,4.6,5.2,6.2].
  //  unique_via( |l: &f64, r: &f64| l.floor() == r.floor() ) // input
  //  vec![1.0,2.0,3.3,4.6,5.2,极6.2]                           // return value
fn is_unique(&self) -> bool;
  //  vec![1,2,1,3,4,3,4,5,6].is_unique()       // input
  //  false                                     // return value
  //  vec![1,2,3,4,5,6].is_unique()             // input
  //  true                                      // return value

use array_tool::vec::Shift;
fn unshift(&mut self, other: T);    // no return value, modifies &mut self directly
  //  let mut x = vec![1,2,3];
  //  x.unshift(0);
  //  assert_eq!(x, vec![0,1,2,3]);
fn shift(&mut self) -> Option<T>;
  //  let mut x = vec![0,1,2,3];
  //  assert_eq!(x.shift(), Some(0));
  //  assert_eq!(x, vec![1,2,3]);

use array_tool::vec::Intersect;
fn intersect(&self, other: Vec<T>) -> Vec<T>;
  //  vec![1,1,3,5].intersect(vec![1,2,3]) // input
  //  vec![1,3]                            // return value
fn intersect_if<F: Fn(&T, &T) -> bool>(&self, other: Vec<T>, validator: F) -> Vec<T>;
  //  vec!['a','a','c','e'].intersect_if(vec!['A','B','C'], |l, r| l.eq_ignore_ascii_case(r)) // input
  //  vec!['a','c']                                                                           // return value

use array_tool::vec::Join;
fn join(&self, joiner: &'static str) -> String;
  //  vec![1,2,3].join(",")                // input
  //  "1,2,3"                              // return value

use array_tool::vec::Times;
fn times(&self, qty: i32) -> Vec<T>;
  //  vec![1,2,3].times(3)                 // input
  //  vec![1,2,3,1,2,3,1,2,3]              // return value

use array_tool::vec::Union;
fn union(&self, other: Vec<T>)极 Vec<T>;
  //  vec!["a","b","c"].union(vec!["c","d","a"])   // input
  //  vec![ "a", "b", "c", "d" ]                   // return value

字符串使用

use array_tool::string::ToGraphemeBytesIter;
fn grapheme_bytes_iter(&'a self) -> GraphemeBytesIter<'a>;
  //  let string = "a s—d féZ";
  //  let mut graphemes = string.grapheme_bytes_iter()
  //  graphemes.skip(3).next();            // input
  //  [226, 128, 148]                      // return value for emdash `—`

use array_tool::string::Squeeze;
fn squeeze(&self, targets: &'static str) -> String;
  //  "yellow moon".squeeze("")            // input
  //  "yelow mon"                          // return value
  //  "  now   is  the".squeeze(" ")       // input
  //  " now is the"                        // return value

use array_tool::string::Justify;
fn justify_line(&self, width: usize) -> String;
  //  "asd as df asd".justify_line(16)     // input
  //  "asd  as  df  asd"                   // return value
  //  "asd as df asd".justify_line(18)     // input
  //  "asd   as   df  asd"                 // return value

use array_tool::string::SubstMarks;
fn subst_marks(&self, marks: Vec<usize>, chr: &'static str) -> String;
  //  "asdf asdf asdf".subst_marks(vec![0,5,8], "Z") // input
  //  "Zsdf ZsdZ asdf"                               // return value

use array_tool::string::WordWrap;
fn word_wrap(&self, width: usize) -> String;
  //  "01234 67 9 BC EFG IJ".word_wrap(6)  // input
  //  "01234\n67 9\nBC\nEFG IJ"            // return value

use array_tool::string::AfterWhitespace;
fn seek_end_of_whitespace(&self, offset: usize) -> Option<usize>;
  //  "asdf           asdf asdf".seek_end_of_whitespace(6) // input
  //  Some(9)                                              // return value
  //  "asdf".seek_end_of_whitespace(3)                     // input
  //  Some(0)                                              // return value
  //  "asdf           ".seek_end_of_whitespace(6)          // input
  //  None                                                 // return_value

完整示例代码

下面是一个扩展的使用array_tool库的完整示例:

extern crate array_tool;
use array_tool::vec::*;
use array_tool::string::*;

fn main() {
    // 向量操作示例
    println!("--- 向量操作示例 ---");
    
    // 使用uniq方法
    let vec1 = vec![1,2,3,4,5,6];
    let vec2 = vec![1,2,5,7,9];
    let result = vec1.uniq(vec2);
    println!("uniq结果: {:?}", result); // 输出: [3,4,6]

    // 使用unique方法去重
    let vec_with_duplicates = vec![1,2,1,3,2,3,4,5,6];
    let unique_vec = vec_with_duplicates.unique();
    println!("去重结果: {:?}", unique_vec); // 输出: [1,2,3,4,5,6]

    // 使用intersect方法求交集
    let vec3 = vec![1,1,3,5];
    let vec4 = vec![1,2,3];
    let intersection = vec3.intersect(vec4);
    println!("交集结果: {:?}", intersection); // 输出: [1,3]

    // 使用union方法求并集
    let vec5 = vec!["a", "b", "c"];
    let vec6 = vec!["c", "d", "a"];
    let union_result = vec5.union(vec6);
    println!("并集结果: {:?}", union_result); // 输出: ["a", "b", "c", "d"]

    // 使用times方法重复数组
    let vec7 = vec![1,2,3];
    let repeated = vec7.times(3);
    println!("重复3次结果: {:?}", repeated); // 输出: [1,2,3,1,2,3,1,2,3]

    // 字符串操作示例
    println!("\n--- 字符串操作示例 ---");
    
    // 使用squeeze方法压缩重复字符
    let s1 = "yellow moon";
    println!("压缩空格前: '{}'", s1);
    println!("压缩空格后: '{}'", s1.squeeze("")); // 输出: "yelow mon"

    // 使用justify_line方法对齐文本
    let s2 = "asd as df asd";
    println!("对齐前: '{}'", s2);
    println!("对齐到16字符: '{}'", s2.justify_line(16)); // 输出: "asd  as  df  asd"

    // 使用word_wrap方法自动换行
    let s3 = "01234 67 9 BC EFG IJ";
    println!("换行前: '{}'", s3);
    println!("6字符换行:\n{}", s3.word_wrap(6)); // 输出多行文本
}

未来计划

预计方法会随着时间的推移变得更加多态(为相似和兼容的类型实现相同的方法)。我计划实现许多在高级语言(如Ruby)中可用的数组方法。期待定期更新。

许可证

根据以下任一许可证授权:

  • Apache License, Version 2.0
  • MIT license

贡献

除非您明确声明,否则任何有意提交的贡献都应按照上述双重许可,无需任何附加条款或条件。


1 回复

Rust数组处理库array_tool的使用指南

array_tool是一个强大的Rust库,它为Rust标准库中的数组/向量操作提供了额外的实用功能,可以显著简化常见的数组处理任务。

安装

在Cargo.toml中添加依赖:

[dependencies]
array_tool = "1.0"

主要功能与使用示例

1. 数组去重

use array_tool::vec::Uniq;

fn main() {
    let vec = vec![1, 2, 2, 3, 4, 4, 5];
    let unique = vec.unique();
    println!("{:?}", unique); // 输出: [1, 2, 3, 4, 5]
}

2. 数组交集

use array_tool::vec::Intersect;

fn main() {
    let vec1 = vec![1, 2, 3, 4, 5];
    let vec2 = vec![3, 4, 5, 6, 7];
    let intersection = vec1.intersect(vec2);
    println!("{:?}", intersection); // 输出: [3, 4, 5]
}

3. 数组合并

use array_tool::vec::Union;

fn main() {
    let vec1 = vec![1, 极简、高效且易于维护。

## 完整示例代码

```rust
use array_tool::vec::{Uniq, Intersect, Union, Difference, SymmetricDifference, Join, Pad};

fn main() {
    // 1. 数组去重示例
    let vec = vec![1, 2, 2, 3, 4, 4, 5];
    let unique = vec.unique();
    println!("去重结果: {:?}", unique);

    // 2. 数组交集示例
    let vec1 = vec![1, 2, 3, 4, 5];
    let vec2 = vec![3, 4, 5, 6, 7];
    let intersection = vec1.intersect(vec2);
    println!("交集结果: {:?}", intersection);

    // 3. 数组合并示例
    let vec3 = vec![1, 2, 3];
    let vec4 = vec![3, 4, 5];
    let union = vec3.union(vec4);
    println!("并集结果: {:?}", union);

    // 4. 数组差集示例
    let vec5 = vec![1, 2, 3, 4, 5];
    let vec6 = vec![3, 4, 5, 6, 7];
    let difference = vec5.difference(vec6);
    println!("差集结果: {:?}", difference);

    // 5. 数组对称差集示例
    let vec7 = vec![1, 2, 3, 4];
    let vec8 = vec![3, 4, 5, 6];
    let sym_diff = vec7.symmetric_difference(vec8);
    println!("对称差集结果: {:?}", sym_diff);

    // 6. 数组连接示例
    let vec9 = vec!["hello", "world"];
    let joined = vec9.join(", ");
    println!("连接结果: {}", joined);

    // 7. 数组填充示例
    let mut vec10 = vec![1, 2, 3];
    vec10.pad(5, &0);
    println!("填充结果: {:?}", vec10);
}

性能特点

array_tool在设计时考虑了性能:

  • 使用高效的算法实现集合操作
  • 避免不必要的内存分配
  • 提供原地操作和返回新数组两种选择

适用场景

  • 需要处理集合运算(并集、交集、差集等)
  • 需要快速去重或查找唯一元素
  • 需要更简洁的数组操作语法
  • 需要扩展标准库的数组功能

array_tool是Rust标准库数组功能的有力补充,特别适合需要频繁进行数组操作的项目。

回到顶部