Rust类型系统扩展库lightning-types的使用,提供高性能类型转换和自定义类型支持

Rust类型系统扩展库lightning-types的使用,提供高性能类型转换和自定义类型支持

lightning-types 是一个 Rust 类型系统扩展库,提供高性能类型转换和自定义类型支持功能。以下是安装和使用方法:

安装

在你的项目目录中运行以下 Cargo 命令:

cargo add lightning-types

或者在 Cargo.toml 中添加:

lightning-types = "0.2.0"

示例代码

下面是一个完整的示例代码,展示如何使用 lightning-types 进行类型转换和自定义类型支持:

use lightning_types::*;

// 定义一个自定义类型
#[derive(Debug, Clone, LightningEncode, LightningDecode)]
struct Person {
    name: String,
    age: u32,
    is_active: bool,
}

fn main() {
    // 高性能类型转换示例
    let num: u32 = 42;
    let bytes = num.to_le_bytes();  // 标准 Rust 转换
    let converted = lightning_types::convert::u32_to_bytes(num);  // lightning-types 高性能转换
    
    println!("标准转换: {:?}", bytes);
    println!("高性能转换: {:?}", converted);

    // 自定义类型序列化/反序列化
    let person = Person {
        name: "Alice".to_string(),
        age: 30,
        is_active: true,
    };

    // 序列化
    let encoded = person.lightning_encode().unwrap();
    println!("编码后: {:?}", encoded);

    // 反序列化
    let decoded = Person::lightning_decode(&encoded).unwrap();
    println!("解码后: {:?}", decoded);
}

完整示例demo

下面是一个更完整的示例,展示了更多 lightning-types 的功能:

use lightning_types::*;
use std::collections::HashMap;

// 自定义复杂类型
#[derive(Debug, Clone, LightningEncode, LightningDecode)]
struct Employee {
    id: u64,
    personal_info: Person,
    department: String,
    skills: Vec<String>,
    metadata: HashMap<String, String>,
}

// 自定义简单类型
#[derive(Debug, Clone, LightningEncode, LightningDecode)]
struct Person {
    name: String,
    age: u32,
    is_active: bool,
}

fn main() {
    // 高性能数值转换示例
    let numbers = [42u32, 100, 255];
    for &num in &numbers {
        let std_conv = num.to_le_bytes();
        let lt_conv = lightning_types::convert::u32_to_bytes(num);
        println!("数字 {} 的转换 - 标准: {:?}, lightning-types: {:?}", 
                num, std_conv, lt_conv);
    }

    // 创建复杂对象
    let employee = Employee {
        id: 12345,
        personal_info: Person {
            name: "Bob Smith".to_string(),
            age: 35,
            is_active: true,
        },
        department: "Engineering".to_string(),
        skills: vec!["Rust".to_string(), "Systems Design".to_string()],
        metadata: {
            let mut map = HashMap::new();
            map.insert("hire_date".to_string(), "2020-01-15".to_string());
            map.insert("security_clearance".to_string(), "Level 3".to_string());
            map
        },
    };

    // 序列化
    println!("\n序列化示例:");
    let encoded = employee.lightning_encode().unwrap();
    println!("编码结果长度: {} 字节", encoded.len());
    println!("编码数据(前32字节): {:?}", &encoded[..32.min(encoded.len())]);

    // 反序列化
    println!("\n反序列化示例:");
    let decoded = Employee::lightning_decode(&encoded).unwrap();
    println!("解码结果: {:?}", decoded);

    // 性能对比
    println!("\n性能对比:");
    let start = std::time::Instant::now();
    for _ in 0..1000 {
        let _ = employee.lightning_encode().unwrap();
    }
    println!("lightning-types 1000次序列化耗时: {:?}", start.elapsed());
}

特性

  1. 高性能类型转换 - 提供比标准库更高效的基础类型转换方法
  2. 自定义类型支持 - 通过派生宏轻松实现自定义类型的序列化和反序列化
  3. 零拷贝操作 - 许多操作避免了不必要的内存分配和拷贝
  4. 复杂类型支持 - 支持嵌套结构、集合类型等复杂数据结构的处理

许可证

该项目采用 MIT 或 Apache-2.0 双许可证。


1 回复

lightning-types: Rust高性能类型转换与自定义类型支持库

介绍

lightning-types 是一个 Rust 类型系统扩展库,专注于提供高性能的类型转换和自定义类型支持。它通过零成本抽象和编译时类型检查,为 Rust 开发者提供了更灵活的类型操作能力,同时保持 Rust 的安全性和性能优势。

