use std::char::{decode_utf16, DecodeUtf16Error}; | |
#[allow(non_camel_case_types)] | |
pub struct wstr([u16]); | |
impl wstr { | |
pub fn to_wstring(&self) -> WString { | |
self.to_owned() | |
} | |
pub fn to_string(&self) -> String { | |
String::from_utf16(&self.0).unwrap() | |
} | |
} | |
impl AsRef<[u16]> for wstr { | |
fn as_ref(&self) -> &[u16] { | |
&self.0 | |
} | |
} | |
impl ToOwned for wstr { | |
type Owned = WString; | |
fn to_owned(&self) -> WString { | |
WString { vec: self.0.to_owned() } | |
} | |
} | |
pub unsafe fn from_utf16_unchecked(v: &[u16]) -> &wstr { | |
&*(v as *const [u16] as *const wstr) | |
} | |
pub fn from_utf16(v: &[u16]) -> Result<&wstr, DecodeUtf16Error> { | |
match decode_utf16(v.iter().cloned()).find_map(|e| e.err()) { | |
Some(e) => Err(e), | |
None => Ok(unsafe { from_utf16_unchecked(v) }), | |
} | |
} | |
pub struct WString { | |
vec: Vec<u16>, | |
} | |
impl WString { | |
pub const fn new() -> WString { | |
WString { vec: Vec::new() } | |
} | |
#[inline] | |
pub fn from_str(s: &str) -> WString { | |
let vec = s.encode_utf16().collect(); | |
WString { vec } | |
} | |
#[inline] | |
pub fn from_utf16(vec: Vec<u16>) -> Result<WString, DecodeUtf16Error> { | |
match from_utf16(&vec) { | |
Ok(..) => Ok(WString { vec }), | |
Err(e) => Err(e), | |
} | |
} | |
#[inline] | |
pub unsafe fn from_utf16_unchecked(bytes: Vec<u16>) -> WString { | |
WString { vec: bytes } | |
} | |
} | |
impl AsRef<wstr> for WString { | |
fn as_ref(&self) -> &wstr { | |
self.borrow() | |
} | |
} | |
impl Borrow<wstr> for WString { | |
fn borrow(&self) -> &wstr { | |
let v: &[u16] = &self.vec[..]; | |
unsafe { std::mem::transmute(v) } | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment