Skip to content

Instantly share code, notes, and snippets.

@rust-play
Created January 24, 2020 15:37
Show Gist options
  • Save rust-play/d4d3450b8c55f98b2783c5e983633911 to your computer and use it in GitHub Desktop.
Save rust-play/d4d3450b8c55f98b2783c5e983633911 to your computer and use it in GitHub Desktop.
Code shared from the Rust Playground
use std::mem::ManuallyDrop;
use std::convert::TryInto;
fn main() {
let mut a = String::with_capacity(50);
a.push_str("öäasdkflieojf");
let (b,c) = unsafe{split(a, 4)};
println!("{} and {}, capacities: {}, {}", b, c, b.capacity(), c.capacity());
}
/// Safety: at needs to be at a valid utf-8 boundary
unsafe fn split(s: String, at: usize) -> (String, String) {
// Prevent automatically dropping the String's data
let mut s = ManuallyDrop::new(s);
let ptr = s.as_mut_ptr();
let len = s.len();
let capacity = s.capacity();
let s1 = String::from_raw_parts(ptr, at, at);
let s2 = String::from_raw_parts(ptr.offset(at.try_into().unwrap()), len - at, capacity - at);
(s1,s2)
}
// Doesn't work yet
fn split_whitespace_owned(s: String) -> Vec<String> {
// Prevent automatically dropping the String's data
let mut s = ManuallyDrop::new(s);
let ptr = s.as_mut_ptr();
let len = s.len();
let capacity = s.capacity();
let offsets = s.split_whitespace().map(|x| {
let start =
(x.as_ptr() as isize - s.as_ptr() as isize) as usize;
let end = start + x.len();
(start, end)
});
Vec::new()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment