1 /* 2 * Copyright (C) 2023 Huawei Device Co., Ltd. 3 * Licensed under the Apache License, Version 2.0 (the "License"); 4 * you may not use this file except in compliance with the License. 5 * You may obtain a copy of the License at 6 * 7 * http://www.apache.org/licenses/LICENSE-2.0 8 * 9 * Unless required by applicable law or agreed to in writing, software 10 * distributed under the License is distributed on an "AS IS" BASIS, 11 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 * See the License for the specific language governing permissions and 13 * limitations under the License. 14 */ 15 16 use std::ffi::{CString, c_char}; 17 18 /// Translate a &str to &[c_char; N]. trans_slice_to_array(src: &str, dest: &mut [c_char])19pub fn trans_slice_to_array(src: &str, dest: &mut [c_char]) { 20 let name = CString::new(src).unwrap(); 21 let name = name.to_bytes(); 22 let name_len = name.len(); 23 let end = if name_len <= dest.len() { 24 name_len 25 } else { 26 dest.len() 27 }; 28 dest[..end].copy_from_slice(&name[..end]) 29 } 30 31 /// recycle CString as raw pointer. 32 /// 33 /// # Safety 34 /// 35 /// The memory which this pointer point to is allocated in rust end, risk under control 36 /// 37 #[allow(dead_code)] free_allocated_str(ptr: *mut c_char)38pub fn free_allocated_str(ptr: *mut c_char) { 39 if ptr.is_null() { 40 return; 41 } 42 unsafe { 43 let _ = CString::from_raw(ptr); 44 } 45 }