Last active
December 18, 2017 12:36
-
-
Save nagisa/ef7df0a048504c23b9ac to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#![feature(unicode, core_intrinsics)] | |
struct MyString(String); | |
impl From<Vec<char>> for MyString { | |
fn from(mut chars: Vec<char>) -> MyString { | |
let mut bytes_used = 0usize; | |
let length = chars.len(); | |
for index in 0..length { | |
let current_char = unsafe { *chars.get_unchecked(index) }; | |
let output_buf: &mut [u8] = unsafe { | |
::std::slice::from_raw_parts_mut( | |
(chars.as_mut_ptr() as *mut _).offset(bytes_used as isize), | |
(index + 1) * ::std::mem::size_of::<char>() - bytes_used | |
) | |
}; | |
bytes_used += current_char.encode_utf8(output_buf).unwrap_or_else(|| | |
unsafe { ::std::intrinsics::unreachable() } | |
); | |
} | |
let vecdata = chars.as_mut_ptr() as *mut _; | |
::std::mem::forget(chars); | |
unsafe { MyString(String::from_raw_parts( | |
vecdata, | |
bytes_used, | |
length * ::std::mem::size_of::<char>() | |
)) } | |
} | |
} | |
fn main() { | |
let a = vec!['a', 'b', 'c', '∀', 'ą', 'a', '😃']; | |
let b: MyString = a.into(); | |
println!("{}", b.0); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment