Skip to content

Instantly share code, notes, and snippets.

@luser
Created December 7, 2020 15:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save luser/80dc1e17981607c6241234454d4bf570 to your computer and use it in GitHub Desktop.
Save luser/80dc1e17981607c6241234454d4bf570 to your computer and use it in GitHub Desktop.
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