writeln!(w, "#[no_mangle]").unwrap();
writeln!(w, "/// Read a {} object from a string", ident).unwrap();
writeln!(w, "pub extern \"C\" fn {}_from_str(s: crate::c_types::Str) -> {} {{", ident, container).unwrap();
- writeln!(w, "\tmatch {}::from_str(s.into()) {{", resolved_path).unwrap();
+ writeln!(w, "\tmatch {}::from_str(s.into_str()) {{", resolved_path).unwrap();
writeln!(w, "\t\tOk(r) => {{").unwrap();
let new_var = types.write_to_c_conversion_new_var(w, &format_ident!("r"), &*i.self_ty, Some(&gen_types), false);
write!(w, "\t\t\tcrate::c_types::CResultTempl::ok(\n\t\t\t\t").unwrap();
"[u8; 3]" if !is_ref => Some("crate::c_types::ThreeBytes"), // Used for RGB values
"str" if is_ref => Some("crate::c_types::Str"),
- "String" if !is_ref => Some("crate::c_types::derived::CVec_u8Z"),
- "String" if is_ref => Some("crate::c_types::Str"),
+ "String" => Some("crate::c_types::Str"),
"std::time::Duration" => Some("u64"),
"std::time::SystemTime" => Some("u64"),
"[usize]" if is_ref => Some(""),
"str" if is_ref => Some(""),
- "String" if !is_ref => Some("String::from_utf8("),
+ "String" => Some(""),
// Note that we'll panic for String if is_ref, as we only have non-owned memory, we
// cannot create a &String.
"[u8]" if is_ref => Some(".to_slice()"),
"[usize]" if is_ref => Some(".to_slice()"),
- "str" if is_ref => Some(".into()"),
- "String" if !is_ref => Some(".into_rust()).unwrap()"),
+ "str" if is_ref => Some(".into_str()"),
+ "String" => Some(".into_string()"),
"std::time::Duration" => Some(")"),
"std::time::SystemTime" => Some("))"),
"[usize]" if is_ref => Some(""),
"str" if is_ref => Some(".into()"),
- "String" if !is_ref => Some(".into_bytes().into()"),
"String" if is_ref => Some(".as_str().into()"),
+ "String" => Some(".into()"),
"std::time::Duration" => Some(".as_secs()"),
"std::time::SystemTime" => Some(".duration_since(::std::time::SystemTime::UNIX_EPOCH).expect(\"Times must be post-1970\").as_secs()"),
Str { chars: self.as_ptr(), len: self.len(), chars_is_owned: false }
}
}
-impl Into<&'static str> for Str {
- fn into(self) -> &'static str {
+impl Str {
+ pub(crate) fn into_str(&self) -> &'static str {
if self.len == 0 { return ""; }
std::str::from_utf8(unsafe { std::slice::from_raw_parts(self.chars, self.len) }).unwrap()
}
+ pub(crate) fn into_string(self) -> String {
+ let bytes = if self.len == 0 {
+ Vec::new()
+ } else if self.chars_is_owned {
+ unsafe {
+ Box::from_raw(std::slice::from_raw_parts_mut(unsafe { self.chars as *mut u8 }, self.len))
+ }.into()
+ } else {
+ let mut ret = Vec::with_capacity(self.len);
+ ret.extend_from_slice(unsafe { std::slice::from_raw_parts(self.chars, self.len) });
+ ret
+ };
+ String::from_utf8(bytes).unwrap()
+ }
}
impl Into<Str> for String {
fn into(self) -> Str {