General internal routine to copy bytes from a C array into a Rust String
(bytes: *const ::std::os::raw::c_char, max_length: usize)
| 256 | |
| 257 | // General internal routine to copy bytes from a C array into a Rust String |
| 258 | fn string_from_bytes(bytes: *const ::std::os::raw::c_char, max_length: usize) -> Result<String> { |
| 259 | let mut newbytes = vec![0u8; max_length]; |
| 260 | |
| 261 | // Get length of the string in old-fashioned style |
| 262 | let mut length: usize = 0; |
| 263 | let mut count = 0; |
| 264 | let mut tmpbytes = bytes; |
| 265 | while count < max_length || length == 0 { |
| 266 | if unsafe { *tmpbytes } == 0 && length == 0 { |
| 267 | length = count; |
| 268 | break; |
| 269 | } |
| 270 | count += 1; |
| 271 | tmpbytes = unsafe { tmpbytes.offset(1) } |
| 272 | } |
| 273 | |
| 274 | // Cope with an empty string |
| 275 | if length == 0 { |
| 276 | return Ok(String::new()); |
| 277 | } |
| 278 | |
| 279 | unsafe { |
| 280 | // We need to fully copy it, not shallow copy it. |
| 281 | // Messy casting on both parts of the copy here to get it to work on both signed |
| 282 | // and unsigned char machines |
| 283 | copy_nonoverlapping(bytes as *mut i8, newbytes.as_mut_ptr() as *mut i8, length); |
| 284 | } |
| 285 | |
| 286 | let cs = match CString::new(&newbytes[0..length]) { |
| 287 | Ok(c1) => c1, |
| 288 | Err(_) => return Err(CsError::CsErrRustString), |
| 289 | }; |
| 290 | |
| 291 | // This is just to convert the error type |
| 292 | match cs.into_string() { |
| 293 | Ok(s) => Ok(s), |
| 294 | Err(_) => Err(CsError::CsErrRustString), |
| 295 | } |
| 296 | } |
no outgoing calls
no test coverage detected