4 个版本
使用旧的 Rust 2015
0.2.2 | 2018 年 9 月 17 日 |
---|---|
0.2.1 | 2018 年 9 月 17 日 |
0.2.0 | 2018 年 9 月 17 日 |
0.1.0 | 2017 年 11 月 29 日 |
1431 在 数据结构 中
9KB
146 行
字节序列
此软件包提供了一些创建字节序列(如 ApiKeys 或 SessionIds)的实用程序。它包含一个宏,允许您指定序列的名称和字节长度。然后,该宏创建一个具有以下方法的结构体:
fn generate_new() -> Self
fn to_string() -> String
fn check(key: &str) -> std::result::Result<Self, failure::Error>;
它还实现了 Display
、Debug
、serde::Serialize
、serde::Deserialize
、PartialOrd
、Ord
、PartialEq
、Eq
、Clone
、Copy
和 Hash
;
完整示例
#[macro_use]
extern crate byte_sequence;
extern crate rand;
use serde;
use std;
use byte_sequence::Checkable;
byte_seq!(ApiKey; 32);
#[test]
fn example() {
// Creates a new ApiKey containing 32 random bytes using a thread_rng
let key = ApiKey::generate_new();
// The to_string method creates a hex encoded string:
// i.e. 'BBC47F308F3D02C3C6C3D6C9555296A64407FE72AD92DE8C7344D610CFFABF67'
assert_eq!(key.to_string().len(), 64);
// you can also do it the other way around: Parse a string into an ApiKey
let key = ApiKey::check("BBC47F308F3D02C3C6C3D6C9555296A64407FE72AD92DE8C7344D610CFFABF67").unwrap();
assert_eq!(key.to_string(), "BBC47F308F3D02C3C6C3D6C9555296A64407FE72AD92DE8C7344D610CFFABF67");
}
您还可以扩展生成的结构体。例如,添加 ApiKey 的公共部分
impl ApiKey {
pub fn public_part(&self) -> PublicApiKey {
let mut pub_data = [0u8; 8];
pub_data.copy_from_slice(&self.0[0..8]);
PublicApiKey(pub_data)
}
}
依赖项
~550–800KB
~15K SLoC