expand_array

Crates.ioexpand_array
lib.rsexpand_array
version0.2.0
sourcesrc
created_at2024-05-17 10:34:48.890032
updated_at2024-05-18 02:33:17.507943
descriptionMacro to convert a static array to a fixed-size array
homepage
repositoryhttps://github.com/acovaci/expand-array-rust-macro
max_upload_size
id1243018
size30,053
Adrian Covaci (acovaci)

documentation

README

Expand Array Rust Macro

This crate provides a macro called arr! to convert a static array to a fixed-size array. Limited type conversion is supported. This is useful when you need to make available global constants in a dynamic library, for example.

As a bonus, the crate also provides a bitify! macro to convert a string literal to a fixed-size array of bytes.

Usage

The arr! macro can take any two primitive types. On top of that, it can take string literals (&str, byte strings and C strings). Using the bitify! macro, it can convert it to a fixed-size array of any primitive type.

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>);

Example

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]);
Commit count: 23

cargo fmt