winres_edit/
utils.rs

1use windows::Win32::Foundation::{GetLastError, WIN32_ERROR};
2
3/// Convert a string to a zero-terminated [`windows::core::PCSTR`] string.
4#[macro_export]
5macro_rules! pcstr {
6    ($s:expr) => {
7        windows::core::PCSTR::from_raw(format!("{}\0", $s).as_ptr())
8    };
9}
10pub(crate) use pcstr;
11
12/// Get last windows error code
13pub(crate) fn get_last_error() -> WIN32_ERROR {
14    unsafe { GetLastError() }
15}
16
17// /// Convert utf16 string to a zero-terminated `Vec<u16>`
18// pub fn utf16sz_to_u16vec(text: &String) -> Vec<u16> {
19//     let len = text.len()+1;
20//     let mut vec: Vec<u16> = Vec::with_capacity(len);
21//     vec.resize(len,0);
22//     for c in text.chars() {
23//         // TODO - proper encoding
24//         // let buf = [0;2];
25//         // c.encode_utf16(&mut buf);
26//         vec.push(c as u16);
27//     }
28//     vec.push(0);
29//     vec
30// }
31
32/// This function convers a string to a zero-terminated
33/// `u16` unicode string represented by a `Vec<u8>` buffer.
34pub(crate) fn string_to_u8vec_sz(text: &String) -> Vec<u8> {
35    let len = text.len() + 1;
36    let mut u16vec: Vec<u16> = Vec::with_capacity(len);
37    // u16vec.resize(len,0);
38    for c in text.chars() {
39        // TODO - proper encoding
40        // let buf = [0;2];
41        // c.encode_utf16(&mut buf);
42        u16vec.push(c as u16);
43    }
44    u16vec.push(0);
45    let len = len * 2;
46    let mut u8vec = vec![0; len];
47    let src = unsafe { std::mem::transmute(u16vec.as_ptr()) };
48    let dest = u8vec[0..].as_mut_ptr();
49    unsafe {
50        std::ptr::copy(src, dest, len);
51    }
52    u8vec
53}
54
55/// Convert `u32` (DWORD) slice to a `Vec<u8>` buffer.
56pub(crate) fn u32slice_to_u8vec(u32slice: &[u32]) -> Vec<u8> {
57    let len = u32slice.len() * 4;
58    let mut u8vec = vec![0; len];
59    let src = unsafe { std::mem::transmute(u32slice.as_ptr()) };
60    let dest = u8vec[0..].as_mut_ptr();
61    unsafe {
62        std::ptr::copy(src, dest, len);
63    }
64    u8vec
65}