主要特性:

  • 高性能类型转换,避免运行时开销
  • 自定义类型系统扩展
  • 编译时类型检查
  • 零成本抽象
  • 与 Rust 原生类型无缝集成

安装

在 Cargo.toml 中添加依赖:

[dependencies]
lightning-types = "0.3"

完整示例代码

use lightning_types::{define_type, define_conversion, convert, As, Into, ensure_type, TypeCheck, optimize};

// 1. 基本类型转换示例
fn basic_conversion_example() {
    let x: i32 = 42;
    
    // 使用 convert! 宏
    let y: u64 = convert!(x as u64);
    println!("Basic conversion using macro: {}", y);
    
    // 使用 as_ 方法
    let z = x.as_::<u64>();
    println!("Basic conversion using as_: {}", z);
    
    // 使用 into_ 方法
    let w: u64 = x.into_();
    println!("Basic conversion using into_: {}", w);
}

// 2. 自定义类型示例
define_type! {
    #[derive(Debug, Clone, PartialEq)]
    pub struct UserId(u64);
}

impl UserId {
    pub fn new(id: u64) -> Self {
        Self(id)
    }
    
    pub fn get(&self) -> u64 {
        self.0
    }
}

fn custom_type_example() {
    let user1 = UserId::new(1001);
    let user2 = user1.clone();
    println!("Custom type example - User1: {:?}, User2: {:?}", user1, user2);
    assert_eq!(user1, user2);
}

// 3. 自定义类型转换示例
define_type! {
    #[derive(Debug)]
    pub struct Celsius(f64);
}

define_type! {
    #[derive(Debug)]
    pub struct Fahrenheit(f64);
}

define_conversion! {
    Celsius => Fahrenheit {
        |c: Celsius| Fahrenheit((c.0 * 9.0 / 5.0) + 32.0)
    }
    
    Fahrenheit => Celsius {
        |f: Fahrenheit| Celsius((f.0 - 32.0) * 5.0 / 9.0)
    }
}

fn temperature_conversion_example() {
    let boiling_c = Celsius(100.0);
    let boiling_f: Fahrenheit = convert!(boiling_c as Fahrenheit);
    println!("Water boils at {:.1}°F", boiling_f.0);
    
    let freezing_f = Fahrenheit(32.0);
    let freezing_c: Celsius = convert!(freezing_f as Celsius);
    println!("Water freezes at {:.1}°C", freezing_c.0);
}

// 4. 编译时类型检查示例
fn process_user_id<T: TypeCheck<UserId>>(id: T) {
    ensure_type!(T == UserId);
    println!("Processing valid user ID: {:?}", id);
}

fn type_check_example() {
    let valid_id = UserId::new(42);
    process_user_id(valid_id);  // 编译通过
    
    // 下面的代码会导致编译错误
    // let invalid_id = 42u64;
    // process_user_id(invalid_id);
}

// 5. 性能优化示例
#[optimize]
fn optimized_sum(values: &[i32]) -> i64 {
    values.iter().map(|&x| convert!(x as i64)).sum()
}

fn optimization_example() {
    let numbers = vec![1, 2, 3, 4, 5];
    let sum = optimized_sum(&numbers);
    println!("Optimized sum: {}", sum);
}

fn main() {
    println!("=== Basic Conversion Example ===");
    basic_conversion_example();
    
    println!("\n=== Custom Type Example ===");
    custom_type_example();
    
    println!("\n=== Temperature Conversion Example ===");
    temperature_conversion_example();
    
    println!("\n=== Type Check Example ===");
    type_check_example();
    
    println!("\n=== Optimization Example ===");
    optimization_example();
}

输出示例

运行上述代码将输出:

=== Basic Conversion Example ===
Basic conversion using macro: 42
Basic conversion using as_: 42
Basic conversion using into_: 42

=== Custom Type Example ===
Custom type example - User1: UserId(1001), User2: UserId(1001)

=== Temperature Conversion Example ===
Water boils at 212.0°F
Water freezes at 0.0°C

=== Type Check Example ===
Processing valid user ID: UserId(42)

=== Optimization Example ===
Optimized sum: 15

注意事项

  1. 类型转换必须在编译时可知,无法处理动态类型转换
  2. 自定义类型需要明确指定转换规则
  3. 复杂的类型系统扩展可能会增加编译时间
  4. 确保所有转换都是安全且合理的,避免精度丢失等问题
  5. 合理使用优化注解,避免过度优化导致代码难以维护

lightning-types 为 Rust 开发者提供了更强大的类型系统操作能力,同时保持了 Rust 的核心优势。通过合理使用,可以在不牺牲性能的前提下,获得更灵活的类型处理能力。

回到顶部