| Crates.io | wstr-literal |
| lib.rs | wstr-literal |
| version | 0.1.1 |
| created_at | 2025-08-25 13:03:26.597253+00 |
| updated_at | 2025-08-26 08:57:16.453393+00 |
| description | Proc macros for building UTF-16 null-terminated arrays at compile time. |
| homepage | |
| repository | https://github.com/vabock/wstr-literal |
| max_upload_size | |
| id | 1809556 |
| size | 27,192 |
Procedural macros for building UTF-16 null-terminated string arrays for Windows FFI and similar APIs at compile time.
This crate provides two macros:
wstr!] — a function-like macro that converts a string literal to a UTF-16 array with a trailing null (0u16). Optionally accepts an explicit array length and pads with zeros.wstr_literal] — an attribute macro for const or static declaration that transforms a string-literal into a UTF-16 array with a trailing null. Supports either a fixed array length or an inferred length via placeholder(_).Both macros expand at compile time into numeric [u16; N] array literals; there is no runtime allocation or conversion.
Add this crate to your Cargo.toml:
[dependencies]
wstr-literal = "0.1"
use wstr_literal::{wstr_literal, wstr};
// Exact-length array (5 code units + 1 null terminator)
let hello: [u16; 6] = wstr!("Hello");
assert_eq!(hello, [
'H' as u16, 'e' as u16, 'l' as u16, 'l' as u16, 'o' as u16, 0
]);
// Pad to a larger, fixed length
let padded: [u16; 10] = wstr!(10, "hello");
assert_eq!(&padded[..6], &[0x68, 0x65, 0x6c, 0x6c, 0x6f, 0]);
assert_eq!(&padded[6..], &[0u16; 4]);
// Slice
let slice: &[u16] = &wstr!("Hi");
assert_eq!(slice, &[0x48, 0x69, 0]);
#[wstr_literal]
const HELLO: [u16; _] = "hello"; // length inferred (5 + 1)
assert_eq!(HELLO.len(), 6);
#[wstr_literal]
static HELLO_PADDED: [u16; 0x10] = "hello"; // padded with zeros to length 0x10
assert_eq!(&HELLO_PADDED[..6], &[0x68, 0x65, 0x6c, 0x6c, 0x6f, 0]);
assert_eq!(&HELLO_PADDED[6..], &[0u16; 10]); // padding
// supports const/static, visibility, mutability, and other attributes
#[wstr_literal]
#[allow(non_upper_case_globals)]
pub static mut GlobalMut: [u16; _] = "x";
These arrays are suitable for FFI calls expecting UTF-16 with a trailing null, for example with windows crate:
use wstr_literal::wstr_literal;
use windows::core::PCWSTR;
#[wstr_literal]
static APP_NAME: [u16; _] = "MyApp";
let pcwstr = PCWSTR(APP_NAME.as_ptr());
// pass `pcwstr` to Windows APIs that expect a wide string
This macro was inspired by auto-const-array crate.