#不可变 #正则表达式 # #包装器 #字符串 #验证 #类型

valistr

使用正则表达式验证的值创建不可变字符串包装类型。

1个不稳定版本

0.1.0 2024年7月8日

1226算法

Download history 108/week @ 2024-07-06 9/week @ 2024-07-13 10/week @ 2024-07-27

每月下载 127次

MIT 许可证

6KB

valistr

使用正则表达式验证的值创建不可变字符串包装类型。

TL;DR

use valistr::valistr;

/// A valid identifier in PascalCase. The regex used here is not perfect, but it's good enough for demonstration.
#[valistr(r"([A-Z][a-z0-9]*)+")]
struct PascalCaseId;

#[valistr(r"(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})")]
struct Date;

fn main() {
    // Create it with `new` method.
    let id = PascalCaseId::new("HelloWorld").unwrap();

    // `Debug` and `Display` are implemented.
    assert_eq!(format!("{}", id), "HelloWorld");
    assert_eq!(format!("{:?}", id), "\"HelloWorld\"");

    // `Deref<Target = String>` is implemented, so methods of `String` can be called directly.
    assert_eq!(id.as_str(), "HelloWorld");

    // `new` returns `None` if the input is not valid.
    assert!(PascalCaseId::new("helloWorld").is_none());

    // `TryFrom<&str>` and `TryFrom<String>` is also implemented.
    assert!(PascalCaseId::try_from("HelloWorld").is_ok());
    assert!(PascalCaseId::try_from("hello_world".to_string()).is_err());

    // For each named capture group `x`, a method `fn get_x(&self) -> Option<&str>` is provided.
    //
    // Note that the method will be generated only if the name matches `[a-z][a-z0-9_]*`. This 
    // constraint guarantees the generated method name is a valid and clean Rust identifier.
    let date = Date::new("2023-08-18").unwrap();
    assert_eq!(date.get_year().unwrap(), "2023");
    assert_eq!(date.get_month().unwrap(), "08");
    assert_eq!(date.get_day().unwrap(), "18");
}

依赖

~2.4–4MB
~71K SLoC