2 个不稳定版本
0.2.0 | 2024 年 5 月 18 日 |
---|---|
0.1.0 | 2024 年 5 月 17 日 |
#280 in FFI
35 每月下载量
11KB
164 代码行
Expand Array Rust 宏
此 crate 提供了一个名为 arr!
的宏,用于将静态数组转换为固定大小的数组。支持有限的类型转换。当您需要将全局常量在动态库中可用时,这很有用,例如。
作为额外功能,该 crate 还提供了一个 bitify!
宏,用于将字符串字面量转换为固定大小的字节数组。
用法
arr!
宏可以接受任何两种原始类型。除此之外,它还可以接受字符串字面量(&str
,字节字符串和 C 字符串)。使用 bitify!
宏,它可以将其转换为任何原始类型的固定大小数组。
use expand_array::arrr;
let var: [<target_type>; target_len] = arrr!(<source> as [<target_type>; target_len]);
let var_with_default: [<target_type>; target_len] = arrr!(<source> as [<target_type>; target_len] with <default_value>);
示例
use expand_array::arrr;
let arr: [u8; 10] = arrr!([1, 2, 3, 4, 5] as [u8; 10]);
assert_eq!(arr, [1, 2, 3, 4, 5, 0, 0, 0, 0, 0]);
let arr: [u8; 10] = arrr!([1, 2, 3, 4, 5] as [u8; 10] with 2);
assert_eq!(arr, [1, 2, 3, 4, 5, 2, 2, 2, 2, 2]);
let arr: [u8; 10] = arrr!(b"Hello" as [u8; 10]);
assert_eq!(arr, [72, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [u8; 10] = arrr!("Hello" as [u8; 10]);
assert_eq!(arr, [72, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [char; 10] = arrr!(['H', 'e', 'l', 'l', 'o'] as [char; 10]);
assert_eq!(arr, ['H', 'e', 'l', 'l', 'o', '\0', '\0', '\0', '\0', '\0']);
let arr: [&str; 10] = arrr!(["Hello", "world"] as [&str; 10] with '!');
assert_eq!(arr, ["Hello", "world", "!", "!", "!", "!", "!", "!", "!", "!"]);
use ::std::ffi::c_char;
let arr: [c_char; 10] = arrr!([72i8, 101, 108, 108, 111] as [c_char; 10]);
assert_eq!(arr, [72i8, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [c_char; 10] = arrr!(c"Hello" as [c_char; 10]);
assert_eq!(arr, [72i8, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [c_char; 10] = arrr!([72u8, 101, 108, 108, 111] as [c_char; 10]);
assert_eq!(arr, [72i8, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [c_char; 10] = arrr!([b'H', b'e', b'l', b'l', b'o'] as [c_char; 10]);
assert_eq!(arr, [72i8, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [c_char; 10] = arrr!(b"Hello" as [c_char; 10]);
assert_eq!(arr, [72i8, 101, 108, 108, 111, 0, 0, 0, 0, 0]);
let arr: [c_char; 10] = arrr!("Hello" as [c_char; 10] with "!");
assert_eq!(arr, [72i8, 101, 108, 108, 111, 33, 33, 33, 33, 33]);