1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
// Copyright takubokudori.
// This source code is licensed under the MIT or Apache-2 license.
//! # Windy
//!
//! Windows strings library
//!
//! This crate supports AString (ANSI string) and WString (Unicode string).
//!
//! # Features
//!
//! - ANSI string(AString)
//! - Unicode string(WString)
//! - Interconversion between AString, WString and String.
//!
//! # Example
//!
//! ```rust
//! use windy::*;
//!
//! #[allow(non_snake_case)]
//! extern "system" {
//!     fn GetEnvironmentVariableA(lpName: *const u8, lpBuffer: *mut u8, nSize: u32) -> u32;
//!     fn GetEnvironmentVariableW(lpName: *const u16, lpBuffer: *mut u16, nSize: u32) -> u32;
//! }
//!
//! fn get_environment_variable_a() {
//!     let name = AString::from_str("PATH").unwrap();
//!     let mut buf = Vec::with_capacity(0x1000);
//!     unsafe {
//!         let l = GetEnvironmentVariableA(
//!             name.as_ptr(),
//!             buf.as_mut_ptr(),
//!             0x1000);
//!         if l == 0 {
//!             println!("GetEnvironmentVariableA failed");
//!             return;
//!         }
//!         buf.set_len(l as usize);
//!         let value = AString::new_unchecked(buf);
//!         println!("value: {}", value.to_string_lossy());
//!     }
//! }
//!
//! fn get_environment_variable_w() {
//!     let name = WString::from_str("PATH").unwrap();
//!     let mut buf = Vec::with_capacity(0x1000);
//!     unsafe {
//!         let l = GetEnvironmentVariableW(
//!             name.as_ptr(),
//!             buf.as_mut_ptr(),
//!             0x1000);
//!         if l == 0 {
//!             println!("GetEnvironmentVariableW failed");
//!             return;
//!         }
//!         buf.set_len(l as usize);
//!         let value = WString::new_unchecked(buf);
//!         println!("value: {}", value.to_string_lossy());
//!     }
//! }
//!
//! fn main() {
//!     println!("*****get_environment_variable_a*****");
//!     get_environment_variable_a();
//!     println!("*****get_environment_variable_w*****");
//!     get_environment_variable_w();
//! }
//! ```
//!
//! # License
//!
//! This software is released under the MIT or Apache-2.0 License, see LICENSE-MIT or LICENSE-APACHE.
#![cfg(windows)]

mod raw;
mod string;

pub use string::*;
use raw::*;
use std::fmt;
use std::ptr::{null, null_mut};

/// Represents a conversion error.
#[derive(Copy, Clone, Ord, PartialOrd, Eq, PartialEq)]
pub enum ConvertError {
    /// Failed to convert to UTF-8 string.
    ConvertToUtf8Error(u32),
    /// Failed to convert to ANSI string.
    ConvertToAnsiError(u32),
    /// Failed to convert to Unicode string.
    ConvertToUnicodeError(u32),
}

impl ConvertError {
    /// Returns a os error code.
    #[inline]
    pub fn to_error_code(&self) -> u32 {
        match self {
            Self::ConvertToUtf8Error(x) => *x,
            Self::ConvertToAnsiError(x) => *x,
            Self::ConvertToUnicodeError(x) => *x,
        }
    }
}

impl fmt::Debug for ConvertError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let st = match self {
            Self::ConvertToUtf8Error(_) => "ConvertToUtf8Error",
            Self::ConvertToAnsiError(_) => "ConvertToAnsiError",
            Self::ConvertToUnicodeError(_) => "ConvertToUnicodeError",
        };
        let e = std::io::Error::from_raw_os_error(self.to_error_code() as i32);
        f.debug_struct(st)
            .field("", &e)
            .finish()
    }
}

impl std::error::Error for ConvertError {}

impl fmt::Display for ConvertError {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        format!("{:?}", self).fmt(f)
    }
}

impl Into<u32> for ConvertError {
    fn into(self) -> u32 {
        self.to_error_code()
    }
}

impl Into<i32> for ConvertError {
    fn into(self) -> i32 {
        self.to_error_code() as i32
    }
}

#[macro_export]
macro_rules! conv_err {
    (@utf8 $e:expr) => (ConvertError::ConvertToUtf8Error($e));
    (@ansi $e:expr) => (ConvertError::ConvertToAnsiError($e));
    (@unicode $e:expr) => (ConvertError::ConvertToUnicodeError($e));
}

pub type ConvertResult<T> = Result<T, ConvertError>;

pub(crate) type OsResult<T> = Result<T, u32>;

#[inline(always)]
#[allow(non_snake_case)]
pub(crate) unsafe fn MultiByteToWideChar(
    CodePage: UINT,
    dwFlags: DWORD,
    lpMultiByteStr: LPCSTR,
    cbMultiByte: c_int,
    lpWideCharStr: LPWSTR,
    cchWideChar: c_int,
) -> OsResult<c_int> {
    match crate::raw::MultiByteToWideChar(
        CodePage,
        dwFlags,
        lpMultiByteStr,
        cbMultiByte,
        lpWideCharStr,
        cchWideChar,
    ) {
        0 => Err(GetLastError()),
        x => Ok(x),
    }
}

#[inline(always)]
#[allow(non_snake_case)]
pub(crate) unsafe fn WideCharToMultiByte(
    CodePage: UINT,
    dwFlags: DWORD,
    lpWideCharStr: LPCWSTR,
    cchWideChar: c_int,
    lpMultiByteStr: LPSTR,
    cbMultiByte: c_int,
    lpDefaultChar: LPCSTR,
    lpUsedDefaultChar: LPBOOL,
) -> OsResult<c_int> {
    match crate::raw::WideCharToMultiByte(
        CodePage,
        dwFlags,
        lpWideCharStr,
        cchWideChar,
        lpMultiByteStr,
        cbMultiByte,
        lpDefaultChar,
        lpUsedDefaultChar,
    ) {
        0 => Err(GetLastError()),
        x => Ok(x),
    }
}

/// Safe wrapper function of MultiByteToWideChar.
#[inline(always)]
pub(crate) fn multi_byte_to_wide_char(
    code_page: UINT,
    mb_flags: DWORD,
    mb_bytes: &[u8],
    wc_bytes: &mut [u16],
) -> OsResult<usize> {
    unsafe {
        MultiByteToWideChar(
            code_page,
            mb_flags,
            mb_bytes.as_ptr() as *const i8,
            mb_bytes.len() as i32,
            wc_bytes.as_mut_ptr(),
            wc_bytes.len() as i32,
        ).and_then(|x| Ok(x as usize))
    }
}

/// Safe wrapper function of WideCharToMultiByte.
#[inline(always)]
pub(crate) fn wide_char_to_multi_byte<'a, DC, UDC>(
    code_page: UINT,
    wc_flags: DWORD,
    wc_bytes: &[u16],
    mb_bytes: &mut [u8],
    default_char: DC,
    used_default_char: UDC,
) -> OsResult<usize>
    where
        DC: Into<Option<char>>,
        UDC: Into<Option<&'a mut bool>>
{
    let dc = default_char.into().map_or(null(), |x| &x);
    unsafe {
        WideCharToMultiByte(
            code_page,
            wc_flags,
            wc_bytes.as_ptr(),
            wc_bytes.len() as i32,
            mb_bytes.as_mut_ptr() as *mut i8,
            mb_bytes.len() as i32,
            dc as *const i8,
            used_default_char.into().map_or(null_mut(), |x| x as *mut _ as *mut _),
        ).and_then(|x| Ok(x as usize))
    }
}